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