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