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