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