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