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