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