Use ImageMagick for tiff decoding too.
[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 std::make_pair;
67 using boost::shared_ptr;
68 using boost::lexical_cast;
69 using boost::to_upper_copy;
70 using boost::ends_with;
71 using boost::starts_with;
72 using boost::optional;
73
74 /** Construct a Film object in a given directory, reading any metadata
75  *  file that exists in that directory.  An exception will be thrown if
76  *  must_exist is true and the specified directory does not exist.
77  *
78  *  @param d Film directory.
79  *  @param must_exist true to throw an exception if does not exist.
80  */
81
82 Film::Film (string d, bool must_exist)
83         : _use_dci_name (false)
84         , _dcp_content_type (0)
85         , _format (0)
86         , _scaler (Scaler::from_id ("bicubic"))
87         , _dcp_trim_start (0)
88         , _dcp_trim_end (0)
89         , _dcp_ab (false)
90         , _use_content_audio (true)
91         , _audio_gain (0)
92         , _audio_delay (0)
93         , _still_duration (10)
94         , _with_subtitles (false)
95         , _subtitle_offset (0)
96         , _subtitle_scale (1)
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_trim_start    (o._dcp_trim_start)
146         , _dcp_trim_end      (o._dcp_trim_end)
147         , _dcp_ab            (o._dcp_ab)
148         , _use_content_audio (o._use_content_audio)
149         , _audio_stream      (o._audio_stream)
150         , _external_audio    (o._external_audio)
151         , _audio_gain        (o._audio_gain)
152         , _audio_delay       (o._audio_delay)
153         , _still_duration    (o._still_duration)
154         , _subtitle_stream   (o._subtitle_stream)
155         , _with_subtitles    (o._with_subtitles)
156         , _subtitle_offset   (o._subtitle_offset)
157         , _subtitle_scale    (o._subtitle_scale)
158         , _audio_language    (o._audio_language)
159         , _subtitle_language (o._subtitle_language)
160         , _territory         (o._territory)
161         , _rating            (o._rating)
162         , _studio            (o._studio)
163         , _facility          (o._facility)
164         , _package_type      (o._package_type)
165         , _thumbs            (o._thumbs)
166         , _size              (o._size)
167         , _length            (o._length)
168         , _content_digest    (o._content_digest)
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         o->padding = format()->dcp_padding (shared_from_this ());
258         o->ratio = format()->ratio_as_float (shared_from_this ());
259         if (dcp_length ()) {
260                 o->video_decode_range = make_pair (dcp_trim_start(), dcp_trim_start() + dcp_length().get());
261                 if (audio_stream()) {
262                         o->audio_decode_range = make_pair (
263                                 video_frames_to_audio_frames (o->video_decode_range.get().first, audio_stream().get().sample_rate(), frames_per_second()),
264                                 video_frames_to_audio_frames (o->video_decode_range.get().second, audio_stream().get().sample_rate(), frames_per_second())
265                                 );
266                 }
267                         
268         }
269         o->decode_subtitles = with_subtitles ();
270         o->decode_video_skip = dcp_frame_rate (frames_per_second()).skip;
271
272         shared_ptr<Job> r;
273
274         if (transcode) {
275                 if (dcp_ab()) {
276                         r = JobManager::instance()->add (shared_ptr<Job> (new ABTranscodeJob (shared_from_this(), o, shared_ptr<Job> ())));
277                 } else {
278                         r = JobManager::instance()->add (shared_ptr<Job> (new TranscodeJob (shared_from_this(), o, shared_ptr<Job> ())));
279                 }
280         }
281
282         r = JobManager::instance()->add (shared_ptr<Job> (new CheckHashesJob (shared_from_this(), o, r)));
283         JobManager::instance()->add (shared_ptr<Job> (new MakeDCPJob (shared_from_this(), o, r)));
284 }
285
286 /** Start a job to examine our content file */
287 void
288 Film::examine_content ()
289 {
290         if (_examine_content_job) {
291                 return;
292         }
293
294         set_thumbs (vector<SourceFrame> ());
295         boost::filesystem::remove_all (dir ("thumbs"));
296
297         /* This call will recreate the directory */
298         dir ("thumbs");
299         
300         _examine_content_job.reset (new ExamineContentJob (shared_from_this(), shared_ptr<Job> ()));
301         _examine_content_job->Finished.connect (bind (&Film::examine_content_finished, this));
302         JobManager::instance()->add (_examine_content_job);
303 }
304
305 void
306 Film::examine_content_finished ()
307 {
308         _examine_content_job.reset ();
309 }
310
311 /** @return full paths to any audio files that this Film has */
312 vector<string>
313 Film::audio_files () const
314 {
315         vector<string> f;
316         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator (dir("wavs")); i != boost::filesystem::directory_iterator(); ++i) {
317                 f.push_back (i->path().string ());
318         }
319
320         return f;
321 }
322
323 /** Start a job to send our DCP to the configured TMS */
324 void
325 Film::send_dcp_to_tms ()
326 {
327         shared_ptr<Job> j (new SCPDCPJob (shared_from_this(), shared_ptr<Job> ()));
328         JobManager::instance()->add (j);
329 }
330
331 void
332 Film::copy_from_dvd ()
333 {
334         shared_ptr<Job> j (new CopyFromDVDJob (shared_from_this(), shared_ptr<Job> ()));
335         JobManager::instance()->add (j);
336 }
337
338 /** Count the number of frames that have been encoded for this film.
339  *  @return frame count.
340  */
341 int
342 Film::encoded_frames () const
343 {
344         if (format() == 0) {
345                 return 0;
346         }
347
348         int N = 0;
349         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator (j2k_dir ()); i != boost::filesystem::directory_iterator(); ++i) {
350                 ++N;
351                 boost::this_thread::interruption_point ();
352         }
353
354         return N;
355 }
356
357 /** Return the filename of a subtitle image if one exists for a given thumb index.
358  *  @param Thumbnail index.
359  *  @return Position of the image within the source frame, and the image filename, if one exists.
360  *  Otherwise the filename will be empty.
361  */
362 pair<Position, string>
363 Film::thumb_subtitle (int n) const
364 {
365         string sub_file = thumb_base(n) + ".sub";
366         if (!boost::filesystem::exists (sub_file)) {
367                 return pair<Position, string> ();
368         }
369
370         pair<Position, string> sub;
371         
372         ifstream f (sub_file.c_str ());
373         multimap<string, string> kv = read_key_value (f);
374         for (map<string, string>::const_iterator i = kv.begin(); i != kv.end(); ++i) {
375                 if (i->first == "x") {
376                         sub.first.x = lexical_cast<int> (i->second);
377                 } else if (i->first == "y") {
378                         sub.first.y = lexical_cast<int> (i->second);
379                         sub.second = String::compose ("%1.sub.png", thumb_base(n));
380                 }
381         }
382         
383         return sub;
384 }
385
386 /** Write state to our `metadata' file */
387 void
388 Film::write_metadata () const
389 {
390         boost::mutex::scoped_lock lm (_state_mutex);
391
392         boost::filesystem::create_directories (directory());
393
394         string const m = file ("metadata");
395         ofstream f (m.c_str ());
396         if (!f.good ()) {
397                 throw CreateFileError (m);
398         }
399
400         /* User stuff */
401         f << "name " << _name << "\n";
402         f << "use_dci_name " << _use_dci_name << "\n";
403         f << "content " << _content << "\n";
404         if (_dcp_content_type) {
405                 f << "dcp_content_type " << _dcp_content_type->pretty_name () << "\n";
406         }
407         if (_format) {
408                 f << "format " << _format->as_metadata () << "\n";
409         }
410         f << "left_crop " << _crop.left << "\n";
411         f << "right_crop " << _crop.right << "\n";
412         f << "top_crop " << _crop.top << "\n";
413         f << "bottom_crop " << _crop.bottom << "\n";
414         for (vector<Filter const *>::const_iterator i = _filters.begin(); i != _filters.end(); ++i) {
415                 f << "filter " << (*i)->id () << "\n";
416         }
417         f << "scaler " << _scaler->id () << "\n";
418         f << "dcp_trim_start " << _dcp_trim_start << "\n";
419         f << "dcp_trim_end " << _dcp_trim_end << "\n";
420         f << "dcp_ab " << (_dcp_ab ? "1" : "0") << "\n";
421         f << "use_content_audio " << (_use_content_audio ? "1" : "0") << "\n";
422         if (_audio_stream) {
423                 f << "selected_audio_stream " << _audio_stream.get().to_string() << "\n";
424         }
425         for (vector<string>::const_iterator i = _external_audio.begin(); i != _external_audio.end(); ++i) {
426                 f << "external_audio " << *i << "\n";
427         }
428         f << "audio_gain " << _audio_gain << "\n";
429         f << "audio_delay " << _audio_delay << "\n";
430         f << "still_duration " << _still_duration << "\n";
431         if (_subtitle_stream) {
432                 f << "selected_subtitle_stream " << _subtitle_stream.get().to_string() << "\n";
433         }
434         f << "with_subtitles " << _with_subtitles << "\n";
435         f << "subtitle_offset " << _subtitle_offset << "\n";
436         f << "subtitle_scale " << _subtitle_scale << "\n";
437         f << "audio_language " << _audio_language << "\n";
438         f << "subtitle_language " << _subtitle_language << "\n";
439         f << "territory " << _territory << "\n";
440         f << "rating " << _rating << "\n";
441         f << "studio " << _studio << "\n";
442         f << "facility " << _facility << "\n";
443         f << "package_type " << _package_type << "\n";
444
445         /* Cached stuff; this is information about our content; we could
446            look it up each time, but that's slow.
447         */
448         for (vector<SourceFrame>::const_iterator i = _thumbs.begin(); i != _thumbs.end(); ++i) {
449                 f << "thumb " << *i << "\n";
450         }
451         f << "width " << _size.width << "\n";
452         f << "height " << _size.height << "\n";
453         f << "length " << _length.get_value_or(0) << "\n";
454         f << "content_digest " << _content_digest << "\n";
455
456         for (vector<AudioStream>::const_iterator i = _audio_streams.begin(); i != _audio_streams.end(); ++i) {
457                 f << "audio_stream " << i->to_string () << "\n";
458         }
459
460         for (vector<SubtitleStream>::const_iterator i = _subtitle_streams.begin(); i != _subtitle_streams.end(); ++i) {
461                 f << "subtitle_stream " << i->to_string () << "\n";
462         }
463
464         f << "frames_per_second " << _frames_per_second << "\n";
465         
466         _dirty = false;
467 }
468
469 /** Read state from our metadata file */
470 void
471 Film::read_metadata ()
472 {
473         boost::mutex::scoped_lock lm (_state_mutex);
474
475         _external_audio.clear ();
476         _thumbs.clear ();
477         _audio_streams.clear ();
478         _subtitle_streams.clear ();
479         
480         ifstream f (file ("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_trim_start") {
510                         _dcp_trim_start = atoi (v.c_str ());
511                 } else if (k == "dcp_trim_end") {
512                         _dcp_trim_end = atoi (v.c_str ());
513                 } else if (k == "dcp_ab") {
514                         _dcp_ab = (v == "1");
515                 } else if (k == "use_content_audio") {
516                         _use_content_audio = (v == "1");
517                 } else if (k == "selected_audio_stream") {
518                         _audio_stream = AudioStream (v);
519                 } else if (k == "external_audio") {
520                         _external_audio.push_back (v);
521                 } else if (k == "audio_gain") {
522                         _audio_gain = atof (v.c_str ());
523                 } else if (k == "audio_delay") {
524                         _audio_delay = atoi (v.c_str ());
525                 } else if (k == "still_duration") {
526                         _still_duration = atoi (v.c_str ());
527                 } else if (k == "selected_subtitle_stream") {
528                         _subtitle_stream = SubtitleStream (v);
529                 } else if (k == "with_subtitles") {
530                         _with_subtitles = (v == "1");
531                 } else if (k == "subtitle_offset") {
532                         _subtitle_offset = atoi (v.c_str ());
533                 } else if (k == "subtitle_scale") {
534                         _subtitle_scale = atof (v.c_str ());
535                 } else if (k == "audio_language") {
536                         _audio_language = v;
537                 } else if (k == "subtitle_language") {
538                         _subtitle_language = v;
539                 } else if (k == "territory") {
540                         _territory = v;
541                 } else if (k == "rating") {
542                         _rating = v;
543                 } else if (k == "studio") {
544                         _studio = v;
545                 } else if (k == "facility") {
546                         _facility = v;
547                 } else if (k == "package_type") {
548                         _package_type = v;
549                 }
550                 
551                 /* Cached stuff */
552                 if (k == "thumb") {
553                         int const n = atoi (v.c_str ());
554                         /* Only add it to the list if it still exists */
555                         if (boost::filesystem::exists (thumb_file_for_frame (n))) {
556                                 _thumbs.push_back (n);
557                         }
558                 } else if (k == "width") {
559                         _size.width = atoi (v.c_str ());
560                 } else if (k == "height") {
561                         _size.height = atoi (v.c_str ());
562                 } else if (k == "length") {
563                         int const vv = atoi (v.c_str ());
564                         if (vv) {
565                                 _length = vv;
566                         }
567                 } else if (k == "content_digest") {
568                         _content_digest = v;
569                 } else if (k == "audio_stream") {
570                         _audio_streams.push_back (AudioStream (v));
571                 } else if (k == "subtitle_stream") {
572                         _subtitle_streams.push_back (SubtitleStream (v));
573                 } else if (k == "frames_per_second") {
574                         _frames_per_second = atof (v.c_str ());
575                 }
576         }
577                 
578         _dirty = false;
579 }
580
581 /** @param n A thumb index.
582  *  @return The path to the thumb's image file.
583  */
584 string
585 Film::thumb_file (int n) const
586 {
587         return thumb_file_for_frame (thumb_frame (n));
588 }
589
590 /** @param n A frame index within the Film's source.
591  *  @return The path to the thumb's image file for this frame;
592  *  we assume that it exists.
593  */
594 string
595 Film::thumb_file_for_frame (SourceFrame n) const
596 {
597         return thumb_base_for_frame(n) + ".png";
598 }
599
600 /** @param n Thumb index.
601  *  Must not be called with the _state_mutex locked.
602  */
603 string
604 Film::thumb_base (int n) const
605 {
606         return thumb_base_for_frame (thumb_frame (n));
607 }
608
609 string
610 Film::thumb_base_for_frame (SourceFrame n) const
611 {
612         stringstream s;
613         s.width (8);
614         s << setfill('0') << n;
615         
616         boost::filesystem::path p;
617         p /= dir ("thumbs");
618         p /= s.str ();
619                 
620         return p.string ();
621 }
622
623 /** @param n A thumb index.
624  *  @return The frame within the Film's source that it is for.
625  *
626  *  Must not be called with the _state_mutex locked.
627  */
628 SourceFrame
629 Film::thumb_frame (int n) const
630 {
631         boost::mutex::scoped_lock lm (_state_mutex);
632         assert (n < int (_thumbs.size ()));
633         return _thumbs[n];
634 }
635
636 Size
637 Film::cropped_size (Size s) const
638 {
639         boost::mutex::scoped_lock lm (_state_mutex);
640         s.width -= _crop.left + _crop.right;
641         s.height -= _crop.top + _crop.bottom;
642         return s;
643 }
644
645 /** Given a directory name, return its full path within the Film's directory.
646  *  The directory (and its parents) will be created if they do not exist.
647  */
648 string
649 Film::dir (string d) const
650 {
651         boost::mutex::scoped_lock lm (_directory_mutex);
652         boost::filesystem::path p;
653         p /= _directory;
654         p /= d;
655         boost::filesystem::create_directories (p);
656         return p.string ();
657 }
658
659 /** Given a file or directory name, return its full path within the Film's directory.
660  *  _directory_mutex must not be locked on entry.
661  */
662 string
663 Film::file (string f) const
664 {
665         boost::mutex::scoped_lock lm (_directory_mutex);
666         boost::filesystem::path p;
667         p /= _directory;
668         p /= f;
669         return p.string ();
670 }
671
672 /** @return full path of the content (actual video) file
673  *  of the Film.
674  */
675 string
676 Film::content_path () const
677 {
678         boost::mutex::scoped_lock lm (_state_mutex);
679         if (boost::filesystem::path(_content).has_root_directory ()) {
680                 return _content;
681         }
682
683         return file (_content);
684 }
685
686 ContentType
687 Film::content_type () const
688 {
689         if (boost::filesystem::is_directory (_content)) {
690                 /* Directory of images, we assume */
691                 return VIDEO;
692         }
693
694         if (still_image_file (_content)) {
695                 return STILL;
696         }
697
698         return VIDEO;
699 }
700
701 /** @return The sampling rate that we will resample the audio to */
702 int
703 Film::target_audio_sample_rate () const
704 {
705         /* Resample to a DCI-approved sample rate */
706         double t = dcp_audio_sample_rate (audio_stream().get().sample_rate());
707
708         DCPFrameRate dfr = dcp_frame_rate (frames_per_second ());
709
710         /* Compensate for the fact that video will be rounded to the
711            nearest integer number of frames per second.
712         */
713         if (dfr.run_fast) {
714                 t *= _frames_per_second * dfr.skip / dfr.frames_per_second;
715         }
716
717         return rint (t);
718 }
719
720 boost::optional<SourceFrame>
721 Film::dcp_length () const
722 {
723         if (!length()) {
724                 return boost::optional<SourceFrame> ();
725         }
726
727         return length().get() - dcp_trim_start() - dcp_trim_end();
728 }
729
730 /** @return a DCI-compliant name for a DCP of this film */
731 string
732 Film::dci_name () const
733 {
734         stringstream d;
735
736         string fixed_name = to_upper_copy (name());
737         for (size_t i = 0; i < fixed_name.length(); ++i) {
738                 if (fixed_name[i] == ' ') {
739                         fixed_name[i] = '-';
740                 }
741         }
742
743         /* Spec is that the name part should be maximum 14 characters, as I understand it */
744         if (fixed_name.length() > 14) {
745                 fixed_name = fixed_name.substr (0, 14);
746         }
747
748         d << fixed_name << "_";
749
750         if (dcp_content_type()) {
751                 d << dcp_content_type()->dci_name() << "_";
752         }
753
754         if (format()) {
755                 d << format()->dci_name() << "_";
756         }
757
758         if (!audio_language().empty ()) {
759                 d << audio_language();
760                 if (!subtitle_language().empty() && with_subtitles()) {
761                         d << "-" << subtitle_language();
762                 } else {
763                         d << "-XX";
764                 }
765                         
766                 d << "_";
767         }
768
769         if (!territory().empty ()) {
770                 d << territory();
771                 if (!rating().empty ()) {
772                         d << "-" << rating();
773                 }
774                 d << "_";
775         }
776
777         switch (audio_channels()) {
778         case 1:
779                 d << "10_";
780                 break;
781         case 2:
782                 d << "20_";
783                 break;
784         case 6:
785                 d << "51_";
786                 break;
787         case 8:
788                 d << "71_";
789                 break;
790         }
791
792         d << "2K_";
793
794         if (!studio().empty ()) {
795                 d << studio() << "_";
796         }
797
798         d << boost::gregorian::to_iso_string (_dci_date) << "_";
799
800         if (!facility().empty ()) {
801                 d << facility() << "_";
802         }
803
804         if (!package_type().empty ()) {
805                 d << package_type();
806         }
807
808         return d.str ();
809 }
810
811 /** @return name to give the DCP */
812 string
813 Film::dcp_name () const
814 {
815         if (use_dci_name()) {
816                 return dci_name ();
817         }
818
819         return name();
820 }
821
822
823 void
824 Film::set_directory (string d)
825 {
826         boost::mutex::scoped_lock lm (_state_mutex);
827         _directory = d;
828         _dirty = true;
829 }
830
831 void
832 Film::set_name (string n)
833 {
834         {
835                 boost::mutex::scoped_lock lm (_state_mutex);
836                 _name = n;
837         }
838         signal_changed (NAME);
839 }
840
841 void
842 Film::set_use_dci_name (bool u)
843 {
844         {
845                 boost::mutex::scoped_lock lm (_state_mutex);
846                 _use_dci_name = u;
847         }
848         signal_changed (USE_DCI_NAME);
849 }
850
851 void
852 Film::set_content (string c)
853 {
854         string check = directory ();
855
856 #if BOOST_FILESYSTEM_VERSION == 3
857         boost::filesystem::path slash ("/");
858         string platform_slash = slash.make_preferred().string ();
859 #else
860 #ifdef DVDOMATIC_WINDOWS
861         string platform_slash = "\\";
862 #else
863         string platform_slash = "/";
864 #endif
865 #endif  
866
867         if (!ends_with (check, platform_slash)) {
868                 check += platform_slash;
869         }
870         
871         if (boost::filesystem::path(c).has_root_directory () && starts_with (c, check)) {
872                 c = c.substr (_directory.length() + 1);
873         }
874
875         string old_content;
876         
877         {
878                 boost::mutex::scoped_lock lm (_state_mutex);
879                 if (c == _content) {
880                         return;
881                 }
882
883                 old_content = _content;
884                 _content = c;
885         }
886
887         _audio_stream = optional<AudioStream> ();
888         _subtitle_stream = optional<SubtitleStream> ();
889
890         /* Create a temporary decoder so that we can get information
891            about the content.
892         */
893
894         try {
895                 shared_ptr<Options> o (new Options ("", "", ""));
896                 o->out_size = Size (1024, 1024);
897                 
898                 shared_ptr<Decoder> d = decoder_factory (shared_from_this(), o, 0);
899                 
900                 set_size (d->native_size ());
901                 set_frames_per_second (d->frames_per_second ());
902                 set_audio_streams (d->audio_streams ());
903                 set_subtitle_streams (d->subtitle_streams ());
904
905                 /* Start off with the first audio and subtitle streams */
906                 if (!d->audio_streams().empty()) {
907                         set_audio_stream (d->audio_streams().front());
908                 }
909                 
910                 if (!d->subtitle_streams().empty()) {
911                         set_subtitle_stream (d->subtitle_streams().front());
912                 }
913                 
914                 {
915                         boost::mutex::scoped_lock lm (_state_mutex);
916                         _content = c;
917                 }
918                 
919                 signal_changed (CONTENT);
920                 
921                 set_content_digest (md5_digest (content_path ()));
922                 
923                 examine_content ();
924
925         } catch (...) {
926
927                 boost::mutex::scoped_lock lm (_state_mutex);
928                 _content = old_content;
929                 throw;
930
931         }
932 }
933                
934 void
935 Film::set_dcp_content_type (DCPContentType const * t)
936 {
937         {
938                 boost::mutex::scoped_lock lm (_state_mutex);
939                 _dcp_content_type = t;
940         }
941         signal_changed (DCP_CONTENT_TYPE);
942 }
943
944 void
945 Film::set_format (Format const * f)
946 {
947         {
948                 boost::mutex::scoped_lock lm (_state_mutex);
949                 _format = f;
950         }
951         signal_changed (FORMAT);
952 }
953
954 void
955 Film::set_crop (Crop c)
956 {
957         {
958                 boost::mutex::scoped_lock lm (_state_mutex);
959                 _crop = c;
960         }
961         signal_changed (CROP);
962 }
963
964 void
965 Film::set_left_crop (int c)
966 {
967         {
968                 boost::mutex::scoped_lock lm (_state_mutex);
969                 
970                 if (_crop.left == c) {
971                         return;
972                 }
973                 
974                 _crop.left = c;
975         }
976         signal_changed (CROP);
977 }
978
979 void
980 Film::set_right_crop (int c)
981 {
982         {
983                 boost::mutex::scoped_lock lm (_state_mutex);
984                 if (_crop.right == c) {
985                         return;
986                 }
987                 
988                 _crop.right = c;
989         }
990         signal_changed (CROP);
991 }
992
993 void
994 Film::set_top_crop (int c)
995 {
996         {
997                 boost::mutex::scoped_lock lm (_state_mutex);
998                 if (_crop.top == c) {
999                         return;
1000                 }
1001                 
1002                 _crop.top = c;
1003         }
1004         signal_changed (CROP);
1005 }
1006
1007 void
1008 Film::set_bottom_crop (int c)
1009 {
1010         {
1011                 boost::mutex::scoped_lock lm (_state_mutex);
1012                 if (_crop.bottom == c) {
1013                         return;
1014                 }
1015                 
1016                 _crop.bottom = c;
1017         }
1018         signal_changed (CROP);
1019 }
1020
1021 void
1022 Film::set_filters (vector<Filter const *> f)
1023 {
1024         {
1025                 boost::mutex::scoped_lock lm (_state_mutex);
1026                 _filters = f;
1027         }
1028         signal_changed (FILTERS);
1029 }
1030
1031 void
1032 Film::set_scaler (Scaler const * s)
1033 {
1034         {
1035                 boost::mutex::scoped_lock lm (_state_mutex);
1036                 _scaler = s;
1037         }
1038         signal_changed (SCALER);
1039 }
1040
1041 void
1042 Film::set_dcp_trim_start (int t)
1043 {
1044         {
1045                 boost::mutex::scoped_lock lm (_state_mutex);
1046                 _dcp_trim_start = t;
1047         }
1048         signal_changed (DCP_TRIM_START);
1049 }
1050
1051 void
1052 Film::set_dcp_trim_end (int t)
1053 {
1054         {
1055                 boost::mutex::scoped_lock lm (_state_mutex);
1056                 _dcp_trim_end = t;
1057         }
1058         signal_changed (DCP_TRIM_END);
1059 }
1060
1061 void
1062 Film::set_dcp_ab (bool a)
1063 {
1064         {
1065                 boost::mutex::scoped_lock lm (_state_mutex);
1066                 _dcp_ab = a;
1067         }
1068         signal_changed (DCP_AB);
1069 }
1070
1071 void
1072 Film::set_use_content_audio (bool s)
1073 {
1074         {
1075                 boost::mutex::scoped_lock lm (_state_mutex);
1076                 _use_content_audio = s;
1077         }
1078         signal_changed (USE_CONTENT_AUDIO);
1079 }
1080
1081 void
1082 Film::set_audio_stream (optional<AudioStream> s)
1083 {
1084         {
1085                 boost::mutex::scoped_lock lm (_state_mutex);
1086                 _audio_stream = s;
1087         }
1088         signal_changed (AUDIO_STREAM);
1089 }
1090
1091 void
1092 Film::set_external_audio (vector<string> a)
1093 {
1094         {
1095                 boost::mutex::scoped_lock lm (_state_mutex);
1096                 _external_audio = a;
1097         }
1098         signal_changed (EXTERNAL_AUDIO);
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 (optional<SubtitleStream> 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<SourceFrame> 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 (SourceFrame 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_content_digest (string d)
1283 {
1284         {
1285                 boost::mutex::scoped_lock lm (_state_mutex);
1286                 _content_digest = d;
1287         }
1288         _dirty = true;
1289 }
1290
1291 void
1292 Film::set_audio_streams (vector<AudioStream> s)
1293 {
1294         {
1295                 boost::mutex::scoped_lock lm (_state_mutex);
1296                 _audio_streams = s;
1297         }
1298         _dirty = true;
1299 }
1300
1301 void
1302 Film::set_subtitle_streams (vector<SubtitleStream> s)
1303 {
1304         {
1305                 boost::mutex::scoped_lock lm (_state_mutex);
1306                 _subtitle_streams = s;
1307         }
1308         _dirty = true;
1309 }
1310
1311 void
1312 Film::set_frames_per_second (float f)
1313 {
1314         {
1315                 boost::mutex::scoped_lock lm (_state_mutex);
1316                 _frames_per_second = f;
1317         }
1318         signal_changed (FRAMES_PER_SECOND);
1319 }
1320         
1321 void
1322 Film::signal_changed (Property p)
1323 {
1324         {
1325                 boost::mutex::scoped_lock lm (_state_mutex);
1326                 _dirty = true;
1327         }
1328
1329         if (ui_signaller) {
1330                 ui_signaller->emit (boost::bind (boost::ref (Changed), p));
1331         }
1332 }
1333
1334 int
1335 Film::audio_channels () const
1336 {
1337         boost::mutex::scoped_lock lm (_state_mutex);
1338         
1339         if (_use_content_audio) {
1340                 if (_audio_stream) {
1341                         return _audio_stream.get().channels ();
1342                 }
1343         } else {
1344                 int last_filled = -1;
1345                 for (size_t i = 0; i < _external_audio.size(); ++i) {
1346                         if (!_external_audio[i].empty()) {
1347                                 last_filled = i;
1348                         }
1349                 }
1350                 
1351                 return last_filled + 1;
1352         }
1353
1354         return 0;
1355 }
1356
1357 void
1358 Film::set_dci_date_today ()
1359 {
1360         _dci_date = boost::gregorian::day_clock::local_day ();
1361 }
1362