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