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