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