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