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