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