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