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