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