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