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