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