GUI and metadata for external audio.
[dcpomatic.git] / src / lib / film.cc
1 /*
2     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <stdexcept>
21 #include <iostream>
22 #include <algorithm>
23 #include <fstream>
24 #include <cstdlib>
25 #include <sstream>
26 #include <iomanip>
27 #include <unistd.h>
28 #include <boost/filesystem.hpp>
29 #include <boost/algorithm/string.hpp>
30 #include <boost/lexical_cast.hpp>
31 #include <boost/date_time.hpp>
32 #include "film.h"
33 #include "format.h"
34 #include "imagemagick_encoder.h"
35 #include "job.h"
36 #include "filter.h"
37 #include "transcoder.h"
38 #include "util.h"
39 #include "job_manager.h"
40 #include "ab_transcode_job.h"
41 #include "transcode_job.h"
42 #include "scp_dcp_job.h"
43 #include "copy_from_dvd_job.h"
44 #include "make_dcp_job.h"
45 #include "log.h"
46 #include "options.h"
47 #include "exceptions.h"
48 #include "examine_content_job.h"
49 #include "scaler.h"
50 #include "decoder_factory.h"
51 #include "config.h"
52 #include "check_hashes_job.h"
53 #include "version.h"
54 #include "ui_signaller.h"
55
56 using std::string;
57 using std::stringstream;
58 using std::multimap;
59 using std::pair;
60 using std::map;
61 using std::vector;
62 using std::ifstream;
63 using std::ofstream;
64 using std::setfill;
65 using std::min;
66 using std::make_pair;
67 using boost::shared_ptr;
68 using boost::lexical_cast;
69 using boost::to_upper_copy;
70 using boost::ends_with;
71 using boost::starts_with;
72
73 /** Construct a Film object in a given directory, reading any metadata
74  *  file that exists in that directory.  An exception will be thrown if
75  *  must_exist is true and the specified directory does not exist.
76  *
77  *  @param d Film directory.
78  *  @param must_exist true to throw an exception if does not exist.
79  */
80
81 Film::Film (string d, bool must_exist)
82         : _use_dci_name (false)
83         , _dcp_content_type (0)
84         , _format (0)
85         , _scaler (Scaler::from_id ("bicubic"))
86         , _dcp_trim_start (0)
87         , _dcp_trim_end (0)
88         , _dcp_ab (false)
89         , _use_source_audio (true)
90         , _audio_stream (-1)
91         , _audio_gain (0)
92         , _audio_delay (0)
93         , _still_duration (10)
94         , _subtitle_stream (-1)
95         , _with_subtitles (false)
96         , _subtitle_offset (0)
97         , _subtitle_scale (1)
98         , _audio_sample_rate (0)
99         , _has_subtitles (false)
100         , _frames_per_second (0)
101         , _dirty (false)
102 {
103         /* Make state.directory a complete path without ..s (where possible)
104            (Code swiped from Adam Bowen on stackoverflow)
105         */
106         
107         boost::filesystem::path p (boost::filesystem::system_complete (d));
108         boost::filesystem::path result;
109         for (boost::filesystem::path::iterator i = p.begin(); i != p.end(); ++i) {
110                 if (*i == "..") {
111                         if (boost::filesystem::is_symlink (result) || result.filename() == "..") {
112                                 result /= *i;
113                         } else {
114                                 result = result.parent_path ();
115                         }
116                 } else if (*i != ".") {
117                         result /= *i;
118                 }
119         }
120
121         set_directory (result.string ());
122         
123         if (!boost::filesystem::exists (directory())) {
124                 if (must_exist) {
125                         throw OpenFileError (directory());
126                 } else {
127                         boost::filesystem::create_directory (directory());
128                 }
129         }
130
131         read_metadata ();
132
133         _log = new FileLog (file ("log"));
134         set_dci_date_today ();
135 }
136
137 Film::Film (Film const & o)
138         : _log (0)
139         , _directory         (o._directory)
140         , _name              (o._name)
141         , _use_dci_name      (o._use_dci_name)
142         , _content           (o._content)
143         , _dcp_content_type  (o._dcp_content_type)
144         , _format            (o._format)
145         , _crop              (o._crop)
146         , _filters           (o._filters)
147         , _scaler            (o._scaler)
148         , _dcp_trim_start    (o._dcp_trim_start)
149         , _dcp_trim_end      (o._dcp_trim_end)
150         , _dcp_ab            (o._dcp_ab)
151         , _use_source_audio  (o._use_source_audio)
152         , _audio_stream      (o._audio_stream)
153         , _external_audio    (o._external_audio)
154         , _audio_gain        (o._audio_gain)
155         , _audio_delay       (o._audio_delay)
156         , _still_duration    (o._still_duration)
157         , _subtitle_stream   (o._subtitle_stream)
158         , _with_subtitles    (o._with_subtitles)
159         , _subtitle_offset   (o._subtitle_offset)
160         , _subtitle_scale    (o._subtitle_scale)
161         , _audio_language    (o._audio_language)
162         , _subtitle_language (o._subtitle_language)
163         , _territory         (o._territory)
164         , _rating            (o._rating)
165         , _studio            (o._studio)
166         , _facility          (o._facility)
167         , _package_type      (o._package_type)
168         , _thumbs            (o._thumbs)
169         , _size              (o._size)
170         , _length            (o._length)
171         , _audio_sample_rate (o._audio_sample_rate)
172         , _content_digest    (o._content_digest)
173         , _has_subtitles     (o._has_subtitles)
174         , _audio_streams     (o._audio_streams)
175         , _subtitle_streams  (o._subtitle_streams)
176         , _frames_per_second (o._frames_per_second)
177         , _dirty             (o._dirty)
178 {
179
180 }
181
182 Film::~Film ()
183 {
184         delete _log;
185 }
186           
187 /** @return The path to the directory to write JPEG2000 files to */
188 string
189 Film::j2k_dir () const
190 {
191         assert (format());
192
193         boost::filesystem::path p;
194
195         /* Start with j2c */
196         p /= "j2c";
197
198         pair<string, string> f = Filter::ffmpeg_strings (filters());
199
200         /* Write stuff to specify the filter / post-processing settings that are in use,
201            so that we don't get confused about J2K files generated using different
202            settings.
203         */
204         stringstream s;
205         s << format()->id()
206           << "_" << content_digest()
207           << "_" << crop().left << "_" << crop().right << "_" << crop().top << "_" << crop().bottom
208           << "_" << f.first << "_" << f.second
209           << "_" << scaler()->id();
210
211         p /= s.str ();
212
213         /* Similarly for the A/B case */
214         if (dcp_ab()) {
215                 stringstream s;
216                 pair<string, string> fa = Filter::ffmpeg_strings (Config::instance()->reference_filters());
217                 s << "ab_" << Config::instance()->reference_scaler()->id() << "_" << fa.first << "_" << fa.second;
218                 p /= s.str ();
219         }
220         
221         return dir (p.string());
222 }
223
224 /** Add suitable Jobs to the JobManager to create a DCP for this Film.
225  *  @param true to transcode, false to use the WAV and J2K files that are already there.
226  */
227 void
228 Film::make_dcp (bool transcode)
229 {
230         set_dci_date_today ();
231         
232         if (dcp_name().find ("/") != string::npos) {
233                 throw BadSettingError ("name", "cannot contain slashes");
234         }
235         
236         log()->log (String::compose ("DVD-o-matic %1 git %2 using %3", dvdomatic_version, dvdomatic_git_commit, dependency_version_summary()));
237
238         {
239                 char buffer[128];
240                 gethostname (buffer, sizeof (buffer));
241                 log()->log (String::compose ("Starting to make DCP on %1", buffer));
242         }
243                 
244         if (format() == 0) {
245                 throw MissingSettingError ("format");
246         }
247
248         if (content().empty ()) {
249                 throw MissingSettingError ("content");
250         }
251
252         if (dcp_content_type() == 0) {
253                 throw MissingSettingError ("content type");
254         }
255
256         if (name().empty()) {
257                 throw MissingSettingError ("name");
258         }
259
260         shared_ptr<Options> o (new Options (j2k_dir(), ".j2c", dir ("wavs")));
261         o->out_size = format()->dcp_size ();
262         o->padding = format()->dcp_padding (shared_from_this ());
263         o->ratio = format()->ratio_as_float (shared_from_this ());
264         if (dcp_length ()) {
265                 o->video_decode_range = make_pair (dcp_trim_start(), dcp_trim_start() + dcp_length().get());
266                 o->audio_decode_range = make_pair (
267                         video_frames_to_audio_frames (o->video_decode_range.get().first, audio_sample_rate(), frames_per_second()),
268                         video_frames_to_audio_frames (o->video_decode_range.get().second, audio_sample_rate(), frames_per_second())
269                         );
270                         
271         }
272         o->decode_subtitles = with_subtitles ();
273         o->decode_video_skip = dcp_frame_rate (frames_per_second()).skip;
274
275         shared_ptr<Job> r;
276
277         if (transcode) {
278                 if (dcp_ab()) {
279                         r = JobManager::instance()->add (shared_ptr<Job> (new ABTranscodeJob (shared_from_this(), o, shared_ptr<Job> ())));
280                 } else {
281                         r = JobManager::instance()->add (shared_ptr<Job> (new TranscodeJob (shared_from_this(), o, shared_ptr<Job> ())));
282                 }
283         }
284
285         r = JobManager::instance()->add (shared_ptr<Job> (new CheckHashesJob (shared_from_this(), o, r)));
286         JobManager::instance()->add (shared_ptr<Job> (new MakeDCPJob (shared_from_this(), o, r)));
287 }
288
289 /** Start a job to examine our content file */
290 void
291 Film::examine_content ()
292 {
293         if (_examine_content_job) {
294                 return;
295         }
296
297         set_thumbs (vector<SourceFrame> ());
298         boost::filesystem::remove_all (dir ("thumbs"));
299
300         /* This call will recreate the directory */
301         dir ("thumbs");
302         
303         _examine_content_job.reset (new ExamineContentJob (shared_from_this(), shared_ptr<Job> ()));
304         _examine_content_job->Finished.connect (bind (&Film::examine_content_finished, this));
305         JobManager::instance()->add (_examine_content_job);
306 }
307
308 void
309 Film::examine_content_finished ()
310 {
311         _examine_content_job.reset ();
312 }
313
314 /** @return full paths to any audio files that this Film has */
315 vector<string>
316 Film::audio_files () const
317 {
318         vector<string> f;
319         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator (dir("wavs")); i != boost::filesystem::directory_iterator(); ++i) {
320                 f.push_back (i->path().string ());
321         }
322
323         return f;
324 }
325
326 /** Start a job to send our DCP to the configured TMS */
327 void
328 Film::send_dcp_to_tms ()
329 {
330         shared_ptr<Job> j (new SCPDCPJob (shared_from_this(), shared_ptr<Job> ()));
331         JobManager::instance()->add (j);
332 }
333
334 void
335 Film::copy_from_dvd ()
336 {
337         shared_ptr<Job> j (new CopyFromDVDJob (shared_from_this(), shared_ptr<Job> ()));
338         JobManager::instance()->add (j);
339 }
340
341 /** Count the number of frames that have been encoded for this film.
342  *  @return frame count.
343  */
344 int
345 Film::encoded_frames () const
346 {
347         if (format() == 0) {
348                 return 0;
349         }
350
351         int N = 0;
352         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator (j2k_dir ()); i != boost::filesystem::directory_iterator(); ++i) {
353                 ++N;
354                 boost::this_thread::interruption_point ();
355         }
356
357         return N;
358 }
359
360 /** Return the filename of a subtitle image if one exists for a given thumb index.
361  *  @param Thumbnail index.
362  *  @return Position of the image within the source frame, and the image filename, if one exists.
363  *  Otherwise the filename will be empty.
364  */
365 pair<Position, string>
366 Film::thumb_subtitle (int n) const
367 {
368         string sub_file = thumb_base(n) + ".sub";
369         if (!boost::filesystem::exists (sub_file)) {
370                 return pair<Position, string> ();
371         }
372
373         pair<Position, string> sub;
374         
375         ifstream f (sub_file.c_str ());
376         multimap<string, string> kv = read_key_value (f);
377         for (map<string, string>::const_iterator i = kv.begin(); i != kv.end(); ++i) {
378                 if (i->first == "x") {
379                         sub.first.x = lexical_cast<int> (i->second);
380                 } else if (i->first == "y") {
381                         sub.first.y = lexical_cast<int> (i->second);
382                         sub.second = String::compose ("%1.sub.png", thumb_base(n));
383                 }
384         }
385         
386         return sub;
387 }
388
389 /** Write state to our `metadata' file */
390 void
391 Film::write_metadata () const
392 {
393         boost::mutex::scoped_lock lm (_state_mutex);
394
395         boost::filesystem::create_directories (directory());
396
397         string const m = file ("metadata");
398         ofstream f (m.c_str ());
399         if (!f.good ()) {
400                 throw CreateFileError (m);
401         }
402
403         /* User stuff */
404         f << "name " << _name << "\n";
405         f << "use_dci_name " << _use_dci_name << "\n";
406         f << "content " << _content << "\n";
407         if (_dcp_content_type) {
408                 f << "dcp_content_type " << _dcp_content_type->pretty_name () << "\n";
409         }
410         if (_format) {
411                 f << "format " << _format->as_metadata () << "\n";
412         }
413         f << "left_crop " << _crop.left << "\n";
414         f << "right_crop " << _crop.right << "\n";
415         f << "top_crop " << _crop.top << "\n";
416         f << "bottom_crop " << _crop.bottom << "\n";
417         for (vector<Filter const *>::const_iterator i = _filters.begin(); i != _filters.end(); ++i) {
418                 f << "filter " << (*i)->id () << "\n";
419         }
420         f << "scaler " << _scaler->id () << "\n";
421         f << "dcp_trim_start " << _dcp_trim_start << "\n";
422         f << "dcp_trim_end " << _dcp_trim_end << "\n";
423         f << "dcp_ab " << (_dcp_ab ? "1" : "0") << "\n";
424         f << "use_source_audio " << (_use_source_audio ? "1" : "0") << "\n";
425         f << "selected_audio_stream " << _audio_stream << "\n";
426         for (vector<string>::const_iterator i = _external_audio.begin(); i != _external_audio.end(); ++i) {
427                 f << "external_audio " << *i << "\n";
428         }
429         f << "audio_gain " << _audio_gain << "\n";
430         f << "audio_delay " << _audio_delay << "\n";
431         f << "still_duration " << _still_duration << "\n";
432         f << "selected_subtitle_stream " << _subtitle_stream << "\n";
433         f << "with_subtitles " << _with_subtitles << "\n";
434         f << "subtitle_offset " << _subtitle_offset << "\n";
435         f << "subtitle_scale " << _subtitle_scale << "\n";
436         f << "audio_language " << _audio_language << "\n";
437         f << "subtitle_language " << _subtitle_language << "\n";
438         f << "territory " << _territory << "\n";
439         f << "rating " << _rating << "\n";
440         f << "studio " << _studio << "\n";
441         f << "facility " << _facility << "\n";
442         f << "package_type " << _package_type << "\n";
443
444         /* Cached stuff; this is information about our content; we could
445            look it up each time, but that's slow.
446         */
447         for (vector<SourceFrame>::const_iterator i = _thumbs.begin(); i != _thumbs.end(); ++i) {
448                 f << "thumb " << *i << "\n";
449         }
450         f << "width " << _size.width << "\n";
451         f << "height " << _size.height << "\n";
452         f << "length " << _length.get_value_or(0) << "\n";
453         f << "audio_sample_rate " << _audio_sample_rate << "\n";
454         f << "content_digest " << _content_digest << "\n";
455         f << "has_subtitles " << _has_subtitles << "\n";
456
457         for (vector<AudioStream>::const_iterator i = _audio_streams.begin(); i != _audio_streams.end(); ++i) {
458                 f << "audio_stream " << i->to_string () << "\n";
459         }
460
461         for (vector<SubtitleStream>::const_iterator i = _subtitle_streams.begin(); i != _subtitle_streams.end(); ++i) {
462                 f << "subtitle_stream " << i->to_string () << "\n";
463         }
464
465         f << "frames_per_second " << _frames_per_second << "\n";
466         
467         _dirty = false;
468 }
469
470 /** Read state from our metadata file */
471 void
472 Film::read_metadata ()
473 {
474         boost::mutex::scoped_lock lm (_state_mutex);
475
476         _external_audio.clear ();
477         _thumbs.clear ();
478         _audio_streams.clear ();
479         _subtitle_streams.clear ();
480         
481         ifstream f (file ("metadata").c_str());
482         multimap<string, string> kv = read_key_value (f);
483         for (multimap<string, string>::const_iterator i = kv.begin(); i != kv.end(); ++i) {
484                 string const k = i->first;
485                 string const v = i->second;
486
487                 /* User-specified stuff */
488                 if (k == "name") {
489                         _name = v;
490                 } else if (k == "use_dci_name") {
491                         _use_dci_name = (v == "1");
492                 } else if (k == "content") {
493                         _content = v;
494                 } else if (k == "dcp_content_type") {
495                         _dcp_content_type = DCPContentType::from_pretty_name (v);
496                 } else if (k == "format") {
497                         _format = Format::from_metadata (v);
498                 } else if (k == "left_crop") {
499                         _crop.left = atoi (v.c_str ());
500                 } else if (k == "right_crop") {
501                         _crop.right = atoi (v.c_str ());
502                 } else if (k == "top_crop") {
503                         _crop.top = atoi (v.c_str ());
504                 } else if (k == "bottom_crop") {
505                         _crop.bottom = atoi (v.c_str ());
506                 } else if (k == "filter") {
507                         _filters.push_back (Filter::from_id (v));
508                 } else if (k == "scaler") {
509                         _scaler = Scaler::from_id (v);
510                 } else if (k == "dcp_trim_start") {
511                         _dcp_trim_start = atoi (v.c_str ());
512                 } else if (k == "dcp_trim_end") {
513                         _dcp_trim_end = atoi (v.c_str ());
514                 } else if (k == "dcp_ab") {
515                         _dcp_ab = (v == "1");
516                 } else if (k == "use_source_audio") {
517                         _use_source_audio = (v == "1");
518                 } else if (k == "selected_audio_stream") {
519                         _audio_stream = atoi (v.c_str ());
520                 } else if (k == "external_audio") {
521                         _external_audio.push_back (v);
522                 } else if (k == "audio_gain") {
523                         _audio_gain = atof (v.c_str ());
524                 } else if (k == "audio_delay") {
525                         _audio_delay = atoi (v.c_str ());
526                 } else if (k == "still_duration") {
527                         _still_duration = atoi (v.c_str ());
528                 } else if (k == "selected_subtitle_stream") {
529                         _subtitle_stream = atoi (v.c_str ());
530                 } else if (k == "with_subtitles") {
531                         _with_subtitles = (v == "1");
532                 } else if (k == "subtitle_offset") {
533                         _subtitle_offset = atoi (v.c_str ());
534                 } else if (k == "subtitle_scale") {
535                         _subtitle_scale = atof (v.c_str ());
536                 } else if (k == "audio_language") {
537                         _audio_language = v;
538                 } else if (k == "subtitle_language") {
539                         _subtitle_language = v;
540                 } else if (k == "territory") {
541                         _territory = v;
542                 } else if (k == "rating") {
543                         _rating = v;
544                 } else if (k == "studio") {
545                         _studio = v;
546                 } else if (k == "facility") {
547                         _facility = v;
548                 } else if (k == "package_type") {
549                         _package_type = v;
550                 }
551                 
552                 /* Cached stuff */
553                 if (k == "thumb") {
554                         int const n = atoi (v.c_str ());
555                         /* Only add it to the list if it still exists */
556                         if (boost::filesystem::exists (thumb_file_for_frame (n))) {
557                                 _thumbs.push_back (n);
558                         }
559                 } else if (k == "width") {
560                         _size.width = atoi (v.c_str ());
561                 } else if (k == "height") {
562                         _size.height = atoi (v.c_str ());
563                 } else if (k == "length") {
564                         int const vv = atoi (v.c_str ());
565                         if (vv) {
566                                 _length = vv;
567                         }
568                 } else if (k == "audio_sample_rate") {
569                         _audio_sample_rate = atoi (v.c_str ());
570                 } else if (k == "content_digest") {
571                         _content_digest = v;
572                 } else if (k == "has_subtitles") {
573                         _has_subtitles = (v == "1");
574                 } else if (k == "audio_stream") {
575                         _audio_streams.push_back (AudioStream (v));
576                 } else if (k == "subtitle_stream") {
577                         _subtitle_streams.push_back (SubtitleStream (v));
578                 } else if (k == "frames_per_second") {
579                         _frames_per_second = atof (v.c_str ());
580                 }
581         }
582                 
583         _dirty = false;
584 }
585
586 /** @param n A thumb index.
587  *  @return The path to the thumb's image file.
588  */
589 string
590 Film::thumb_file (int n) const
591 {
592         return thumb_file_for_frame (thumb_frame (n));
593 }
594
595 /** @param n A frame index within the Film's source.
596  *  @return The path to the thumb's image file for this frame;
597  *  we assume that it exists.
598  */
599 string
600 Film::thumb_file_for_frame (SourceFrame n) const
601 {
602         return thumb_base_for_frame(n) + ".png";
603 }
604
605 /** @param n Thumb index.
606  *  Must not be called with the _state_mutex locked.
607  */
608 string
609 Film::thumb_base (int n) const
610 {
611         return thumb_base_for_frame (thumb_frame (n));
612 }
613
614 string
615 Film::thumb_base_for_frame (SourceFrame n) const
616 {
617         stringstream s;
618         s.width (8);
619         s << setfill('0') << n;
620         
621         boost::filesystem::path p;
622         p /= dir ("thumbs");
623         p /= s.str ();
624                 
625         return p.string ();
626 }
627
628 /** @param n A thumb index.
629  *  @return The frame within the Film's source that it is for.
630  *
631  *  Must not be called with the _state_mutex locked.
632  */
633 SourceFrame
634 Film::thumb_frame (int n) const
635 {
636         boost::mutex::scoped_lock lm (_state_mutex);
637         assert (n < int (_thumbs.size ()));
638         return _thumbs[n];
639 }
640
641 Size
642 Film::cropped_size (Size s) const
643 {
644         boost::mutex::scoped_lock lm (_state_mutex);
645         s.width -= _crop.left + _crop.right;
646         s.height -= _crop.top + _crop.bottom;
647         return s;
648 }
649
650 /** Given a directory name, return its full path within the Film's directory.
651  *  The directory (and its parents) will be created if they do not exist.
652  */
653 string
654 Film::dir (string d) const
655 {
656         boost::mutex::scoped_lock lm (_directory_mutex);
657         boost::filesystem::path p;
658         p /= _directory;
659         p /= d;
660         boost::filesystem::create_directories (p);
661         return p.string ();
662 }
663
664 /** Given a file or directory name, return its full path within the Film's directory.
665  *  _directory_mutex must not be locked on entry.
666  */
667 string
668 Film::file (string f) const
669 {
670         boost::mutex::scoped_lock lm (_directory_mutex);
671         boost::filesystem::path p;
672         p /= _directory;
673         p /= f;
674         return p.string ();
675 }
676
677 /** @return full path of the content (actual video) file
678  *  of the Film.
679  */
680 string
681 Film::content_path () const
682 {
683         boost::mutex::scoped_lock lm (_state_mutex);
684         if (boost::filesystem::path(_content).has_root_directory ()) {
685                 return _content;
686         }
687
688         return file (_content);
689 }
690
691 ContentType
692 Film::content_type () const
693 {
694 #if BOOST_FILESYSTEM_VERSION == 3
695         string ext = boost::filesystem::path(_content).extension().string();
696 #else
697         string ext = boost::filesystem::path(_content).extension();
698 #endif
699
700         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
701         
702         if (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png") {
703                 return STILL;
704         }
705
706         return VIDEO;
707 }
708
709 /** @return The sampling rate that we will resample the audio to */
710 int
711 Film::target_audio_sample_rate () const
712 {
713         /* Resample to a DCI-approved sample rate */
714         double t = dcp_audio_sample_rate (audio_sample_rate());
715
716         DCPFrameRate dfr = dcp_frame_rate (frames_per_second ());
717
718         /* Compensate for the fact that video will be rounded to the
719            nearest integer number of frames per second.
720         */
721         if (dfr.run_fast) {
722                 t *= _frames_per_second * dfr.skip / dfr.frames_per_second;
723         }
724
725         return rint (t);
726 }
727
728 boost::optional<SourceFrame>
729 Film::dcp_length () const
730 {
731         if (!length()) {
732                 return boost::optional<SourceFrame> ();
733         }
734
735         return length().get() - dcp_trim_start() - dcp_trim_end();
736 }
737
738 /** @return a DCI-compliant name for a DCP of this film */
739 string
740 Film::dci_name () const
741 {
742         stringstream d;
743
744         string fixed_name = to_upper_copy (name());
745         for (size_t i = 0; i < fixed_name.length(); ++i) {
746                 if (fixed_name[i] == ' ') {
747                         fixed_name[i] = '-';
748                 }
749         }
750
751         /* Spec is that the name part should be maximum 14 characters, as I understand it */
752         if (fixed_name.length() > 14) {
753                 fixed_name = fixed_name.substr (0, 14);
754         }
755
756         d << fixed_name << "_";
757
758         if (dcp_content_type()) {
759                 d << dcp_content_type()->dci_name() << "_";
760         }
761
762         if (format()) {
763                 d << format()->dci_name() << "_";
764         }
765
766         if (!audio_language().empty ()) {
767                 d << audio_language();
768                 if (!subtitle_language().empty() && with_subtitles()) {
769                         d << "-" << subtitle_language();
770                 } else {
771                         d << "-XX";
772                 }
773                         
774                 d << "_";
775         }
776
777         if (!territory().empty ()) {
778                 d << territory();
779                 if (!rating().empty ()) {
780                         d << "-" << rating();
781                 }
782                 d << "_";
783         }
784
785         switch (audio_channels()) {
786         case 1:
787                 d << "10_";
788                 break;
789         case 2:
790                 d << "20_";
791                 break;
792         case 6:
793                 d << "51_";
794                 break;
795         case 8:
796                 d << "71_";
797                 break;
798         }
799
800         d << "2K_";
801
802         if (!studio().empty ()) {
803                 d << studio() << "_";
804         }
805
806         d << boost::gregorian::to_iso_string (_dci_date) << "_";
807
808         if (!facility().empty ()) {
809                 d << facility() << "_";
810         }
811
812         if (!package_type().empty ()) {
813                 d << package_type();
814         }
815
816         return d.str ();
817 }
818
819 /** @return name to give the DCP */
820 string
821 Film::dcp_name () const
822 {
823         if (use_dci_name()) {
824                 return dci_name ();
825         }
826
827         return name();
828 }
829
830
831 void
832 Film::set_directory (string d)
833 {
834         boost::mutex::scoped_lock lm (_state_mutex);
835         _directory = d;
836         _dirty = true;
837 }
838
839 void
840 Film::set_name (string n)
841 {
842         {
843                 boost::mutex::scoped_lock lm (_state_mutex);
844                 _name = n;
845         }
846         signal_changed (NAME);
847 }
848
849 void
850 Film::set_use_dci_name (bool u)
851 {
852         {
853                 boost::mutex::scoped_lock lm (_state_mutex);
854                 _use_dci_name = u;
855         }
856         signal_changed (USE_DCI_NAME);
857 }
858
859 void
860 Film::set_content (string c)
861 {
862         string check = directory ();
863
864 #if BOOST_FILESYSTEM_VERSION == 3
865         boost::filesystem::path slash ("/");
866         string platform_slash = slash.make_preferred().string ();
867 #else
868 #ifdef DVDOMATIC_WINDOWS
869         string platform_slash = "\\";
870 #else
871         string platform_slash = "/";
872 #endif
873 #endif  
874
875         if (!ends_with (check, platform_slash)) {
876                 check += platform_slash;
877         }
878         
879         if (boost::filesystem::path(c).has_root_directory () && starts_with (c, check)) {
880                 c = c.substr (_directory.length() + 1);
881         }
882
883         string old_content;
884         
885         {
886                 boost::mutex::scoped_lock lm (_state_mutex);
887                 if (c == _content) {
888                         return;
889                 }
890
891                 old_content = _content;
892                 _content = c;
893         }
894
895         /* Create a temporary decoder so that we can get information
896            about the content.
897         */
898
899         try {
900                 shared_ptr<Options> o (new Options ("", "", ""));
901                 o->out_size = Size (1024, 1024);
902                 
903                 shared_ptr<Decoder> d = decoder_factory (shared_from_this(), o, 0);
904                 
905                 set_size (d->native_size ());
906                 set_frames_per_second (d->frames_per_second ());
907                 set_audio_sample_rate (d->audio_sample_rate ());
908                 set_has_subtitles (d->has_subtitles ());
909                 set_audio_streams (d->audio_streams ());
910                 set_subtitle_streams (d->subtitle_streams ());
911                 set_audio_stream (audio_streams().empty() ? -1 : 0);
912                 set_subtitle_stream (subtitle_streams().empty() ? -1 : 0);
913                 
914                 {
915                         boost::mutex::scoped_lock lm (_state_mutex);
916                         _content = c;
917                 }
918                 
919                 signal_changed (CONTENT);
920                 
921                 set_content_digest (md5_digest (content_path ()));
922                 
923                 examine_content ();
924
925         } catch (...) {
926
927                 boost::mutex::scoped_lock lm (_state_mutex);
928                 _content = old_content;
929                 throw;
930
931         }
932 }
933                
934 void
935 Film::set_dcp_content_type (DCPContentType const * t)
936 {
937         {
938                 boost::mutex::scoped_lock lm (_state_mutex);
939                 _dcp_content_type = t;
940         }
941         signal_changed (DCP_CONTENT_TYPE);
942 }
943
944 void
945 Film::set_format (Format const * f)
946 {
947         {
948                 boost::mutex::scoped_lock lm (_state_mutex);
949                 _format = f;
950         }
951         signal_changed (FORMAT);
952 }
953
954 void
955 Film::set_crop (Crop c)
956 {
957         {
958                 boost::mutex::scoped_lock lm (_state_mutex);
959                 _crop = c;
960         }
961         signal_changed (CROP);
962 }
963
964 void
965 Film::set_left_crop (int c)
966 {
967         {
968                 boost::mutex::scoped_lock lm (_state_mutex);
969                 
970                 if (_crop.left == c) {
971                         return;
972                 }
973                 
974                 _crop.left = c;
975         }
976         signal_changed (CROP);
977 }
978
979 void
980 Film::set_right_crop (int c)
981 {
982         {
983                 boost::mutex::scoped_lock lm (_state_mutex);
984                 if (_crop.right == c) {
985                         return;
986                 }
987                 
988                 _crop.right = c;
989         }
990         signal_changed (CROP);
991 }
992
993 void
994 Film::set_top_crop (int c)
995 {
996         {
997                 boost::mutex::scoped_lock lm (_state_mutex);
998                 if (_crop.top == c) {
999                         return;
1000                 }
1001                 
1002                 _crop.top = c;
1003         }
1004         signal_changed (CROP);
1005 }
1006
1007 void
1008 Film::set_bottom_crop (int c)
1009 {
1010         {
1011                 boost::mutex::scoped_lock lm (_state_mutex);
1012                 if (_crop.bottom == c) {
1013                         return;
1014                 }
1015                 
1016                 _crop.bottom = c;
1017         }
1018         signal_changed (CROP);
1019 }
1020
1021 void
1022 Film::set_filters (vector<Filter const *> f)
1023 {
1024         {
1025                 boost::mutex::scoped_lock lm (_state_mutex);
1026                 _filters = f;
1027         }
1028         signal_changed (FILTERS);
1029 }
1030
1031 void
1032 Film::set_scaler (Scaler const * s)
1033 {
1034         {
1035                 boost::mutex::scoped_lock lm (_state_mutex);
1036                 _scaler = s;
1037         }
1038         signal_changed (SCALER);
1039 }
1040
1041 void
1042 Film::set_dcp_trim_start (int t)
1043 {
1044         {
1045                 boost::mutex::scoped_lock lm (_state_mutex);
1046                 _dcp_trim_start = t;
1047         }
1048         signal_changed (DCP_TRIM_START);
1049 }
1050
1051 void
1052 Film::set_dcp_trim_end (int t)
1053 {
1054         {
1055                 boost::mutex::scoped_lock lm (_state_mutex);
1056                 _dcp_trim_end = t;
1057         }
1058         signal_changed (DCP_TRIM_END);
1059 }
1060
1061 void
1062 Film::set_dcp_ab (bool a)
1063 {
1064         {
1065                 boost::mutex::scoped_lock lm (_state_mutex);
1066                 _dcp_ab = a;
1067         }
1068         signal_changed (DCP_AB);
1069 }
1070
1071 void
1072 Film::set_use_source_audio (bool s)
1073 {
1074         {
1075                 boost::mutex::scoped_lock lm (_state_mutex);
1076                 _use_source_audio = s;
1077         }
1078         signal_changed (USE_SOURCE_AUDIO);
1079 }
1080
1081 void
1082 Film::set_audio_stream (int s)
1083 {
1084         {
1085                 boost::mutex::scoped_lock lm (_state_mutex);
1086                 _audio_stream = s;
1087         }
1088         signal_changed (AUDIO_STREAM);
1089 }
1090
1091 void
1092 Film::set_external_audio (vector<string> a)
1093 {
1094         {
1095                 boost::mutex::scoped_lock lm (_state_mutex);
1096                 _external_audio = a;
1097         }
1098         signal_changed (EXTERNAL_AUDIO);
1099 }
1100
1101 void
1102 Film::set_audio_gain (float g)
1103 {
1104         {
1105                 boost::mutex::scoped_lock lm (_state_mutex);
1106                 _audio_gain = g;
1107         }
1108         signal_changed (AUDIO_GAIN);
1109 }
1110
1111 void
1112 Film::set_audio_delay (int d)
1113 {
1114         {
1115                 boost::mutex::scoped_lock lm (_state_mutex);
1116                 _audio_delay = d;
1117         }
1118         signal_changed (AUDIO_DELAY);
1119 }
1120
1121 void
1122 Film::set_still_duration (int d)
1123 {
1124         {
1125                 boost::mutex::scoped_lock lm (_state_mutex);
1126                 _still_duration = d;
1127         }
1128         signal_changed (STILL_DURATION);
1129 }
1130
1131 void
1132 Film::set_subtitle_stream (int s)
1133 {
1134         {
1135                 boost::mutex::scoped_lock lm (_state_mutex);
1136                 _subtitle_stream = s;
1137         }
1138         signal_changed (SUBTITLE_STREAM);
1139 }
1140
1141 void
1142 Film::set_with_subtitles (bool w)
1143 {
1144         {
1145                 boost::mutex::scoped_lock lm (_state_mutex);
1146                 _with_subtitles = w;
1147         }
1148         signal_changed (WITH_SUBTITLES);
1149 }
1150
1151 void
1152 Film::set_subtitle_offset (int o)
1153 {
1154         {
1155                 boost::mutex::scoped_lock lm (_state_mutex);
1156                 _subtitle_offset = o;
1157         }
1158         signal_changed (SUBTITLE_OFFSET);
1159 }
1160
1161 void
1162 Film::set_subtitle_scale (float s)
1163 {
1164         {
1165                 boost::mutex::scoped_lock lm (_state_mutex);
1166                 _subtitle_scale = s;
1167         }
1168         signal_changed (SUBTITLE_SCALE);
1169 }
1170
1171 void
1172 Film::set_audio_language (string l)
1173 {
1174         {
1175                 boost::mutex::scoped_lock lm (_state_mutex);
1176                 _audio_language = l;
1177         }
1178         signal_changed (DCI_METADATA);
1179 }
1180
1181 void
1182 Film::set_subtitle_language (string l)
1183 {
1184         {
1185                 boost::mutex::scoped_lock lm (_state_mutex);
1186                 _subtitle_language = l;
1187         }
1188         signal_changed (DCI_METADATA);
1189 }
1190
1191 void
1192 Film::set_territory (string t)
1193 {
1194         {
1195                 boost::mutex::scoped_lock lm (_state_mutex);
1196                 _territory = t;
1197         }
1198         signal_changed (DCI_METADATA);
1199 }
1200
1201 void
1202 Film::set_rating (string r)
1203 {
1204         {
1205                 boost::mutex::scoped_lock lm (_state_mutex);
1206                 _rating = r;
1207         }
1208         signal_changed (DCI_METADATA);
1209 }
1210
1211 void
1212 Film::set_studio (string s)
1213 {
1214         {
1215                 boost::mutex::scoped_lock lm (_state_mutex);
1216                 _studio = s;
1217         }
1218         signal_changed (DCI_METADATA);
1219 }
1220
1221 void
1222 Film::set_facility (string f)
1223 {
1224         {
1225                 boost::mutex::scoped_lock lm (_state_mutex);
1226                 _facility = f;
1227         }
1228         signal_changed (DCI_METADATA);
1229 }
1230
1231 void
1232 Film::set_package_type (string p)
1233 {
1234         {
1235                 boost::mutex::scoped_lock lm (_state_mutex);
1236                 _package_type = p;
1237         }
1238         signal_changed (DCI_METADATA);
1239 }
1240
1241 void
1242 Film::set_thumbs (vector<SourceFrame> t)
1243 {
1244         {
1245                 boost::mutex::scoped_lock lm (_state_mutex);
1246                 _thumbs = t;
1247         }
1248         signal_changed (THUMBS);
1249 }
1250
1251 void
1252 Film::set_size (Size s)
1253 {
1254         {
1255                 boost::mutex::scoped_lock lm (_state_mutex);
1256                 _size = s;
1257         }
1258         signal_changed (SIZE);
1259 }
1260
1261 void
1262 Film::set_length (SourceFrame l)
1263 {
1264         {
1265                 boost::mutex::scoped_lock lm (_state_mutex);
1266                 _length = l;
1267         }
1268         signal_changed (LENGTH);
1269 }
1270
1271 void
1272 Film::unset_length ()
1273 {
1274         {
1275                 boost::mutex::scoped_lock lm (_state_mutex);
1276                 _length = boost::none;
1277         }
1278         signal_changed (LENGTH);
1279 }       
1280
1281 void
1282 Film::set_audio_sample_rate (int r)
1283 {
1284         {
1285                 boost::mutex::scoped_lock lm (_state_mutex);
1286                 _audio_sample_rate = r;
1287         }
1288         signal_changed (AUDIO_SAMPLE_RATE);
1289 }
1290
1291 void
1292 Film::set_content_digest (string d)
1293 {
1294         {
1295                 boost::mutex::scoped_lock lm (_state_mutex);
1296                 _content_digest = d;
1297         }
1298         _dirty = true;
1299 }
1300
1301 void
1302 Film::set_has_subtitles (bool s)
1303 {
1304         {
1305                 boost::mutex::scoped_lock lm (_state_mutex);
1306                 _has_subtitles = s;
1307         }
1308         signal_changed (HAS_SUBTITLES);
1309 }
1310
1311 void
1312 Film::set_audio_streams (vector<AudioStream> s)
1313 {
1314         {
1315                 boost::mutex::scoped_lock lm (_state_mutex);
1316                 _audio_streams = s;
1317         }
1318         _dirty = true;
1319 }
1320
1321 void
1322 Film::set_subtitle_streams (vector<SubtitleStream> s)
1323 {
1324         {
1325                 boost::mutex::scoped_lock lm (_state_mutex);
1326                 _subtitle_streams = s;
1327         }
1328         _dirty = true;
1329 }
1330
1331 void
1332 Film::set_frames_per_second (float f)
1333 {
1334         {
1335                 boost::mutex::scoped_lock lm (_state_mutex);
1336                 _frames_per_second = f;
1337         }
1338         signal_changed (FRAMES_PER_SECOND);
1339 }
1340         
1341 void
1342 Film::signal_changed (Property p)
1343 {
1344         {
1345                 boost::mutex::scoped_lock lm (_state_mutex);
1346                 _dirty = true;
1347         }
1348
1349         if (ui_signaller) {
1350                 ui_signaller->emit (boost::bind (boost::ref (Changed), p));
1351         }
1352 }
1353
1354 int
1355 Film::audio_channels () const
1356 {
1357         boost::mutex::scoped_lock lm (_state_mutex);
1358         
1359         if (_use_source_audio) {
1360                 if (_audio_stream >= 0) {
1361                         return _audio_streams[_audio_stream].channels ();
1362                 }
1363         } else {
1364                 int last_filled = -1;
1365                 for (size_t i = 0; i < _external_audio.size(); ++i) {
1366                         if (!_external_audio[i].empty()) {
1367                                 last_filled = i;
1368                         }
1369                 }
1370                 
1371                 return last_filled + 1;
1372         }
1373
1374         return 0;
1375 }
1376
1377 void
1378 Film::set_dci_date_today ()
1379 {
1380         _dci_date = boost::gregorian::day_clock::local_day ();
1381 }
1382