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