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