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