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