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