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