Skeletal remains.
[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 "job.h"
35 #include "filter.h"
36 #include "transcoder.h"
37 #include "util.h"
38 #include "job_manager.h"
39 #include "ab_transcode_job.h"
40 #include "transcode_job.h"
41 #include "scp_dcp_job.h"
42 #include "log.h"
43 #include "options.h"
44 #include "exceptions.h"
45 #include "examine_content_job.h"
46 #include "scaler.h"
47 #include "decoder_factory.h"
48 #include "config.h"
49 #include "version.h"
50 #include "ui_signaller.h"
51 #include "video_decoder.h"
52 #include "audio_decoder.h"
53 #include "sndfile_decoder.h"
54 #include "analyse_audio_job.h"
55
56 #include "i18n.h"
57
58 using std::string;
59 using std::stringstream;
60 using std::multimap;
61 using std::pair;
62 using std::map;
63 using std::vector;
64 using std::ifstream;
65 using std::ofstream;
66 using std::setfill;
67 using std::min;
68 using std::make_pair;
69 using std::endl;
70 using boost::shared_ptr;
71 using boost::lexical_cast;
72 using boost::to_upper_copy;
73 using boost::ends_with;
74 using boost::starts_with;
75 using boost::optional;
76 using libdcp::Size;
77
78 int const Film::state_version = 4;
79
80 /** Construct a Film object in a given directory, reading any metadata
81  *  file that exists in that directory.  An exception will be thrown if
82  *  must_exist is true and the specified directory does not exist.
83  *
84  *  @param d Film directory.
85  *  @param must_exist true to throw an exception if does not exist.
86  */
87
88 Film::Film (string d, bool must_exist)
89         : _use_dci_name (true)
90         , _trust_content_header (true)
91         , _dcp_content_type (0)
92         , _format (0)
93         , _scaler (Scaler::from_id ("bicubic"))
94         , _trim_start (0)
95         , _trim_end (0)
96         , _dcp_ab (false)
97         , _audio_gain (0)
98         , _audio_delay (0)
99         , _with_subtitles (false)
100         , _subtitle_offset (0)
101         , _subtitle_scale (1)
102         , _colour_lut (0)
103         , _j2k_bandwidth (200000000)
104         , _dci_metadata (Config::instance()->default_dci_metadata ())
105         , _dcp_frame_rate (0)
106         , _dirty (false)
107 {
108         set_dci_date_today ();
109         
110         /* Make state.directory a complete path without ..s (where possible)
111            (Code swiped from Adam Bowen on stackoverflow)
112         */
113         
114         boost::filesystem::path p (boost::filesystem::system_complete (d));
115         boost::filesystem::path result;
116         for (boost::filesystem::path::iterator i = p.begin(); i != p.end(); ++i) {
117                 if (*i == "..") {
118                         if (boost::filesystem::is_symlink (result) || result.filename() == "..") {
119                                 result /= *i;
120                         } else {
121                                 result = result.parent_path ();
122                         }
123                 } else if (*i != ".") {
124                         result /= *i;
125                 }
126         }
127
128         set_directory (result.string ());
129         
130         if (!boost::filesystem::exists (directory())) {
131                 if (must_exist) {
132                         throw OpenFileError (directory());
133                 } else {
134                         boost::filesystem::create_directory (directory());
135                 }
136         }
137
138         _sndfile_stream = SndfileStream::create ();
139         
140         if (must_exist) {
141                 read_metadata ();
142         }
143
144         _log.reset (new FileLog (file ("log")));
145 }
146
147 Film::Film (Film const & o)
148         : boost::enable_shared_from_this<Film> (o)
149         /* note: the copied film shares the original's log */
150         , _log               (o._log)
151         , _directory         (o._directory)
152         , _name              (o._name)
153         , _use_dci_name      (o._use_dci_name)
154         , _trust_content_header (o._trust_content_header)
155         , _dcp_content_type  (o._dcp_content_type)
156         , _format            (o._format)
157         , _crop              (o._crop)
158         , _filters           (o._filters)
159         , _scaler            (o._scaler)
160         , _trim_start        (o._trim_start)
161         , _trim_end          (o._trim_end)
162         , _dcp_ab            (o._dcp_ab)
163         , _audio_gain        (o._audio_gain)
164         , _audio_delay       (o._audio_delay)
165         , _still_duration    (o._still_duration)
166         , _with_subtitles    (o._with_subtitles)
167         , _subtitle_offset   (o._subtitle_offset)
168         , _subtitle_scale    (o._subtitle_scale)
169         , _colour_lut        (o._colour_lut)
170         , _j2k_bandwidth     (o._j2k_bandwidth)
171         , _dci_metadata      (o._dci_metadata)
172         , _dci_date          (o._dci_date)
173         , _dcp_frame_rate    (o._dcp_frame_rate)
174         , _dirty             (o._dirty)
175 {
176         
177 }
178
179 Film::~Film ()
180 {
181
182 }
183
184 string
185 Film::video_state_identifier () const
186 {
187         assert (format ());
188
189         pair<string, string> f = Filter::ffmpeg_strings (filters());
190
191         stringstream s;
192         s << format()->id()
193           << "_" << content_digest()
194           << "_" << crop().left << "_" << crop().right << "_" << crop().top << "_" << crop().bottom
195           << "_" << _dcp_frame_rate
196           << "_" << f.first << "_" << f.second
197           << "_" << scaler()->id()
198           << "_" << j2k_bandwidth()
199           << "_" << boost::lexical_cast<int> (colour_lut());
200
201         if (dcp_ab()) {
202                 pair<string, string> fa = Filter::ffmpeg_strings (Config::instance()->reference_filters());
203                 s << "ab_" << Config::instance()->reference_scaler()->id() << "_" << fa.first << "_" << fa.second;
204         }
205
206         return s.str ();
207 }
208           
209 /** @return The path to the directory to write video frame info files to */
210 string
211 Film::info_dir () const
212 {
213         boost::filesystem::path p;
214         p /= "info";
215         p /= video_state_identifier ();
216         return dir (p.string());
217 }
218
219 string
220 Film::video_mxf_dir () const
221 {
222         boost::filesystem::path p;
223         return dir ("video");
224 }
225
226 string
227 Film::video_mxf_filename () const
228 {
229         return video_state_identifier() + ".mxf";
230 }
231
232 string
233 Film::audio_analysis_path () const
234 {
235         boost::filesystem::path p;
236         p /= "analysis";
237         p /= content_digest();
238         return file (p.string ());
239 }
240
241 /** Add suitable Jobs to the JobManager to create a DCP for this Film */
242 void
243 Film::make_dcp ()
244 {
245         set_dci_date_today ();
246         
247         if (dcp_name().find ("/") != string::npos) {
248                 throw BadSettingError (_("name"), _("cannot contain slashes"));
249         }
250         
251         log()->log (String::compose ("DVD-o-matic %1 git %2 using %3", dvdomatic_version, dvdomatic_git_commit, dependency_version_summary()));
252
253         {
254                 char buffer[128];
255                 gethostname (buffer, sizeof (buffer));
256                 log()->log (String::compose ("Starting to make DCP on %1", buffer));
257         }
258         
259         log()->log (String::compose ("Content is %1; type %2", content_path(), (content_type() == STILL ? _("still") : _("video"))));
260         if (length()) {
261                 log()->log (String::compose ("Content length %1", length().get()));
262         }
263         log()->log (String::compose ("Content digest %1", content_digest()));
264         log()->log (String::compose ("Content at %1 fps, DCP at %2 fps", source_frame_rate(), dcp_frame_rate()));
265         log()->log (String::compose ("%1 threads", Config::instance()->num_local_encoding_threads()));
266         log()->log (String::compose ("J2K bandwidth %1", j2k_bandwidth()));
267 #ifdef DVDOMATIC_DEBUG
268         log()->log ("DVD-o-matic built in debug mode.");
269 #else
270         log()->log ("DVD-o-matic built in optimised mode.");
271 #endif
272 #ifdef LIBDCP_DEBUG
273         log()->log ("libdcp built in debug mode.");
274 #else
275         log()->log ("libdcp built in optimised mode.");
276 #endif
277         pair<string, int> const c = cpu_info ();
278         log()->log (String::compose ("CPU: %1, %2 processors", c.first, c.second));
279         
280         if (format() == 0) {
281                 throw MissingSettingError (_("format"));
282         }
283
284         if (content().empty ()) {
285                 throw MissingSettingError (_("content"));
286         }
287
288         if (dcp_content_type() == 0) {
289                 throw MissingSettingError (_("content type"));
290         }
291
292         if (name().empty()) {
293                 throw MissingSettingError (_("name"));
294         }
295
296         DecodeOptions od;
297         od.decode_subtitles = with_subtitles ();
298
299         shared_ptr<Job> r;
300
301         if (dcp_ab()) {
302                 r = JobManager::instance()->add (shared_ptr<Job> (new ABTranscodeJob (shared_from_this(), od)));
303         } else {
304                 r = JobManager::instance()->add (shared_ptr<Job> (new TranscodeJob (shared_from_this(), od)));
305         }
306 }
307
308 /** Start a job to analyse the audio of our content file */
309 void
310 Film::analyse_audio ()
311 {
312         if (_analyse_audio_job) {
313                 return;
314         }
315
316         _analyse_audio_job.reset (new AnalyseAudioJob (shared_from_this()));
317         _analyse_audio_job->Finished.connect (bind (&Film::analyse_audio_finished, this));
318         JobManager::instance()->add (_analyse_audio_job);
319 }
320
321 /** Start a job to examine our content file */
322 void
323 Film::examine_content ()
324 {
325         if (_examine_content_job) {
326                 return;
327         }
328
329         _examine_content_job.reset (new ExamineContentJob (shared_from_this()));
330         _examine_content_job->Finished.connect (bind (&Film::examine_content_finished, this));
331         JobManager::instance()->add (_examine_content_job);
332 }
333
334 void
335 Film::analyse_audio_finished ()
336 {
337         ensure_ui_thread ();
338
339         if (_analyse_audio_job->finished_ok ()) {
340                 AudioAnalysisSucceeded ();
341         }
342         
343         _analyse_audio_job.reset ();
344 }
345
346 void
347 Film::examine_content_finished ()
348 {
349         _examine_content_job.reset ();
350 }
351
352 /** Start a job to send our DCP to the configured TMS */
353 void
354 Film::send_dcp_to_tms ()
355 {
356         shared_ptr<Job> j (new SCPDCPJob (shared_from_this()));
357         JobManager::instance()->add (j);
358 }
359
360 /** Count the number of frames that have been encoded for this film.
361  *  @return frame count.
362  */
363 int
364 Film::encoded_frames () const
365 {
366         if (format() == 0) {
367                 return 0;
368         }
369
370         int N = 0;
371         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator (info_dir ()); i != boost::filesystem::directory_iterator(); ++i) {
372                 ++N;
373                 boost::this_thread::interruption_point ();
374         }
375
376         return N;
377 }
378
379 /** Write state to our `metadata' file */
380 void
381 Film::write_metadata () const
382 {
383         boost::mutex::scoped_lock lm (_state_mutex);
384
385         boost::filesystem::create_directories (directory());
386
387         string const m = file ("metadata");
388         ofstream f (m.c_str ());
389         if (!f.good ()) {
390                 throw CreateFileError (m);
391         }
392
393         f << "version " << state_version << endl;
394
395         /* User stuff */
396         f << "name " << _name << endl;
397         f << "use_dci_name " << _use_dci_name << endl;
398         f << "content " << _content << endl;
399         f << "trust_content_header " << (_trust_content_header ? "1" : "0") << endl;
400         if (_dcp_content_type) {
401                 f << "dcp_content_type " << _dcp_content_type->dci_name () << endl;
402         }
403         if (_format) {
404                 f << "format " << _format->as_metadata () << endl;
405         }
406         f << "left_crop " << _crop.left << endl;
407         f << "right_crop " << _crop.right << endl;
408         f << "top_crop " << _crop.top << endl;
409         f << "bottom_crop " << _crop.bottom << endl;
410         for (vector<Filter const *>::const_iterator i = _filters.begin(); i != _filters.end(); ++i) {
411                 f << "filter " << (*i)->id () << endl;
412         }
413         f << "scaler " << _scaler->id () << endl;
414         f << "trim_start " << _trim_start << endl;
415         f << "trim_end " << _trim_end << endl;
416         f << "dcp_ab " << (_dcp_ab ? "1" : "0") << endl;
417         if (_content_audio_stream) {
418                 f << "selected_content_audio_stream " << _content_audio_stream->to_string() << endl;
419         }
420         for (vector<string>::const_iterator i = _external_audio.begin(); i != _external_audio.end(); ++i) {
421                 f << "external_audio " << *i << endl;
422         }
423         f << "use_content_audio " << (_use_content_audio ? "1" : "0") << endl;
424         f << "audio_gain " << _audio_gain << endl;
425         f << "audio_delay " << _audio_delay << endl;
426         f << "still_duration " << _still_duration << endl;
427         if (_subtitle_stream) {
428                 f << "selected_subtitle_stream " << _subtitle_stream->to_string() << endl;
429         }
430         f << "with_subtitles " << _with_subtitles << endl;
431         f << "subtitle_offset " << _subtitle_offset << endl;
432         f << "subtitle_scale " << _subtitle_scale << endl;
433         f << "colour_lut " << _colour_lut << endl;
434         f << "j2k_bandwidth " << _j2k_bandwidth << endl;
435         _dci_metadata.write (f);
436         f << "dci_date " << boost::gregorian::to_iso_string (_dci_date) << endl;
437         f << "dcp_frame_rate " << _dcp_frame_rate << endl;
438         f << "width " << _size.width << endl;
439         f << "height " << _size.height << endl;
440         f << "length " << _length.get_value_or(0) << endl;
441         f << "content_digest " << _content_digest << endl;
442
443         for (vector<shared_ptr<AudioStream> >::const_iterator i = _content_audio_streams.begin(); i != _content_audio_streams.end(); ++i) {
444                 f << "content_audio_stream " << (*i)->to_string () << endl;
445         }
446
447         f << "external_audio_stream " << _sndfile_stream->to_string() << endl;
448
449         for (vector<shared_ptr<SubtitleStream> >::const_iterator i = _subtitle_streams.begin(); i != _subtitle_streams.end(); ++i) {
450                 f << "subtitle_stream " << (*i)->to_string () << endl;
451         }
452
453         f << "source_frame_rate " << _source_frame_rate << endl;
454         
455         _dirty = false;
456 }
457
458 /** Read state from our metadata file */
459 void
460 Film::read_metadata ()
461 {
462         boost::mutex::scoped_lock lm (_state_mutex);
463
464         _external_audio.clear ();
465         _content_audio_streams.clear ();
466         _subtitle_streams.clear ();
467
468         boost::optional<int> version;
469
470         /* Backward compatibility things */
471         boost::optional<int> audio_sample_rate;
472         boost::optional<int> audio_stream_index;
473         boost::optional<int> subtitle_stream_index;
474
475         ifstream f (file ("metadata").c_str());
476         if (!f.good()) {
477                 throw OpenFileError (file ("metadata"));
478         }
479         
480         multimap<string, string> kv = read_key_value (f);
481
482         /* We need version before anything else */
483         multimap<string, string>::iterator v = kv.find ("version");
484         if (v != kv.end ()) {
485                 version = atoi (v->second.c_str());
486         }
487         
488         for (multimap<string, string>::const_iterator i = kv.begin(); i != kv.end(); ++i) {
489                 string const k = i->first;
490                 string const v = i->second;
491
492                 if (k == "audio_sample_rate") {
493                         audio_sample_rate = atoi (v.c_str());
494                 }
495
496                 /* User-specified stuff */
497                 if (k == "name") {
498                         _name = v;
499                 } else if (k == "use_dci_name") {
500                         _use_dci_name = (v == "1");
501                 } else if (k == "content") {
502                         _content = v;
503                 } else if (k == "trust_content_header") {
504                         _trust_content_header = (v == "1");
505                 } else if (k == "dcp_content_type") {
506                         if (version < 3) {
507                                 _dcp_content_type = DCPContentType::from_pretty_name (v);
508                         } else {
509                                 _dcp_content_type = DCPContentType::from_dci_name (v);
510                         }
511                 } else if (k == "format") {
512                         _format = Format::from_metadata (v);
513                 } else if (k == "left_crop") {
514                         _crop.left = atoi (v.c_str ());
515                 } else if (k == "right_crop") {
516                         _crop.right = atoi (v.c_str ());
517                 } else if (k == "top_crop") {
518                         _crop.top = atoi (v.c_str ());
519                 } else if (k == "bottom_crop") {
520                         _crop.bottom = atoi (v.c_str ());
521                 } else if (k == "filter") {
522                         _filters.push_back (Filter::from_id (v));
523                 } else if (k == "scaler") {
524                         _scaler = Scaler::from_id (v);
525                 } else if ( ((!version || version < 2) && k == "dcp_trim_start") || k == "trim_start") {
526                         _trim_start = atoi (v.c_str ());
527                 } else if ( ((!version || version < 2) && k == "dcp_trim_end") || k == "trim_end") {
528                         _trim_end = atoi (v.c_str ());
529                 } else if (k == "dcp_ab") {
530                         _dcp_ab = (v == "1");
531                 } else if (k == "selected_content_audio_stream" || (!version && k == "selected_audio_stream")) {
532                         if (!version) {
533                                 audio_stream_index = atoi (v.c_str ());
534                         } else {
535                                 _content_audio_stream = audio_stream_factory (v, version);
536                         }
537                 } else if (k == "external_audio") {
538                         _external_audio.push_back (v);
539                 } else if (k == "use_content_audio") {
540                         _use_content_audio = (v == "1");
541                 } else if (k == "audio_gain") {
542                         _audio_gain = atof (v.c_str ());
543                 } else if (k == "audio_delay") {
544                         _audio_delay = atoi (v.c_str ());
545                 } else if (k == "still_duration") {
546                         _still_duration = atoi (v.c_str ());
547                 } else if (k == "selected_subtitle_stream") {
548                         if (!version) {
549                                 subtitle_stream_index = atoi (v.c_str ());
550                         } else {
551                                 _subtitle_stream = subtitle_stream_factory (v, version);
552                         }
553                 } else if (k == "with_subtitles") {
554                         _with_subtitles = (v == "1");
555                 } else if (k == "subtitle_offset") {
556                         _subtitle_offset = atoi (v.c_str ());
557                 } else if (k == "subtitle_scale") {
558                         _subtitle_scale = atof (v.c_str ());
559                 } else if (k == "colour_lut") {
560                         _colour_lut = atoi (v.c_str ());
561                 } else if (k == "j2k_bandwidth") {
562                         _j2k_bandwidth = atoi (v.c_str ());
563                 } else if (k == "dci_date") {
564                         _dci_date = boost::gregorian::from_undelimited_string (v);
565                 } else if (k == "dcp_frame_rate") {
566                         _dcp_frame_rate = atoi (v.c_str ());
567                 }
568
569                 _dci_metadata.read (k, v);
570                 
571                 /* Cached stuff */
572                 if (k == "width") {
573                         _size.width = atoi (v.c_str ());
574                 } else if (k == "height") {
575                         _size.height = atoi (v.c_str ());
576                 } else if (k == "length") {
577                         int const vv = atoi (v.c_str ());
578                         if (vv) {
579                                 _length = vv;
580                         }
581                 } else if (k == "content_digest") {
582                         _content_digest = v;
583                 } else if (k == "content_audio_stream" || (!version && k == "audio_stream")) {
584                         _content_audio_streams.push_back (audio_stream_factory (v, version));
585                 } else if (k == "external_audio_stream") {
586                         _sndfile_stream = audio_stream_factory (v, version);
587                 } else if (k == "subtitle_stream") {
588                         _subtitle_streams.push_back (subtitle_stream_factory (v, version));
589                 } else if (k == "source_frame_rate") {
590                         _source_frame_rate = atof (v.c_str ());
591                 } else if (version < 4 && k == "frames_per_second") {
592                         _source_frame_rate = atof (v.c_str ());
593                         /* Fill in what would have been used for DCP frame rate by the older version */
594                         _dcp_frame_rate = best_dcp_frame_rate (_source_frame_rate);
595                 }
596         }
597
598         if (!version) {
599                 if (audio_sample_rate) {
600                         /* version < 1 didn't specify sample rate in the audio streams, so fill it in here */
601                         for (vector<shared_ptr<AudioStream> >::iterator i = _content_audio_streams.begin(); i != _content_audio_streams.end(); ++i) {
602                                 (*i)->set_sample_rate (audio_sample_rate.get());
603                         }
604                 }
605
606                 /* also the selected stream was specified as an index */
607                 if (audio_stream_index && audio_stream_index.get() >= 0 && audio_stream_index.get() < (int) _content_audio_streams.size()) {
608                         _content_audio_stream = _content_audio_streams[audio_stream_index.get()];
609                 }
610
611                 /* similarly the subtitle */
612                 if (subtitle_stream_index && subtitle_stream_index.get() >= 0 && subtitle_stream_index.get() < (int) _subtitle_streams.size()) {
613                         _subtitle_stream = _subtitle_streams[subtitle_stream_index.get()];
614                 }
615         }
616                 
617         _dirty = false;
618 }
619
620 libdcp::Size
621 Film::cropped_size (libdcp::Size s) const
622 {
623         boost::mutex::scoped_lock lm (_state_mutex);
624         s.width -= _crop.left + _crop.right;
625         s.height -= _crop.top + _crop.bottom;
626         return s;
627 }
628
629 /** Given a directory name, return its full path within the Film's directory.
630  *  The directory (and its parents) will be created if they do not exist.
631  */
632 string
633 Film::dir (string d) const
634 {
635         boost::mutex::scoped_lock lm (_directory_mutex);
636         
637         boost::filesystem::path p;
638         p /= _directory;
639         p /= d;
640         
641         boost::filesystem::create_directories (p);
642         
643         return p.string ();
644 }
645
646 /** Given a file or directory name, return its full path within the Film's directory.
647  *  _directory_mutex must not be locked on entry.
648  *  Any required parent directories will be created.
649  */
650 string
651 Film::file (string f) const
652 {
653         boost::mutex::scoped_lock lm (_directory_mutex);
654
655         boost::filesystem::path p;
656         p /= _directory;
657         p /= f;
658
659         boost::filesystem::create_directories (p.parent_path ());
660         
661         return p.string ();
662 }
663
664 /** @return full path of the content (actual video) file
665  *  of the Film.
666  */
667 string
668 Film::content_path () const
669 {
670         boost::mutex::scoped_lock lm (_state_mutex);
671         if (boost::filesystem::path(_content).has_root_directory ()) {
672                 return _content;
673         }
674
675         return file (_content);
676 }
677
678 ContentType
679 Film::content_type () const
680 {
681         if (boost::filesystem::is_directory (_content)) {
682                 /* Directory of images, we assume */
683                 return VIDEO;
684         }
685
686         if (still_image_file (_content)) {
687                 return STILL;
688         }
689
690         return VIDEO;
691 }
692
693 /** @return The sampling rate that we will resample the audio to */
694 int
695 Film::target_audio_sample_rate () const
696 {
697         if (!audio_stream()) {
698                 return 0;
699         }
700         
701         /* Resample to a DCI-approved sample rate */
702         double t = dcp_audio_sample_rate (audio_stream()->sample_rate());
703
704         FrameRateConversion frc (source_frame_rate(), dcp_frame_rate());
705
706         /* Compensate if the DCP is being run at a different frame rate
707            to the source; that is, if the video is run such that it will
708            look different in the DCP compared to the source (slower or faster).
709            skip/repeat doesn't come into effect here.
710         */
711
712         if (frc.change_speed) {
713                 t *= source_frame_rate() * frc.factor() / dcp_frame_rate();
714         }
715
716         return rint (t);
717 }
718
719 int
720 Film::still_duration_in_frames () const
721 {
722         return still_duration() * source_frame_rate();
723 }
724
725 /** @return a DCI-compliant name for a DCP of this film */
726 string
727 Film::dci_name (bool if_created_now) const
728 {
729         stringstream d;
730
731         string fixed_name = to_upper_copy (name());
732         for (size_t i = 0; i < fixed_name.length(); ++i) {
733                 if (fixed_name[i] == ' ') {
734                         fixed_name[i] = '-';
735                 }
736         }
737
738         /* Spec is that the name part should be maximum 14 characters, as I understand it */
739         if (fixed_name.length() > 14) {
740                 fixed_name = fixed_name.substr (0, 14);
741         }
742
743         d << fixed_name;
744
745         if (dcp_content_type()) {
746                 d << "_" << dcp_content_type()->dci_name();
747         }
748
749         if (format()) {
750                 d << "_" << format()->dci_name();
751         }
752
753         DCIMetadata const dm = dci_metadata ();
754
755         if (!dm.audio_language.empty ()) {
756                 d << "_" << dm.audio_language;
757                 if (!dm.subtitle_language.empty()) {
758                         d << "-" << dm.subtitle_language;
759                 } else {
760                         d << "-XX";
761                 }
762         }
763
764         if (!dm.territory.empty ()) {
765                 d << "_" << dm.territory;
766                 if (!dm.rating.empty ()) {
767                         d << "-" << dm.rating;
768                 }
769         }
770
771         switch (audio_channels()) {
772         case 1:
773                 d << "_10";
774                 break;
775         case 2:
776                 d << "_20";
777                 break;
778         case 6:
779                 d << "_51";
780                 break;
781         case 8:
782                 d << "_71";
783                 break;
784         }
785
786         d << "_2K";
787
788         if (!dm.studio.empty ()) {
789                 d << "_" << dm.studio;
790         }
791
792         if (if_created_now) {
793                 d << "_" << boost::gregorian::to_iso_string (boost::gregorian::day_clock::local_day ());
794         } else {
795                 d << "_" << boost::gregorian::to_iso_string (_dci_date);
796         }
797
798         if (!dm.facility.empty ()) {
799                 d << "_" << dm.facility;
800         }
801
802         if (!dm.package_type.empty ()) {
803                 d << "_" << dm.package_type;
804         }
805
806         return d.str ();
807 }
808
809 /** @return name to give the DCP */
810 string
811 Film::dcp_name (bool if_created_now) const
812 {
813         if (use_dci_name()) {
814                 return dci_name (if_created_now);
815         }
816
817         return name();
818 }
819
820
821 void
822 Film::set_directory (string d)
823 {
824         boost::mutex::scoped_lock lm (_state_mutex);
825         _directory = d;
826         _dirty = true;
827 }
828
829 void
830 Film::set_name (string n)
831 {
832         {
833                 boost::mutex::scoped_lock lm (_state_mutex);
834                 _name = n;
835         }
836         signal_changed (NAME);
837 }
838
839 void
840 Film::set_use_dci_name (bool u)
841 {
842         {
843                 boost::mutex::scoped_lock lm (_state_mutex);
844                 _use_dci_name = u;
845         }
846         signal_changed (USE_DCI_NAME);
847 }
848
849 void
850 Film::set_content (string c)
851 {
852         string check = directory ();
853
854         boost::filesystem::path slash ("/");
855         string platform_slash = slash.make_preferred().string ();
856
857         if (!ends_with (check, platform_slash)) {
858                 check += platform_slash;
859         }
860         
861         if (boost::filesystem::path(c).has_root_directory () && starts_with (c, check)) {
862                 c = c.substr (_directory.length() + 1);
863         }
864
865         string old_content;
866         
867         {
868                 boost::mutex::scoped_lock lm (_state_mutex);
869                 if (c == _content) {
870                         return;
871                 }
872
873                 old_content = _content;
874                 _content = c;
875         }
876
877         /* Reset streams here in case the new content doesn't have one or the other */
878         _content_audio_stream = shared_ptr<AudioStream> ();
879         _subtitle_stream = shared_ptr<SubtitleStream> ();
880
881         /* Start off using content audio */
882         set_use_content_audio (true);
883
884         /* Create a temporary decoder so that we can get information
885            about the content.
886         */
887
888         try {
889                 Decoders d = decoder_factory (shared_from_this(), DecodeOptions());
890                 
891                 set_size (d.video->native_size ());
892                 set_source_frame_rate (d.video->frames_per_second ());
893                 set_dcp_frame_rate (best_dcp_frame_rate (source_frame_rate ()));
894                 set_subtitle_streams (d.video->subtitle_streams ());
895                 if (d.audio) {
896                         set_content_audio_streams (d.audio->audio_streams ());
897                 }
898
899                 {
900                         boost::mutex::scoped_lock lm (_state_mutex);
901                         _content = c;
902                 }
903                 
904                 signal_changed (CONTENT);
905                 
906                 /* Start off with the first audio and subtitle streams */
907                 if (d.audio && !d.audio->audio_streams().empty()) {
908                         set_content_audio_stream (d.audio->audio_streams().front());
909                 }
910                 
911                 if (!d.video->subtitle_streams().empty()) {
912                         set_subtitle_stream (d.video->subtitle_streams().front());
913                 }
914                 
915                 examine_content ();
916
917         } catch (...) {
918
919                 boost::mutex::scoped_lock lm (_state_mutex);
920                 _content = old_content;
921                 throw;
922
923         }
924
925         /* Default format */
926         switch (content_type()) {
927         case STILL:
928                 set_format (Format::from_id ("var-185"));
929                 break;
930         case VIDEO:
931                 set_format (Format::from_id ("185"));
932                 break;
933         }
934
935         /* Still image DCPs must use external audio */
936         if (content_type() == STILL) {
937                 set_use_content_audio (false);
938         }
939 }
940
941 void
942 Film::set_trust_content_header (bool t)
943 {
944         {
945                 boost::mutex::scoped_lock lm (_state_mutex);
946                 _trust_content_header = t;
947         }
948         
949         signal_changed (TRUST_CONTENT_HEADER);
950
951         if (!_trust_content_header && !content().empty()) {
952                 /* We just said that we don't trust the content's header */
953                 examine_content ();
954         }
955 }
956                
957 void
958 Film::set_dcp_content_type (DCPContentType const * t)
959 {
960         {
961                 boost::mutex::scoped_lock lm (_state_mutex);
962                 _dcp_content_type = t;
963         }
964         signal_changed (DCP_CONTENT_TYPE);
965 }
966
967 void
968 Film::set_format (Format const * f)
969 {
970         {
971                 boost::mutex::scoped_lock lm (_state_mutex);
972                 _format = f;
973         }
974         signal_changed (FORMAT);
975 }
976
977 void
978 Film::set_crop (Crop c)
979 {
980         {
981                 boost::mutex::scoped_lock lm (_state_mutex);
982                 _crop = c;
983         }
984         signal_changed (CROP);
985 }
986
987 void
988 Film::set_left_crop (int c)
989 {
990         {
991                 boost::mutex::scoped_lock lm (_state_mutex);
992                 
993                 if (_crop.left == c) {
994                         return;
995                 }
996                 
997                 _crop.left = c;
998         }
999         signal_changed (CROP);
1000 }
1001
1002 void
1003 Film::set_right_crop (int c)
1004 {
1005         {
1006                 boost::mutex::scoped_lock lm (_state_mutex);
1007                 if (_crop.right == c) {
1008                         return;
1009                 }
1010                 
1011                 _crop.right = c;
1012         }
1013         signal_changed (CROP);
1014 }
1015
1016 void
1017 Film::set_top_crop (int c)
1018 {
1019         {
1020                 boost::mutex::scoped_lock lm (_state_mutex);
1021                 if (_crop.top == c) {
1022                         return;
1023                 }
1024                 
1025                 _crop.top = c;
1026         }
1027         signal_changed (CROP);
1028 }
1029
1030 void
1031 Film::set_bottom_crop (int c)
1032 {
1033         {
1034                 boost::mutex::scoped_lock lm (_state_mutex);
1035                 if (_crop.bottom == c) {
1036                         return;
1037                 }
1038                 
1039                 _crop.bottom = c;
1040         }
1041         signal_changed (CROP);
1042 }
1043
1044 void
1045 Film::set_filters (vector<Filter const *> f)
1046 {
1047         {
1048                 boost::mutex::scoped_lock lm (_state_mutex);
1049                 _filters = f;
1050         }
1051         signal_changed (FILTERS);
1052 }
1053
1054 void
1055 Film::set_scaler (Scaler const * s)
1056 {
1057         {
1058                 boost::mutex::scoped_lock lm (_state_mutex);
1059                 _scaler = s;
1060         }
1061         signal_changed (SCALER);
1062 }
1063
1064 void
1065 Film::set_trim_start (int t)
1066 {
1067         {
1068                 boost::mutex::scoped_lock lm (_state_mutex);
1069                 _trim_start = t;
1070         }
1071         signal_changed (TRIM_START);
1072 }
1073
1074 void
1075 Film::set_trim_end (int t)
1076 {
1077         {
1078                 boost::mutex::scoped_lock lm (_state_mutex);
1079                 _trim_end = t;
1080         }
1081         signal_changed (TRIM_END);
1082 }
1083
1084 void
1085 Film::set_dcp_ab (bool a)
1086 {
1087         {
1088                 boost::mutex::scoped_lock lm (_state_mutex);
1089                 _dcp_ab = a;
1090         }
1091         signal_changed (DCP_AB);
1092 }
1093
1094 void
1095 Film::set_content_audio_stream (shared_ptr<AudioStream> s)
1096 {
1097         {
1098                 boost::mutex::scoped_lock lm (_state_mutex);
1099                 _content_audio_stream = s;
1100         }
1101         signal_changed (CONTENT_AUDIO_STREAM);
1102 }
1103
1104 void
1105 Film::set_external_audio (vector<string> a)
1106 {
1107         {
1108                 boost::mutex::scoped_lock lm (_state_mutex);
1109                 _external_audio = a;
1110         }
1111
1112         shared_ptr<SndfileDecoder> decoder (new SndfileDecoder (shared_from_this(), DecodeOptions()));
1113         if (decoder->audio_stream()) {
1114                 _sndfile_stream = decoder->audio_stream ();
1115         }
1116         
1117         signal_changed (EXTERNAL_AUDIO);
1118 }
1119
1120 void
1121 Film::set_use_content_audio (bool e)
1122 {
1123         {
1124                 boost::mutex::scoped_lock lm (_state_mutex);
1125                 _use_content_audio = e;
1126         }
1127
1128         signal_changed (USE_CONTENT_AUDIO);
1129 }
1130
1131 void
1132 Film::set_audio_gain (float g)
1133 {
1134         {
1135                 boost::mutex::scoped_lock lm (_state_mutex);
1136                 _audio_gain = g;
1137         }
1138         signal_changed (AUDIO_GAIN);
1139 }
1140
1141 void
1142 Film::set_audio_delay (int d)
1143 {
1144         {
1145                 boost::mutex::scoped_lock lm (_state_mutex);
1146                 _audio_delay = d;
1147         }
1148         signal_changed (AUDIO_DELAY);
1149 }
1150
1151 void
1152 Film::set_still_duration (int d)
1153 {
1154         {
1155                 boost::mutex::scoped_lock lm (_state_mutex);
1156                 _still_duration = d;
1157         }
1158         signal_changed (STILL_DURATION);
1159 }
1160
1161 void
1162 Film::set_subtitle_stream (shared_ptr<SubtitleStream> s)
1163 {
1164         {
1165                 boost::mutex::scoped_lock lm (_state_mutex);
1166                 _subtitle_stream = s;
1167         }
1168         signal_changed (SUBTITLE_STREAM);
1169 }
1170
1171 void
1172 Film::set_with_subtitles (bool w)
1173 {
1174         {
1175                 boost::mutex::scoped_lock lm (_state_mutex);
1176                 _with_subtitles = w;
1177         }
1178         signal_changed (WITH_SUBTITLES);
1179 }
1180
1181 void
1182 Film::set_subtitle_offset (int o)
1183 {
1184         {
1185                 boost::mutex::scoped_lock lm (_state_mutex);
1186                 _subtitle_offset = o;
1187         }
1188         signal_changed (SUBTITLE_OFFSET);
1189 }
1190
1191 void
1192 Film::set_subtitle_scale (float s)
1193 {
1194         {
1195                 boost::mutex::scoped_lock lm (_state_mutex);
1196                 _subtitle_scale = s;
1197         }
1198         signal_changed (SUBTITLE_SCALE);
1199 }
1200
1201 void
1202 Film::set_colour_lut (int i)
1203 {
1204         {
1205                 boost::mutex::scoped_lock lm (_state_mutex);
1206                 _colour_lut = i;
1207         }
1208         signal_changed (COLOUR_LUT);
1209 }
1210
1211 void
1212 Film::set_j2k_bandwidth (int b)
1213 {
1214         {
1215                 boost::mutex::scoped_lock lm (_state_mutex);
1216                 _j2k_bandwidth = b;
1217         }
1218         signal_changed (J2K_BANDWIDTH);
1219 }
1220
1221 void
1222 Film::set_dci_metadata (DCIMetadata m)
1223 {
1224         {
1225                 boost::mutex::scoped_lock lm (_state_mutex);
1226                 _dci_metadata = m;
1227         }
1228         signal_changed (DCI_METADATA);
1229 }
1230
1231
1232 void
1233 Film::set_dcp_frame_rate (int f)
1234 {
1235         {
1236                 boost::mutex::scoped_lock lm (_state_mutex);
1237                 _dcp_frame_rate = f;
1238         }
1239         signal_changed (DCP_FRAME_RATE);
1240 }
1241
1242 void
1243 Film::set_size (libdcp::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 (SourceFrame 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_content_digest (string d)
1274 {
1275         {
1276                 boost::mutex::scoped_lock lm (_state_mutex);
1277                 _content_digest = d;
1278         }
1279         _dirty = true;
1280 }
1281
1282 void
1283 Film::set_content_audio_streams (vector<shared_ptr<AudioStream> > s)
1284 {
1285         {
1286                 boost::mutex::scoped_lock lm (_state_mutex);
1287                 _content_audio_streams = s;
1288         }
1289         signal_changed (CONTENT_AUDIO_STREAMS);
1290 }
1291
1292 void
1293 Film::set_subtitle_streams (vector<shared_ptr<SubtitleStream> > s)
1294 {
1295         {
1296                 boost::mutex::scoped_lock lm (_state_mutex);
1297                 _subtitle_streams = s;
1298         }
1299         signal_changed (SUBTITLE_STREAMS);
1300 }
1301
1302 void
1303 Film::set_source_frame_rate (float f)
1304 {
1305         {
1306                 boost::mutex::scoped_lock lm (_state_mutex);
1307                 _source_frame_rate = f;
1308         }
1309         signal_changed (SOURCE_FRAME_RATE);
1310 }
1311         
1312 void
1313 Film::signal_changed (Property p)
1314 {
1315         {
1316                 boost::mutex::scoped_lock lm (_state_mutex);
1317                 _dirty = true;
1318         }
1319
1320         if (ui_signaller) {
1321                 ui_signaller->emit (boost::bind (boost::ref (Changed), p));
1322         }
1323 }
1324
1325 int
1326 Film::audio_channels () const
1327 {
1328         shared_ptr<AudioStream> s = audio_stream ();
1329         if (!s) {
1330                 return 0;
1331         }
1332
1333         return s->channels ();
1334 }
1335
1336 void
1337 Film::set_dci_date_today ()
1338 {
1339         _dci_date = boost::gregorian::day_clock::local_day ();
1340 }
1341
1342 boost::shared_ptr<AudioStream>
1343 Film::audio_stream () const
1344 {
1345         if (use_content_audio()) {
1346                 return _content_audio_stream;
1347         }
1348
1349         return _sndfile_stream;
1350 }
1351
1352 string
1353 Film::info_path (int f) const
1354 {
1355         boost::filesystem::path p;
1356         p /= info_dir ();
1357
1358         stringstream s;
1359         s.width (8);
1360         s << setfill('0') << f << ".md5";
1361
1362         p /= s.str();
1363
1364         /* info_dir() will already have added any initial bit of the path,
1365            so don't call file() on this.
1366         */
1367         return p.string ();
1368 }
1369
1370 string
1371 Film::j2c_path (int f, bool t) const
1372 {
1373         boost::filesystem::path p;
1374         p /= "j2c";
1375         p /= video_state_identifier ();
1376
1377         stringstream s;
1378         s.width (8);
1379         s << setfill('0') << f << ".j2c";
1380
1381         if (t) {
1382                 s << ".tmp";
1383         }
1384
1385         p /= s.str();
1386         return file (p.string ());
1387 }
1388
1389 /** Make an educated guess as to whether we have a complete DCP
1390  *  or not.
1391  *  @return true if we do.
1392  */
1393
1394 bool
1395 Film::have_dcp () const
1396 {
1397         try {
1398                 libdcp::DCP dcp (dir (dcp_name()));
1399                 dcp.read ();
1400         } catch (...) {
1401                 return false;
1402         }
1403
1404         return true;
1405 }
1406
1407 bool
1408 Film::has_audio () const
1409 {
1410         if (use_content_audio()) {
1411                 return audio_stream();
1412         }
1413
1414         vector<string> const e = external_audio ();
1415         for (vector<string>::const_iterator i = e.begin(); i != e.end(); ++i) {
1416                 if (!i->empty ()) {
1417                         return true;
1418                 }
1419         }
1420
1421         return false;
1422 }
1423