Merge branch 'master' into plot-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 "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         ensure_ui_thread ();
346         _analyse_audio_job.reset ();
347
348         AudioAnalysisFinished ();
349 }
350
351 void
352 Film::examine_content_finished ()
353 {
354         _examine_content_job.reset ();
355 }
356
357 /** Start a job to send our DCP to the configured TMS */
358 void
359 Film::send_dcp_to_tms ()
360 {
361         shared_ptr<Job> j (new SCPDCPJob (shared_from_this()));
362         JobManager::instance()->add (j);
363 }
364
365 /** Count the number of frames that have been encoded for this film.
366  *  @return frame count.
367  */
368 int
369 Film::encoded_frames () const
370 {
371         if (format() == 0) {
372                 return 0;
373         }
374
375         int N = 0;
376         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator (info_dir ()); i != boost::filesystem::directory_iterator(); ++i) {
377                 ++N;
378                 boost::this_thread::interruption_point ();
379         }
380
381         return N;
382 }
383
384 /** Write state to our `metadata' file */
385 void
386 Film::write_metadata () const
387 {
388         boost::mutex::scoped_lock lm (_state_mutex);
389
390         boost::filesystem::create_directories (directory());
391
392         string const m = file ("metadata");
393         ofstream f (m.c_str ());
394         if (!f.good ()) {
395                 throw CreateFileError (m);
396         }
397
398         f << "version " << state_version << "\n";
399
400         /* User stuff */
401         f << "name " << _name << "\n";
402         f << "use_dci_name " << _use_dci_name << "\n";
403         f << "content " << _content << "\n";
404         f << "trust_content_header " << (_trust_content_header ? "1" : "0") << "\n";
405         if (_dcp_content_type) {
406                 f << "dcp_content_type " << _dcp_content_type->dci_name () << "\n";
407         }
408         if (_format) {
409                 f << "format " << _format->as_metadata () << "\n";
410         }
411         f << "left_crop " << _crop.left << "\n";
412         f << "right_crop " << _crop.right << "\n";
413         f << "top_crop " << _crop.top << "\n";
414         f << "bottom_crop " << _crop.bottom << "\n";
415         for (vector<Filter const *>::const_iterator i = _filters.begin(); i != _filters.end(); ++i) {
416                 f << "filter " << (*i)->id () << "\n";
417         }
418         f << "scaler " << _scaler->id () << "\n";
419         f << "trim_start " << _trim_start << "\n";
420         f << "trim_end " << _trim_end << "\n";
421         f << "dcp_ab " << (_dcp_ab ? "1" : "0") << "\n";
422         if (_content_audio_stream) {
423                 f << "selected_content_audio_stream " << _content_audio_stream->to_string() << "\n";
424         }
425         for (vector<string>::const_iterator i = _external_audio.begin(); i != _external_audio.end(); ++i) {
426                 f << "external_audio " << *i << "\n";
427         }
428         f << "use_content_audio " << (_use_content_audio ? "1" : "0") << "\n";
429         f << "audio_gain " << _audio_gain << "\n";
430         f << "audio_delay " << _audio_delay << "\n";
431         f << "still_duration " << _still_duration << "\n";
432         if (_subtitle_stream) {
433                 f << "selected_subtitle_stream " << _subtitle_stream->to_string() << "\n";
434         }
435         f << "with_subtitles " << _with_subtitles << "\n";
436         f << "subtitle_offset " << _subtitle_offset << "\n";
437         f << "subtitle_scale " << _subtitle_scale << "\n";
438         f << "colour_lut " << _colour_lut << "\n";
439         f << "j2k_bandwidth " << _j2k_bandwidth << "\n";
440         _dci_metadata.write (f);
441         f << "dci_date " << boost::gregorian::to_iso_string (_dci_date) << "\n";
442         f << "width " << _size.width << "\n";
443         f << "height " << _size.height << "\n";
444         f << "length " << _length.get_value_or(0) << "\n";
445         f << "dcp_intrinsic_duration " << _dcp_intrinsic_duration.get_value_or(0) << "\n";
446         f << "content_digest " << _content_digest << "\n";
447
448         for (vector<shared_ptr<AudioStream> >::const_iterator i = _content_audio_streams.begin(); i != _content_audio_streams.end(); ++i) {
449                 f << "content_audio_stream " << (*i)->to_string () << "\n";
450         }
451
452         f << "external_audio_stream " << _external_audio_stream->to_string() << "\n";
453
454         for (vector<shared_ptr<SubtitleStream> >::const_iterator i = _subtitle_streams.begin(); i != _subtitle_streams.end(); ++i) {
455                 f << "subtitle_stream " << (*i)->to_string () << "\n";
456         }
457
458         f << "frames_per_second " << _frames_per_second << "\n";
459         
460         _dirty = false;
461 }
462
463 /** Read state from our metadata file */
464 void
465 Film::read_metadata ()
466 {
467         boost::mutex::scoped_lock lm (_state_mutex);
468
469         _external_audio.clear ();
470         _content_audio_streams.clear ();
471         _subtitle_streams.clear ();
472
473         boost::optional<int> version;
474
475         /* Backward compatibility things */
476         boost::optional<int> audio_sample_rate;
477         boost::optional<int> audio_stream_index;
478         boost::optional<int> subtitle_stream_index;
479
480         ifstream f (file ("metadata").c_str());
481         if (!f.good()) {
482                 throw OpenFileError (file ("metadata"));
483         }
484         
485         multimap<string, string> kv = read_key_value (f);
486
487         /* We need version before anything else */
488         multimap<string, string>::iterator v = kv.find ("version");
489         if (v != kv.end ()) {
490                 version = atoi (v->second.c_str());
491         }
492         
493         for (multimap<string, string>::const_iterator i = kv.begin(); i != kv.end(); ++i) {
494                 string const k = i->first;
495                 string const v = i->second;
496
497                 if (k == "audio_sample_rate") {
498                         audio_sample_rate = atoi (v.c_str());
499                 }
500
501                 /* User-specified stuff */
502                 if (k == "name") {
503                         _name = v;
504                 } else if (k == "use_dci_name") {
505                         _use_dci_name = (v == "1");
506                 } else if (k == "content") {
507                         _content = v;
508                 } else if (k == "trust_content_header") {
509                         _trust_content_header = (v == "1");
510                 } else if (k == "dcp_content_type") {
511                         if (version < 3) {
512                                 _dcp_content_type = DCPContentType::from_pretty_name (v);
513                         } else {
514                                 _dcp_content_type = DCPContentType::from_dci_name (v);
515                         }
516                 } else if (k == "format") {
517                         _format = Format::from_metadata (v);
518                 } else if (k == "left_crop") {
519                         _crop.left = atoi (v.c_str ());
520                 } else if (k == "right_crop") {
521                         _crop.right = atoi (v.c_str ());
522                 } else if (k == "top_crop") {
523                         _crop.top = atoi (v.c_str ());
524                 } else if (k == "bottom_crop") {
525                         _crop.bottom = atoi (v.c_str ());
526                 } else if (k == "filter") {
527                         _filters.push_back (Filter::from_id (v));
528                 } else if (k == "scaler") {
529                         _scaler = Scaler::from_id (v);
530                 } else if ( ((!version || version < 2) && k == "dcp_trim_start") || k == "trim_start") {
531                         _trim_start = atoi (v.c_str ());
532                 } else if ( ((!version || version < 2) && k == "dcp_trim_end") || k == "trim_end") {
533                         _trim_end = atoi (v.c_str ());
534                 } else if (k == "dcp_ab") {
535                         _dcp_ab = (v == "1");
536                 } else if (k == "selected_content_audio_stream" || (!version && k == "selected_audio_stream")) {
537                         if (!version) {
538                                 audio_stream_index = atoi (v.c_str ());
539                         } else {
540                                 _content_audio_stream = audio_stream_factory (v, version);
541                         }
542                 } else if (k == "external_audio") {
543                         _external_audio.push_back (v);
544                 } else if (k == "use_content_audio") {
545                         _use_content_audio = (v == "1");
546                 } else if (k == "audio_gain") {
547                         _audio_gain = atof (v.c_str ());
548                 } else if (k == "audio_delay") {
549                         _audio_delay = atoi (v.c_str ());
550                 } else if (k == "still_duration") {
551                         _still_duration = atoi (v.c_str ());
552                 } else if (k == "selected_subtitle_stream") {
553                         if (!version) {
554                                 subtitle_stream_index = atoi (v.c_str ());
555                         } else {
556                                 _subtitle_stream = subtitle_stream_factory (v, version);
557                         }
558                 } else if (k == "with_subtitles") {
559                         _with_subtitles = (v == "1");
560                 } else if (k == "subtitle_offset") {
561                         _subtitle_offset = atoi (v.c_str ());
562                 } else if (k == "subtitle_scale") {
563                         _subtitle_scale = atof (v.c_str ());
564                 } else if (k == "colour_lut") {
565                         _colour_lut = atoi (v.c_str ());
566                 } else if (k == "j2k_bandwidth") {
567                         _j2k_bandwidth = atoi (v.c_str ());
568                 } else if (k == "dci_date") {
569                         _dci_date = boost::gregorian::from_undelimited_string (v);
570                 }
571
572                 _dci_metadata.read (k, v);
573                 
574                 /* Cached stuff */
575                 if (k == "width") {
576                         _size.width = atoi (v.c_str ());
577                 } else if (k == "height") {
578                         _size.height = atoi (v.c_str ());
579                 } else if (k == "length") {
580                         int const vv = atoi (v.c_str ());
581                         if (vv) {
582                                 _length = vv;
583                         }
584                 } else if (k == "dcp_intrinsic_duration") {
585                         int const vv = atoi (v.c_str ());
586                         if (vv) {
587                                 _dcp_intrinsic_duration = vv;
588                         }
589                 } else if (k == "content_digest") {
590                         _content_digest = v;
591                 } else if (k == "content_audio_stream" || (!version && k == "audio_stream")) {
592                         _content_audio_streams.push_back (audio_stream_factory (v, version));
593                 } else if (k == "external_audio_stream") {
594                         _external_audio_stream = audio_stream_factory (v, version);
595                 } else if (k == "subtitle_stream") {
596                         _subtitle_streams.push_back (subtitle_stream_factory (v, version));
597                 } else if (k == "frames_per_second") {
598                         _frames_per_second = atof (v.c_str ());
599                 }
600         }
601
602         if (!version) {
603                 if (audio_sample_rate) {
604                         /* version < 1 didn't specify sample rate in the audio streams, so fill it in here */
605                         for (vector<shared_ptr<AudioStream> >::iterator i = _content_audio_streams.begin(); i != _content_audio_streams.end(); ++i) {
606                                 (*i)->set_sample_rate (audio_sample_rate.get());
607                         }
608                 }
609
610                 /* also the selected stream was specified as an index */
611                 if (audio_stream_index && audio_stream_index.get() >= 0 && audio_stream_index.get() < (int) _content_audio_streams.size()) {
612                         _content_audio_stream = _content_audio_streams[audio_stream_index.get()];
613                 }
614
615                 /* similarly the subtitle */
616                 if (subtitle_stream_index && subtitle_stream_index.get() >= 0 && subtitle_stream_index.get() < (int) _subtitle_streams.size()) {
617                         _subtitle_stream = _subtitle_streams[subtitle_stream_index.get()];
618                 }
619         }
620                 
621         _dirty = false;
622 }
623
624 libdcp::Size
625 Film::cropped_size (libdcp::Size s) const
626 {
627         boost::mutex::scoped_lock lm (_state_mutex);
628         s.width -= _crop.left + _crop.right;
629         s.height -= _crop.top + _crop.bottom;
630         return s;
631 }
632
633 /** Given a directory name, return its full path within the Film's directory.
634  *  The directory (and its parents) will be created if they do not exist.
635  */
636 string
637 Film::dir (string d) const
638 {
639         boost::mutex::scoped_lock lm (_directory_mutex);
640         
641         boost::filesystem::path p;
642         p /= _directory;
643         p /= d;
644         
645         boost::filesystem::create_directories (p);
646         
647         return p.string ();
648 }
649
650 /** Given a file or directory name, return its full path within the Film's directory.
651  *  _directory_mutex must not be locked on entry.
652  *  Any required parent directories will be created.
653  */
654 string
655 Film::file (string f) const
656 {
657         boost::mutex::scoped_lock lm (_directory_mutex);
658
659         boost::filesystem::path p;
660         p /= _directory;
661         p /= f;
662
663         boost::filesystem::create_directories (p.parent_path ());
664         
665         return p.string ();
666 }
667
668 /** @return full path of the content (actual video) file
669  *  of the Film.
670  */
671 string
672 Film::content_path () const
673 {
674         boost::mutex::scoped_lock lm (_state_mutex);
675         if (boost::filesystem::path(_content).has_root_directory ()) {
676                 return _content;
677         }
678
679         return file (_content);
680 }
681
682 ContentType
683 Film::content_type () const
684 {
685         if (boost::filesystem::is_directory (_content)) {
686                 /* Directory of images, we assume */
687                 return VIDEO;
688         }
689
690         if (still_image_file (_content)) {
691                 return STILL;
692         }
693
694         return VIDEO;
695 }
696
697 /** @return The sampling rate that we will resample the audio to */
698 int
699 Film::target_audio_sample_rate () const
700 {
701         if (!audio_stream()) {
702                 return 0;
703         }
704         
705         /* Resample to a DCI-approved sample rate */
706         double t = dcp_audio_sample_rate (audio_stream()->sample_rate());
707
708         DCPFrameRate dfr (frames_per_second ());
709
710         /* Compensate if the DCP is being run at a different frame rate
711            to the source; that is, if the video is run such that it will
712            look different in the DCP compared to the source (slower or faster).
713            skip/repeat doesn't come into effect here.
714         */
715
716         if (dfr.change_speed) {
717                 t *= _frames_per_second * dfr.factor() / dfr.frames_per_second;
718         }
719
720         return rint (t);
721 }
722
723 int
724 Film::still_duration_in_frames () const
725 {
726         return still_duration() * frames_per_second();
727 }
728
729 /** @return a DCI-compliant name for a DCP of this film */
730 string
731 Film::dci_name (bool if_created_now) const
732 {
733         stringstream d;
734
735         string fixed_name = to_upper_copy (name());
736         for (size_t i = 0; i < fixed_name.length(); ++i) {
737                 if (fixed_name[i] == ' ') {
738                         fixed_name[i] = '-';
739                 }
740         }
741
742         /* Spec is that the name part should be maximum 14 characters, as I understand it */
743         if (fixed_name.length() > 14) {
744                 fixed_name = fixed_name.substr (0, 14);
745         }
746
747         d << fixed_name << "_";
748
749         if (dcp_content_type()) {
750                 d << dcp_content_type()->dci_name() << "_";
751         }
752
753         if (format()) {
754                 d << format()->dci_name() << "_";
755         }
756
757         DCIMetadata const dm = dci_metadata ();
758
759         if (!dm.audio_language.empty ()) {
760                 d << dm.audio_language;
761                 if (!dm.subtitle_language.empty() && with_subtitles()) {
762                         d << "-" << dm.subtitle_language;
763                 } else {
764                         d << "-XX";
765                 }
766                         
767                 d << "_";
768         }
769
770         if (!dm.territory.empty ()) {
771                 d << dm.territory;
772                 if (!dm.rating.empty ()) {
773                         d << "-" << dm.rating;
774                 }
775                 d << "_";
776         }
777
778         switch (audio_channels()) {
779         case 1:
780                 d << "10_";
781                 break;
782         case 2:
783                 d << "20_";
784                 break;
785         case 6:
786                 d << "51_";
787                 break;
788         case 8:
789                 d << "71_";
790                 break;
791         }
792
793         d << "2K_";
794
795         if (!dm.studio.empty ()) {
796                 d << dm.studio << "_";
797         }
798
799         if (if_created_now) {
800                 d << boost::gregorian::to_iso_string (boost::gregorian::day_clock::local_day ()) << "_";
801         } else {
802                 d << boost::gregorian::to_iso_string (_dci_date) << "_";
803         }
804
805         if (!dm.facility.empty ()) {
806                 d << dm.facility << "_";
807         }
808
809         if (!dm.package_type.empty ()) {
810                 d << dm.package_type;
811         }
812
813         return d.str ();
814 }
815
816 /** @return name to give the DCP */
817 string
818 Film::dcp_name (bool if_created_now) const
819 {
820         if (use_dci_name()) {
821                 return dci_name (if_created_now);
822         }
823
824         return name();
825 }
826
827
828 void
829 Film::set_directory (string d)
830 {
831         boost::mutex::scoped_lock lm (_state_mutex);
832         _directory = d;
833         _dirty = true;
834 }
835
836 void
837 Film::set_name (string n)
838 {
839         {
840                 boost::mutex::scoped_lock lm (_state_mutex);
841                 _name = n;
842         }
843         signal_changed (NAME);
844 }
845
846 void
847 Film::set_use_dci_name (bool u)
848 {
849         {
850                 boost::mutex::scoped_lock lm (_state_mutex);
851                 _use_dci_name = u;
852         }
853         signal_changed (USE_DCI_NAME);
854 }
855
856 void
857 Film::set_content (string c)
858 {
859         string check = directory ();
860
861         boost::filesystem::path slash ("/");
862         string platform_slash = slash.make_preferred().string ();
863
864         if (!ends_with (check, platform_slash)) {
865                 check += platform_slash;
866         }
867         
868         if (boost::filesystem::path(c).has_root_directory () && starts_with (c, check)) {
869                 c = c.substr (_directory.length() + 1);
870         }
871
872         string old_content;
873         
874         {
875                 boost::mutex::scoped_lock lm (_state_mutex);
876                 if (c == _content) {
877                         return;
878                 }
879
880                 old_content = _content;
881                 _content = c;
882         }
883
884         /* Reset streams here in case the new content doesn't have one or the other */
885         _content_audio_stream = shared_ptr<AudioStream> ();
886         _subtitle_stream = shared_ptr<SubtitleStream> ();
887
888         /* Start off using content audio */
889         set_use_content_audio (true);
890
891         /* Create a temporary decoder so that we can get information
892            about the content.
893         */
894
895         try {
896                 Decoders d = decoder_factory (shared_from_this(), DecodeOptions());
897                 
898                 set_size (d.video->native_size ());
899                 set_frames_per_second (d.video->frames_per_second ());
900                 set_subtitle_streams (d.video->subtitle_streams ());
901                 if (d.audio) {
902                         set_content_audio_streams (d.audio->audio_streams ());
903                 }
904
905                 {
906                         boost::mutex::scoped_lock lm (_state_mutex);
907                         _content = c;
908                 }
909                 
910                 signal_changed (CONTENT);
911                 
912                 /* Start off with the first audio and subtitle streams */
913                 if (d.audio && !d.audio->audio_streams().empty()) {
914                         set_content_audio_stream (d.audio->audio_streams().front());
915                 }
916                 
917                 if (!d.video->subtitle_streams().empty()) {
918                         set_subtitle_stream (d.video->subtitle_streams().front());
919                 }
920                 
921                 examine_content ();
922
923         } catch (...) {
924
925                 boost::mutex::scoped_lock lm (_state_mutex);
926                 _content = old_content;
927                 throw;
928
929         }
930
931         /* Default format */
932         switch (content_type()) {
933         case STILL:
934                 set_format (Format::from_id ("var-185"));
935                 break;
936         case VIDEO:
937                 set_format (Format::from_id ("185"));
938                 break;
939         }
940
941         /* Still image DCPs must use external audio */
942         if (content_type() == STILL) {
943                 set_use_content_audio (false);
944         }
945 }
946
947 void
948 Film::set_trust_content_header (bool t)
949 {
950         {
951                 boost::mutex::scoped_lock lm (_state_mutex);
952                 _trust_content_header = t;
953         }
954         
955         signal_changed (TRUST_CONTENT_HEADER);
956
957         if (!_trust_content_header && !content().empty()) {
958                 /* We just said that we don't trust the content's header */
959                 examine_content ();
960         }
961 }
962                
963 void
964 Film::set_dcp_content_type (DCPContentType const * t)
965 {
966         {
967                 boost::mutex::scoped_lock lm (_state_mutex);
968                 _dcp_content_type = t;
969         }
970         signal_changed (DCP_CONTENT_TYPE);
971 }
972
973 void
974 Film::set_format (Format const * f)
975 {
976         {
977                 boost::mutex::scoped_lock lm (_state_mutex);
978                 _format = f;
979         }
980         signal_changed (FORMAT);
981 }
982
983 void
984 Film::set_crop (Crop c)
985 {
986         {
987                 boost::mutex::scoped_lock lm (_state_mutex);
988                 _crop = c;
989         }
990         signal_changed (CROP);
991 }
992
993 void
994 Film::set_left_crop (int c)
995 {
996         {
997                 boost::mutex::scoped_lock lm (_state_mutex);
998                 
999                 if (_crop.left == c) {
1000                         return;
1001                 }
1002                 
1003                 _crop.left = c;
1004         }
1005         signal_changed (CROP);
1006 }
1007
1008 void
1009 Film::set_right_crop (int c)
1010 {
1011         {
1012                 boost::mutex::scoped_lock lm (_state_mutex);
1013                 if (_crop.right == c) {
1014                         return;
1015                 }
1016                 
1017                 _crop.right = c;
1018         }
1019         signal_changed (CROP);
1020 }
1021
1022 void
1023 Film::set_top_crop (int c)
1024 {
1025         {
1026                 boost::mutex::scoped_lock lm (_state_mutex);
1027                 if (_crop.top == c) {
1028                         return;
1029                 }
1030                 
1031                 _crop.top = c;
1032         }
1033         signal_changed (CROP);
1034 }
1035
1036 void
1037 Film::set_bottom_crop (int c)
1038 {
1039         {
1040                 boost::mutex::scoped_lock lm (_state_mutex);
1041                 if (_crop.bottom == c) {
1042                         return;
1043                 }
1044                 
1045                 _crop.bottom = c;
1046         }
1047         signal_changed (CROP);
1048 }
1049
1050 void
1051 Film::set_filters (vector<Filter const *> f)
1052 {
1053         {
1054                 boost::mutex::scoped_lock lm (_state_mutex);
1055                 _filters = f;
1056         }
1057         signal_changed (FILTERS);
1058 }
1059
1060 void
1061 Film::set_scaler (Scaler const * s)
1062 {
1063         {
1064                 boost::mutex::scoped_lock lm (_state_mutex);
1065                 _scaler = s;
1066         }
1067         signal_changed (SCALER);
1068 }
1069
1070 void
1071 Film::set_trim_start (int t)
1072 {
1073         {
1074                 boost::mutex::scoped_lock lm (_state_mutex);
1075                 _trim_start = t;
1076         }
1077         signal_changed (TRIM_START);
1078 }
1079
1080 void
1081 Film::set_trim_end (int t)
1082 {
1083         {
1084                 boost::mutex::scoped_lock lm (_state_mutex);
1085                 _trim_end = t;
1086         }
1087         signal_changed (TRIM_END);
1088 }
1089
1090 void
1091 Film::set_dcp_ab (bool a)
1092 {
1093         {
1094                 boost::mutex::scoped_lock lm (_state_mutex);
1095                 _dcp_ab = a;
1096         }
1097         signal_changed (DCP_AB);
1098 }
1099
1100 void
1101 Film::set_content_audio_stream (shared_ptr<AudioStream> s)
1102 {
1103         {
1104                 boost::mutex::scoped_lock lm (_state_mutex);
1105                 _content_audio_stream = s;
1106         }
1107         signal_changed (CONTENT_AUDIO_STREAM);
1108 }
1109
1110 void
1111 Film::set_external_audio (vector<string> a)
1112 {
1113         {
1114                 boost::mutex::scoped_lock lm (_state_mutex);
1115                 _external_audio = a;
1116         }
1117
1118         shared_ptr<ExternalAudioDecoder> decoder (new ExternalAudioDecoder (shared_from_this(), DecodeOptions()));
1119         if (decoder->audio_stream()) {
1120                 _external_audio_stream = decoder->audio_stream ();
1121         }
1122         
1123         signal_changed (EXTERNAL_AUDIO);
1124 }
1125
1126 void
1127 Film::set_use_content_audio (bool e)
1128 {
1129         {
1130                 boost::mutex::scoped_lock lm (_state_mutex);
1131                 _use_content_audio = e;
1132         }
1133
1134         signal_changed (USE_CONTENT_AUDIO);
1135 }
1136
1137 void
1138 Film::set_audio_gain (float g)
1139 {
1140         {
1141                 boost::mutex::scoped_lock lm (_state_mutex);
1142                 _audio_gain = g;
1143         }
1144         signal_changed (AUDIO_GAIN);
1145 }
1146
1147 void
1148 Film::set_audio_delay (int d)
1149 {
1150         {
1151                 boost::mutex::scoped_lock lm (_state_mutex);
1152                 _audio_delay = d;
1153         }
1154         signal_changed (AUDIO_DELAY);
1155 }
1156
1157 void
1158 Film::set_still_duration (int d)
1159 {
1160         {
1161                 boost::mutex::scoped_lock lm (_state_mutex);
1162                 _still_duration = d;
1163         }
1164         signal_changed (STILL_DURATION);
1165 }
1166
1167 void
1168 Film::set_subtitle_stream (shared_ptr<SubtitleStream> s)
1169 {
1170         {
1171                 boost::mutex::scoped_lock lm (_state_mutex);
1172                 _subtitle_stream = s;
1173         }
1174         signal_changed (SUBTITLE_STREAM);
1175 }
1176
1177 void
1178 Film::set_with_subtitles (bool w)
1179 {
1180         {
1181                 boost::mutex::scoped_lock lm (_state_mutex);
1182                 _with_subtitles = w;
1183         }
1184         signal_changed (WITH_SUBTITLES);
1185 }
1186
1187 void
1188 Film::set_subtitle_offset (int o)
1189 {
1190         {
1191                 boost::mutex::scoped_lock lm (_state_mutex);
1192                 _subtitle_offset = o;
1193         }
1194         signal_changed (SUBTITLE_OFFSET);
1195 }
1196
1197 void
1198 Film::set_subtitle_scale (float s)
1199 {
1200         {
1201                 boost::mutex::scoped_lock lm (_state_mutex);
1202                 _subtitle_scale = s;
1203         }
1204         signal_changed (SUBTITLE_SCALE);
1205 }
1206
1207 void
1208 Film::set_colour_lut (int i)
1209 {
1210         {
1211                 boost::mutex::scoped_lock lm (_state_mutex);
1212                 _colour_lut = i;
1213         }
1214         signal_changed (COLOUR_LUT);
1215 }
1216
1217 void
1218 Film::set_j2k_bandwidth (int b)
1219 {
1220         {
1221                 boost::mutex::scoped_lock lm (_state_mutex);
1222                 _j2k_bandwidth = b;
1223         }
1224         signal_changed (J2K_BANDWIDTH);
1225 }
1226
1227 void
1228 Film::set_dci_metadata (DCIMetadata m)
1229 {
1230         {
1231                 boost::mutex::scoped_lock lm (_state_mutex);
1232                 _dci_metadata = m;
1233         }
1234         signal_changed (DCI_METADATA);
1235 }
1236
1237 void
1238 Film::set_size (libdcp::Size s)
1239 {
1240         {
1241                 boost::mutex::scoped_lock lm (_state_mutex);
1242                 _size = s;
1243         }
1244         signal_changed (SIZE);
1245 }
1246
1247 void
1248 Film::set_length (SourceFrame l)
1249 {
1250         {
1251                 boost::mutex::scoped_lock lm (_state_mutex);
1252                 _length = l;
1253         }
1254         signal_changed (LENGTH);
1255 }
1256
1257 void
1258 Film::unset_length ()
1259 {
1260         {
1261                 boost::mutex::scoped_lock lm (_state_mutex);
1262                 _length = boost::none;
1263         }
1264         signal_changed (LENGTH);
1265 }
1266
1267 void
1268 Film::set_dcp_intrinsic_duration (int d)
1269 {
1270         {
1271                 boost::mutex::scoped_lock lm (_state_mutex);
1272                 _dcp_intrinsic_duration = d;
1273         }
1274         signal_changed (DCP_INTRINSIC_DURATION);
1275 }
1276
1277 void
1278 Film::set_content_digest (string d)
1279 {
1280         {
1281                 boost::mutex::scoped_lock lm (_state_mutex);
1282                 _content_digest = d;
1283         }
1284         _dirty = true;
1285 }
1286
1287 void
1288 Film::set_content_audio_streams (vector<shared_ptr<AudioStream> > s)
1289 {
1290         {
1291                 boost::mutex::scoped_lock lm (_state_mutex);
1292                 _content_audio_streams = s;
1293         }
1294         signal_changed (CONTENT_AUDIO_STREAMS);
1295 }
1296
1297 void
1298 Film::set_subtitle_streams (vector<shared_ptr<SubtitleStream> > s)
1299 {
1300         {
1301                 boost::mutex::scoped_lock lm (_state_mutex);
1302                 _subtitle_streams = s;
1303         }
1304         signal_changed (SUBTITLE_STREAMS);
1305 }
1306
1307 void
1308 Film::set_frames_per_second (float f)
1309 {
1310         {
1311                 boost::mutex::scoped_lock lm (_state_mutex);
1312                 _frames_per_second = f;
1313         }
1314         signal_changed (FRAMES_PER_SECOND);
1315 }
1316         
1317 void
1318 Film::signal_changed (Property p)
1319 {
1320         {
1321                 boost::mutex::scoped_lock lm (_state_mutex);
1322                 _dirty = true;
1323         }
1324
1325         if (ui_signaller) {
1326                 ui_signaller->emit (boost::bind (boost::ref (Changed), p));
1327         }
1328 }
1329
1330 int
1331 Film::audio_channels () const
1332 {
1333         shared_ptr<AudioStream> s = audio_stream ();
1334         if (!s) {
1335                 return 0;
1336         }
1337
1338         return s->channels ();
1339 }
1340
1341 void
1342 Film::set_dci_date_today ()
1343 {
1344         _dci_date = boost::gregorian::day_clock::local_day ();
1345 }
1346
1347 boost::shared_ptr<AudioStream>
1348 Film::audio_stream () const
1349 {
1350         if (use_content_audio()) {
1351                 return _content_audio_stream;
1352         }
1353
1354         return _external_audio_stream;
1355 }
1356
1357 string
1358 Film::info_path (int f) const
1359 {
1360         boost::filesystem::path p;
1361         p /= info_dir ();
1362
1363         stringstream s;
1364         s.width (8);
1365         s << setfill('0') << f << ".md5";
1366
1367         p /= s.str();
1368
1369         /* info_dir() will already have added any initial bit of the path,
1370            so don't call file() on this.
1371         */
1372         return p.string ();
1373 }
1374
1375 string
1376 Film::j2c_path (int f, bool t) const
1377 {
1378         boost::filesystem::path p;
1379         p /= "j2c";
1380         p /= video_state_identifier ();
1381
1382         stringstream s;
1383         s.width (8);
1384         s << setfill('0') << f << ".j2c";
1385
1386         if (t) {
1387                 s << ".tmp";
1388         }
1389
1390         p /= s.str();
1391         return file (p.string ());
1392 }
1393
1394 /** Make an educated guess as to whether we have a complete DCP
1395  *  or not.
1396  *  @return true if we do.
1397  */
1398
1399 bool
1400 Film::have_dcp () const
1401 {
1402         try {
1403                 libdcp::DCP dcp (dir (dcp_name()));
1404                 dcp.read ();
1405         } catch (...) {
1406                 return false;
1407         }
1408
1409         return true;
1410 }