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