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