Merge branch '1.0' of /home/carl/git/dvdomatic into 1.0
[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 <libcxml/cxml.h>
34 #include "film.h"
35 #include "format.h"
36 #include "job.h"
37 #include "filter.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 "log.h"
44 #include "exceptions.h"
45 #include "examine_content_job.h"
46 #include "scaler.h"
47 #include "config.h"
48 #include "version.h"
49 #include "ui_signaller.h"
50 #include "analyse_audio_job.h"
51 #include "playlist.h"
52 #include "player.h"
53 #include "ffmpeg_content.h"
54 #include "imagemagick_content.h"
55 #include "sndfile_content.h"
56 #include "dcp_content_type.h"
57
58 #include "i18n.h"
59
60 using std::string;
61 using std::stringstream;
62 using std::multimap;
63 using std::pair;
64 using std::map;
65 using std::vector;
66 using std::ifstream;
67 using std::ofstream;
68 using std::setfill;
69 using std::min;
70 using std::make_pair;
71 using std::endl;
72 using std::cout;
73 using std::list;
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 using libdcp::Size;
81
82 int const Film::state_version = 4;
83
84 /** Construct a Film object in a given directory, reading any metadata
85  *  file that exists in that directory.  An exception will be thrown if
86  *  must_exist is true and the specified directory does not exist.
87  *
88  *  @param d Film directory.
89  *  @param must_exist true to throw an exception if does not exist.
90  */
91
92 Film::Film (string d, bool must_exist)
93         : _playlist (new Playlist)
94         , _use_dci_name (true)
95         , _trust_content_headers (true)
96         , _dcp_content_type (0)
97         , _format (Format::from_id ("185"))
98         , _scaler (Scaler::from_id ("bicubic"))
99         , _trim_start (0)
100         , _trim_end (0)
101         , _trim_type (CPL)
102         , _ab (false)
103         , _audio_gain (0)
104         , _audio_delay (0)
105         , _with_subtitles (false)
106         , _subtitle_offset (0)
107         , _subtitle_scale (1)
108         , _colour_lut (0)
109         , _j2k_bandwidth (200000000)
110         , _dci_metadata (Config::instance()->default_dci_metadata ())
111         , _dcp_frame_rate (0)
112         , _dirty (false)
113 {
114         set_dci_date_today ();
115
116         _playlist->Changed.connect (bind (&Film::playlist_changed, this));
117         _playlist->ContentChanged.connect (bind (&Film::playlist_content_changed, this, _1, _2));
118         
119         /* Make state.directory a complete path without ..s (where possible)
120            (Code swiped from Adam Bowen on stackoverflow)
121         */
122         
123         boost::filesystem::path p (boost::filesystem::system_complete (d));
124         boost::filesystem::path result;
125         for (boost::filesystem::path::iterator i = p.begin(); i != p.end(); ++i) {
126                 if (*i == "..") {
127                         if (boost::filesystem::is_symlink (result) || result.filename() == "..") {
128                                 result /= *i;
129                         } else {
130                                 result = result.parent_path ();
131                         }
132                 } else if (*i != ".") {
133                         result /= *i;
134                 }
135         }
136
137         set_directory (result.string ());
138         
139         if (!boost::filesystem::exists (directory())) {
140                 if (must_exist) {
141                         throw OpenFileError (directory());
142                 } else {
143                         boost::filesystem::create_directory (directory());
144                 }
145         }
146
147         if (must_exist) {
148                 read_metadata ();
149         } else {
150                 write_metadata ();
151         }
152
153         _log.reset (new FileLog (file ("log")));
154 }
155
156 Film::Film (Film const & o)
157         : boost::enable_shared_from_this<Film> (o)
158         /* note: the copied film shares the original's log */
159         , _log               (o._log)
160         , _playlist          (new Playlist (o._playlist))
161         , _directory         (o._directory)
162         , _name              (o._name)
163         , _use_dci_name      (o._use_dci_name)
164         , _trust_content_headers (o._trust_content_headers)
165         , _dcp_content_type  (o._dcp_content_type)
166         , _format            (o._format)
167         , _crop              (o._crop)
168         , _filters           (o._filters)
169         , _scaler            (o._scaler)
170         , _trim_start        (o._trim_start)
171         , _trim_end          (o._trim_end)
172         , _trim_type         (o._trim_type)
173         , _ab                (o._ab)
174         , _audio_gain        (o._audio_gain)
175         , _audio_delay       (o._audio_delay)
176         , _with_subtitles    (o._with_subtitles)
177         , _subtitle_offset   (o._subtitle_offset)
178         , _subtitle_scale    (o._subtitle_scale)
179         , _colour_lut        (o._colour_lut)
180         , _j2k_bandwidth     (o._j2k_bandwidth)
181         , _dci_metadata      (o._dci_metadata)
182         , _dcp_frame_rate    (o._dcp_frame_rate)
183         , _dci_date          (o._dci_date)
184         , _dirty             (o._dirty)
185 {
186         _playlist->ContentChanged.connect (bind (&Film::playlist_content_changed, this, _1, _2));
187 }
188
189 string
190 Film::video_state_identifier () const
191 {
192         assert (format ());
193         LocaleGuard lg;
194
195         pair<string, string> f = Filter::ffmpeg_strings (filters());
196
197         stringstream s;
198         s << format()->id()
199           << "_" << _playlist->video_digest()
200           << "_" << crop().left << "_" << crop().right << "_" << crop().top << "_" << crop().bottom
201           << "_" << _dcp_frame_rate
202           << "_" << f.first << "_" << f.second
203           << "_" << scaler()->id()
204           << "_" << j2k_bandwidth()
205           << "_" << boost::lexical_cast<int> (colour_lut());
206
207         if (ab()) {
208                 pair<string, string> fa = Filter::ffmpeg_strings (Config::instance()->reference_filters());
209                 s << "ab_" << Config::instance()->reference_scaler()->id() << "_" << fa.first << "_" << fa.second;
210         }
211
212         return s.str ();
213 }
214           
215 /** @return The path to the directory to write video frame info files to */
216 string
217 Film::info_dir () const
218 {
219         boost::filesystem::path p;
220         p /= "info";
221         p /= video_state_identifier ();
222         return dir (p.string());
223 }
224
225 string
226 Film::internal_video_mxf_dir () const
227 {
228         boost::filesystem::path p;
229         return dir ("video");
230 }
231
232 string
233 Film::internal_video_mxf_filename () const
234 {
235         return video_state_identifier() + ".mxf";
236 }
237
238 string
239 Film::dcp_video_mxf_filename () const
240 {
241         return filename_safe_name() + "_video.mxf";
242 }
243
244 string
245 Film::dcp_audio_mxf_filename () const
246 {
247         return filename_safe_name() + "_audio.mxf";
248 }
249
250 string
251 Film::filename_safe_name () const
252 {
253         string const n = name ();
254         string o;
255         for (size_t i = 0; i < n.length(); ++i) {
256                 if (isalnum (n[i])) {
257                         o += n[i];
258                 } else {
259                         o += "_";
260                 }
261         }
262
263         return o;
264 }
265
266 string
267 Film::audio_analysis_path () const
268 {
269         boost::filesystem::path p;
270         p /= "analysis";
271         p /= _playlist->audio_digest();
272         return file (p.string ());
273 }
274
275 /** Add suitable Jobs to the JobManager to create a DCP for this Film */
276 void
277 Film::make_dcp ()
278 {
279         set_dci_date_today ();
280         
281         if (dcp_name().find ("/") != string::npos) {
282                 throw BadSettingError (_("name"), _("cannot contain slashes"));
283         }
284         
285         log()->log (String::compose ("DCP-o-matic %1 git %2 using %3", dcpomatic_version, dcpomatic_git_commit, dependency_version_summary()));
286
287         {
288                 char buffer[128];
289                 gethostname (buffer, sizeof (buffer));
290                 log()->log (String::compose ("Starting to make DCP on %1", buffer));
291         }
292         
293 //      log()->log (String::compose ("Content is %1; type %2", content_path(), (content_type() == STILL ? _("still") : _("video"))));
294 //      if (length()) {
295 //              log()->log (String::compose ("Content length %1", length().get()));
296 //      }
297 //      log()->log (String::compose ("Content digest %1", content_digest()));
298 //      log()->log (String::compose ("Content at %1 fps, DCP at %2 fps", source_frame_rate(), dcp_frame_rate()));
299         log()->log (String::compose ("%1 threads", Config::instance()->num_local_encoding_threads()));
300         log()->log (String::compose ("J2K bandwidth %1", j2k_bandwidth()));
301 #ifdef DCPOMATIC_DEBUG
302         log()->log ("DCP-o-matic built in debug mode.");
303 #else
304         log()->log ("DCP-o-matic built in optimised mode.");
305 #endif
306 #ifdef LIBDCP_DEBUG
307         log()->log ("libdcp built in debug mode.");
308 #else
309         log()->log ("libdcp built in optimised mode.");
310 #endif
311         pair<string, int> const c = cpu_info ();
312         log()->log (String::compose ("CPU: %1, %2 processors", c.first, c.second));
313         
314         if (format() == 0) {
315                 throw MissingSettingError (_("format"));
316         }
317
318         if (_playlist->content().empty ()) {
319                 throw MissingSettingError (_("content"));
320         }
321
322         if (dcp_content_type() == 0) {
323                 throw MissingSettingError (_("content type"));
324         }
325
326         if (name().empty()) {
327                 throw MissingSettingError (_("name"));
328         }
329
330         shared_ptr<Job> r;
331
332         if (ab()) {
333                 r = JobManager::instance()->add (shared_ptr<Job> (new ABTranscodeJob (shared_from_this())));
334         } else {
335                 r = JobManager::instance()->add (shared_ptr<Job> (new TranscodeJob (shared_from_this())));
336         }
337 }
338
339 /** Start a job to analyse the audio in our Playlist */
340 void
341 Film::analyse_audio ()
342 {
343         if (_analyse_audio_job) {
344                 return;
345         }
346
347         _analyse_audio_job.reset (new AnalyseAudioJob (shared_from_this()));
348         _analyse_audio_job->Finished.connect (bind (&Film::analyse_audio_finished, this));
349         JobManager::instance()->add (_analyse_audio_job);
350 }
351
352 /** Start a job to examine a piece of content */
353 void
354 Film::examine_content (shared_ptr<Content> c)
355 {
356         shared_ptr<Job> j (new ExamineContentJob (shared_from_this(), c, trust_content_headers ()));
357         JobManager::instance()->add (j);
358 }
359
360 void
361 Film::analyse_audio_finished ()
362 {
363         ensure_ui_thread ();
364
365         if (_analyse_audio_job->finished_ok ()) {
366                 AudioAnalysisSucceeded ();
367         }
368         
369         _analyse_audio_job.reset ();
370 }
371
372 /** Start a job to send our DCP to the configured TMS */
373 void
374 Film::send_dcp_to_tms ()
375 {
376         shared_ptr<Job> j (new SCPDCPJob (shared_from_this()));
377         JobManager::instance()->add (j);
378 }
379
380 /** Count the number of frames that have been encoded for this film.
381  *  @return frame count.
382  */
383 int
384 Film::encoded_frames () const
385 {
386         if (format() == 0) {
387                 return 0;
388         }
389
390         int N = 0;
391         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator (info_dir ()); i != boost::filesystem::directory_iterator(); ++i) {
392                 ++N;
393                 boost::this_thread::interruption_point ();
394         }
395
396         return N;
397 }
398
399 /** Write state to our `metadata' file */
400 void
401 Film::write_metadata () const
402 {
403         boost::mutex::scoped_lock lm (_state_mutex);
404         LocaleGuard lg;
405
406         boost::filesystem::create_directories (directory());
407
408         xmlpp::Document doc;
409         xmlpp::Element* root = doc.create_root_node ("Metadata");
410
411         root->add_child("Version")->add_child_text (boost::lexical_cast<string> (state_version));
412         root->add_child("Name")->add_child_text (_name);
413         root->add_child("UseDCIName")->add_child_text (_use_dci_name ? "1" : "0");
414         root->add_child("TrustContentHeaders")->add_child_text (_trust_content_headers ? "1" : "0");
415
416         if (_dcp_content_type) {
417                 root->add_child("DCPContentType")->add_child_text (_dcp_content_type->dci_name ());
418         }
419
420         if (_format) {
421                 root->add_child("Format")->add_child_text (_format->id ());
422         }
423
424         switch (_trim_type) {
425         case CPL:
426                 root->add_child("TrimType")->add_child_text ("CPL");
427                 break;
428         case ENCODE:
429                 root->add_child("TrimType")->add_child_text ("Encode");
430         }
431                         
432         root->add_child("LeftCrop")->add_child_text (boost::lexical_cast<string> (_crop.left));
433         root->add_child("RightCrop")->add_child_text (boost::lexical_cast<string> (_crop.right));
434         root->add_child("TopCrop")->add_child_text (boost::lexical_cast<string> (_crop.top));
435         root->add_child("BottomCrop")->add_child_text (boost::lexical_cast<string> (_crop.bottom));
436
437         for (vector<Filter const *>::const_iterator i = _filters.begin(); i != _filters.end(); ++i) {
438                 root->add_child("Filter")->add_child_text ((*i)->id ());
439         }
440         
441         root->add_child("Scaler")->add_child_text (_scaler->id ());
442         root->add_child("TrimStart")->add_child_text (boost::lexical_cast<string> (_trim_start));
443         root->add_child("TrimEnd")->add_child_text (boost::lexical_cast<string> (_trim_end));
444         root->add_child("AB")->add_child_text (_ab ? "1" : "0");
445         root->add_child("AudioGain")->add_child_text (boost::lexical_cast<string> (_audio_gain));
446         root->add_child("AudioDelay")->add_child_text (boost::lexical_cast<string> (_audio_delay));
447         root->add_child("WithSubtitles")->add_child_text (_with_subtitles ? "1" : "0");
448         root->add_child("SubtitleOffset")->add_child_text (boost::lexical_cast<string> (_subtitle_offset));
449         root->add_child("SubtitleScale")->add_child_text (boost::lexical_cast<string> (_subtitle_scale));
450         root->add_child("ColourLUT")->add_child_text (boost::lexical_cast<string> (_colour_lut));
451         root->add_child("J2KBandwidth")->add_child_text (boost::lexical_cast<string> (_j2k_bandwidth));
452         _dci_metadata.as_xml (root->add_child ("DCIMetadata"));
453         root->add_child("DCPFrameRate")->add_child_text (boost::lexical_cast<string> (_dcp_frame_rate));
454         root->add_child("DCIDate")->add_child_text (boost::gregorian::to_iso_string (_dci_date));
455         _audio_mapping.as_xml (root->add_child("AudioMapping"));
456         _playlist->as_xml (root->add_child ("Playlist"));
457
458         doc.write_to_file_formatted (file ("metadata.xml"));
459         
460         _dirty = false;
461 }
462
463 /** Read state from our metadata file */
464 void
465 Film::read_metadata ()
466 {
467         boost::mutex::scoped_lock lm (_state_mutex);
468         LocaleGuard lg;
469
470         if (boost::filesystem::exists (file ("metadata")) && !boost::filesystem::exists (file ("metadata.xml"))) {
471                 throw StringError (_("This film was created with an older version of DCP-o-matic, and unfortunately it cannot be loaded into this version.  You will need to create a new Film, re-add your content and set it up again.  Sorry!"));
472         }
473
474         cxml::File f (file ("metadata.xml"), "Metadata");
475         
476         _name = f.string_child ("Name");
477         _use_dci_name = f.bool_child ("UseDCIName");
478         _trust_content_headers = f.bool_child ("TrustContentHeaders");
479
480         {
481                 optional<string> c = f.optional_string_child ("DCPContentType");
482                 if (c) {
483                         _dcp_content_type = DCPContentType::from_dci_name (c.get ());
484                 }
485         }
486
487         {
488                 optional<string> c = f.optional_string_child ("Format");
489                 if (c) {
490                         _format = Format::from_id (c.get ());
491                 }
492         }
493
494         {
495                 optional<string> c = f.optional_string_child ("TrimType");
496                 if (!c || c.get() == "CPL") {
497                         _trim_type = CPL;
498                 } else if (c && c.get() == "Encode") {
499                         _trim_type = ENCODE;
500                 }
501         }
502
503         _crop.left = f.number_child<int> ("LeftCrop");
504         _crop.right = f.number_child<int> ("RightCrop");
505         _crop.top = f.number_child<int> ("TopCrop");
506         _crop.bottom = f.number_child<int> ("BottomCrop");
507
508         {
509                 list<shared_ptr<cxml::Node> > c = f.node_children ("Filter");
510                 for (list<shared_ptr<cxml::Node> >::iterator i = c.begin(); i != c.end(); ++i) {
511                         _filters.push_back (Filter::from_id ((*i)->content ()));
512                 }
513         }
514
515         _scaler = Scaler::from_id (f.string_child ("Scaler"));
516         _trim_start = f.number_child<int> ("TrimStart");
517         _trim_end = f.number_child<int> ("TrimEnd");
518         _ab = f.bool_child ("AB");
519         _audio_gain = f.number_child<float> ("AudioGain");
520         _audio_delay = f.number_child<int> ("AudioDelay");
521         _with_subtitles = f.bool_child ("WithSubtitles");
522         _subtitle_offset = f.number_child<float> ("SubtitleOffset");
523         _subtitle_scale = f.number_child<float> ("SubtitleScale");
524         _colour_lut = f.number_child<int> ("ColourLUT");
525         _j2k_bandwidth = f.number_child<int> ("J2KBandwidth");
526         _dci_metadata = DCIMetadata (f.node_child ("DCIMetadata"));
527         _dcp_frame_rate = f.number_child<int> ("DCPFrameRate");
528         _dci_date = boost::gregorian::from_undelimited_string (f.string_child ("DCIDate"));
529
530         _playlist->set_from_xml (f.node_child ("Playlist"));
531         _audio_mapping.set_from_xml (_playlist->content(), f.node_child ("AudioMapping"));
532
533         _dirty = false;
534 }
535
536 libdcp::Size
537 Film::cropped_size (libdcp::Size s) const
538 {
539         boost::mutex::scoped_lock lm (_state_mutex);
540         s.width -= _crop.left + _crop.right;
541         s.height -= _crop.top + _crop.bottom;
542         return s;
543 }
544
545 /** Given a directory name, return its full path within the Film's directory.
546  *  The directory (and its parents) will be created if they do not exist.
547  */
548 string
549 Film::dir (string d) const
550 {
551         boost::mutex::scoped_lock lm (_directory_mutex);
552         
553         boost::filesystem::path p;
554         p /= _directory;
555         p /= d;
556         
557         boost::filesystem::create_directories (p);
558         
559         return p.string ();
560 }
561
562 /** Given a file or directory name, return its full path within the Film's directory.
563  *  _directory_mutex must not be locked on entry.
564  *  Any required parent directories will be created.
565  */
566 string
567 Film::file (string f) const
568 {
569         boost::mutex::scoped_lock lm (_directory_mutex);
570
571         boost::filesystem::path p;
572         p /= _directory;
573         p /= f;
574
575         boost::filesystem::create_directories (p.parent_path ());
576         
577         return p.string ();
578 }
579
580 /** @return The sampling rate that we will resample the audio to */
581 int
582 Film::target_audio_sample_rate () const
583 {
584         if (!has_audio ()) {
585                 return 0;
586         }
587         
588         /* Resample to a DCI-approved sample rate */
589         double t = dcp_audio_sample_rate (audio_frame_rate());
590
591         FrameRateConversion frc (video_frame_rate(), dcp_frame_rate());
592
593         /* Compensate if the DCP is being run at a different frame rate
594            to the source; that is, if the video is run such that it will
595            look different in the DCP compared to the source (slower or faster).
596            skip/repeat doesn't come into effect here.
597         */
598
599         if (frc.change_speed) {
600                 t *= video_frame_rate() * frc.factor() / dcp_frame_rate();
601         }
602
603         return rint (t);
604 }
605
606 /** @return a DCI-compliant name for a DCP of this film */
607 string
608 Film::dci_name (bool if_created_now) const
609 {
610         stringstream d;
611
612         string fixed_name = to_upper_copy (name());
613         for (size_t i = 0; i < fixed_name.length(); ++i) {
614                 if (fixed_name[i] == ' ') {
615                         fixed_name[i] = '-';
616                 }
617         }
618
619         /* Spec is that the name part should be maximum 14 characters, as I understand it */
620         if (fixed_name.length() > 14) {
621                 fixed_name = fixed_name.substr (0, 14);
622         }
623
624         d << fixed_name;
625
626         if (dcp_content_type()) {
627                 d << "_" << dcp_content_type()->dci_name();
628         }
629
630         if (format()) {
631                 d << "_" << format()->dci_name();
632         }
633
634         DCIMetadata const dm = dci_metadata ();
635
636         if (!dm.audio_language.empty ()) {
637                 d << "_" << dm.audio_language;
638                 if (!dm.subtitle_language.empty()) {
639                         d << "-" << dm.subtitle_language;
640                 } else {
641                         d << "-XX";
642                 }
643         }
644
645         if (!dm.territory.empty ()) {
646                 d << "_" << dm.territory;
647                 if (!dm.rating.empty ()) {
648                         d << "-" << dm.rating;
649                 }
650         }
651
652         switch (audio_channels ()) {
653         case 1:
654                 d << "_10";
655                 break;
656         case 2:
657                 d << "_20";
658                 break;
659         case 6:
660                 d << "_51";
661                 break;
662         case 8:
663                 d << "_71";
664                 break;
665         }
666
667         d << "_2K";
668
669         if (!dm.studio.empty ()) {
670                 d << "_" << dm.studio;
671         }
672
673         if (if_created_now) {
674                 d << "_" << boost::gregorian::to_iso_string (boost::gregorian::day_clock::local_day ());
675         } else {
676                 d << "_" << boost::gregorian::to_iso_string (_dci_date);
677         }
678
679         if (!dm.facility.empty ()) {
680                 d << "_" << dm.facility;
681         }
682
683         if (!dm.package_type.empty ()) {
684                 d << "_" << dm.package_type;
685         }
686
687         return d.str ();
688 }
689
690 /** @return name to give the DCP */
691 string
692 Film::dcp_name (bool if_created_now) const
693 {
694         if (use_dci_name()) {
695                 return dci_name (if_created_now);
696         }
697
698         return name();
699 }
700
701
702 void
703 Film::set_directory (string d)
704 {
705         boost::mutex::scoped_lock lm (_state_mutex);
706         _directory = d;
707         _dirty = true;
708 }
709
710 void
711 Film::set_name (string n)
712 {
713         {
714                 boost::mutex::scoped_lock lm (_state_mutex);
715                 _name = n;
716         }
717         signal_changed (NAME);
718 }
719
720 void
721 Film::set_use_dci_name (bool u)
722 {
723         {
724                 boost::mutex::scoped_lock lm (_state_mutex);
725                 _use_dci_name = u;
726         }
727         signal_changed (USE_DCI_NAME);
728 }
729
730 void
731 Film::set_trust_content_headers (bool t)
732 {
733         {
734                 boost::mutex::scoped_lock lm (_state_mutex);
735                 _trust_content_headers = t;
736         }
737         
738         signal_changed (TRUST_CONTENT_HEADERS);
739
740         
741         ContentList content = _playlist->content ();
742         if (!_trust_content_headers && !content.empty()) {
743                 /* We just said that we don't trust the content's header */
744                 for (ContentList::iterator i = content.begin(); i != content.end(); ++i) {
745                         examine_content (*i);
746                 }
747         }
748 }
749                
750 void
751 Film::set_dcp_content_type (DCPContentType const * t)
752 {
753         {
754                 boost::mutex::scoped_lock lm (_state_mutex);
755                 _dcp_content_type = t;
756         }
757         signal_changed (DCP_CONTENT_TYPE);
758 }
759
760 void
761 Film::set_format (Format const * f)
762 {
763         {
764                 boost::mutex::scoped_lock lm (_state_mutex);
765                 _format = f;
766         }
767         signal_changed (FORMAT);
768 }
769
770 void
771 Film::set_crop (Crop c)
772 {
773         {
774                 boost::mutex::scoped_lock lm (_state_mutex);
775                 _crop = c;
776         }
777         signal_changed (CROP);
778 }
779
780 void
781 Film::set_left_crop (int c)
782 {
783         {
784                 boost::mutex::scoped_lock lm (_state_mutex);
785                 
786                 if (_crop.left == c) {
787                         return;
788                 }
789                 
790                 _crop.left = c;
791         }
792         signal_changed (CROP);
793 }
794
795 void
796 Film::set_right_crop (int c)
797 {
798         {
799                 boost::mutex::scoped_lock lm (_state_mutex);
800                 if (_crop.right == c) {
801                         return;
802                 }
803                 
804                 _crop.right = c;
805         }
806         signal_changed (CROP);
807 }
808
809 void
810 Film::set_top_crop (int c)
811 {
812         {
813                 boost::mutex::scoped_lock lm (_state_mutex);
814                 if (_crop.top == c) {
815                         return;
816                 }
817                 
818                 _crop.top = c;
819         }
820         signal_changed (CROP);
821 }
822
823 void
824 Film::set_bottom_crop (int c)
825 {
826         {
827                 boost::mutex::scoped_lock lm (_state_mutex);
828                 if (_crop.bottom == c) {
829                         return;
830                 }
831                 
832                 _crop.bottom = c;
833         }
834         signal_changed (CROP);
835 }
836
837 void
838 Film::set_filters (vector<Filter const *> f)
839 {
840         {
841                 boost::mutex::scoped_lock lm (_state_mutex);
842                 _filters = f;
843         }
844         signal_changed (FILTERS);
845 }
846
847 void
848 Film::set_scaler (Scaler const * s)
849 {
850         {
851                 boost::mutex::scoped_lock lm (_state_mutex);
852                 _scaler = s;
853         }
854         signal_changed (SCALER);
855 }
856
857 void
858 Film::set_trim_start (int t)
859 {
860         {
861                 boost::mutex::scoped_lock lm (_state_mutex);
862                 _trim_start = t;
863         }
864         signal_changed (TRIM_START);
865 }
866
867 void
868 Film::set_trim_end (int t)
869 {
870         {
871                 boost::mutex::scoped_lock lm (_state_mutex);
872                 _trim_end = t;
873         }
874         signal_changed (TRIM_END);
875 }
876
877 void
878 Film::set_trim_type (TrimType t)
879 {
880         {
881                 boost::mutex::scoped_lock lm (_state_mutex);
882                 _trim_type = t;
883         }
884         signal_changed (TRIM_TYPE);
885 }
886
887 void
888 Film::set_ab (bool a)
889 {
890         {
891                 boost::mutex::scoped_lock lm (_state_mutex);
892                 _ab = a;
893         }
894         signal_changed (AB);
895 }
896
897 void
898 Film::set_audio_gain (float g)
899 {
900         {
901                 boost::mutex::scoped_lock lm (_state_mutex);
902                 _audio_gain = g;
903         }
904         signal_changed (AUDIO_GAIN);
905 }
906
907 void
908 Film::set_audio_delay (int d)
909 {
910         {
911                 boost::mutex::scoped_lock lm (_state_mutex);
912                 _audio_delay = d;
913         }
914         signal_changed (AUDIO_DELAY);
915 }
916
917 void
918 Film::set_with_subtitles (bool w)
919 {
920         {
921                 boost::mutex::scoped_lock lm (_state_mutex);
922                 _with_subtitles = w;
923         }
924         signal_changed (WITH_SUBTITLES);
925 }
926
927 void
928 Film::set_subtitle_offset (int o)
929 {
930         {
931                 boost::mutex::scoped_lock lm (_state_mutex);
932                 _subtitle_offset = o;
933         }
934         signal_changed (SUBTITLE_OFFSET);
935 }
936
937 void
938 Film::set_subtitle_scale (float s)
939 {
940         {
941                 boost::mutex::scoped_lock lm (_state_mutex);
942                 _subtitle_scale = s;
943         }
944         signal_changed (SUBTITLE_SCALE);
945 }
946
947 void
948 Film::set_colour_lut (int i)
949 {
950         {
951                 boost::mutex::scoped_lock lm (_state_mutex);
952                 _colour_lut = i;
953         }
954         signal_changed (COLOUR_LUT);
955 }
956
957 void
958 Film::set_j2k_bandwidth (int b)
959 {
960         {
961                 boost::mutex::scoped_lock lm (_state_mutex);
962                 _j2k_bandwidth = b;
963         }
964         signal_changed (J2K_BANDWIDTH);
965 }
966
967 void
968 Film::set_dci_metadata (DCIMetadata m)
969 {
970         {
971                 boost::mutex::scoped_lock lm (_state_mutex);
972                 _dci_metadata = m;
973         }
974         signal_changed (DCI_METADATA);
975 }
976
977
978 void
979 Film::set_dcp_frame_rate (int f)
980 {
981         {
982                 boost::mutex::scoped_lock lm (_state_mutex);
983                 _dcp_frame_rate = f;
984         }
985         signal_changed (DCP_FRAME_RATE);
986 }
987
988 void
989 Film::signal_changed (Property p)
990 {
991         {
992                 boost::mutex::scoped_lock lm (_state_mutex);
993                 _dirty = true;
994         }
995
996         switch (p) {
997         case Film::CONTENT:
998                 set_dcp_frame_rate (best_dcp_frame_rate (video_frame_rate ()));
999                 set_audio_mapping (_playlist->default_audio_mapping ());
1000                 break;
1001         default:
1002                 break;
1003         }
1004
1005         if (ui_signaller) {
1006                 ui_signaller->emit (boost::bind (boost::ref (Changed), p));
1007         }
1008 }
1009
1010 void
1011 Film::set_dci_date_today ()
1012 {
1013         _dci_date = boost::gregorian::day_clock::local_day ();
1014 }
1015
1016 string
1017 Film::info_path (int f) const
1018 {
1019         boost::filesystem::path p;
1020         p /= info_dir ();
1021
1022         stringstream s;
1023         s.width (8);
1024         s << setfill('0') << f << ".md5";
1025
1026         p /= s.str();
1027
1028         /* info_dir() will already have added any initial bit of the path,
1029            so don't call file() on this.
1030         */
1031         return p.string ();
1032 }
1033
1034 string
1035 Film::j2c_path (int f, bool t) const
1036 {
1037         boost::filesystem::path p;
1038         p /= "j2c";
1039         p /= video_state_identifier ();
1040
1041         stringstream s;
1042         s.width (8);
1043         s << setfill('0') << f << ".j2c";
1044
1045         if (t) {
1046                 s << ".tmp";
1047         }
1048
1049         p /= s.str();
1050         return file (p.string ());
1051 }
1052
1053 /** Make an educated guess as to whether we have a complete DCP
1054  *  or not.
1055  *  @return true if we do.
1056  */
1057
1058 bool
1059 Film::have_dcp () const
1060 {
1061         try {
1062                 libdcp::DCP dcp (dir (dcp_name()));
1063                 dcp.read ();
1064         } catch (...) {
1065                 return false;
1066         }
1067
1068         return true;
1069 }
1070
1071 shared_ptr<Player>
1072 Film::player () const
1073 {
1074         boost::mutex::scoped_lock lm (_state_mutex);
1075         return shared_ptr<Player> (new Player (shared_from_this (), _playlist));
1076 }
1077
1078 ContentList
1079 Film::content () const
1080 {
1081         return _playlist->content ();
1082 }
1083
1084 void
1085 Film::add_content (shared_ptr<Content> c)
1086 {
1087         _playlist->add (c);
1088         examine_content (c);
1089 }
1090
1091 void
1092 Film::remove_content (shared_ptr<Content> c)
1093 {
1094         _playlist->remove (c);
1095 }
1096
1097 void
1098 Film::move_content_earlier (shared_ptr<Content> c)
1099 {
1100         _playlist->move_earlier (c);
1101 }
1102
1103 void
1104 Film::move_content_later (shared_ptr<Content> c)
1105 {
1106         _playlist->move_later (c);
1107 }
1108
1109 ContentAudioFrame
1110 Film::audio_length () const
1111 {
1112         return _playlist->audio_length ();
1113 }
1114
1115 int
1116 Film::audio_channels () const
1117 {
1118         return _playlist->audio_channels ();
1119 }
1120
1121 int
1122 Film::audio_frame_rate () const
1123 {
1124         return _playlist->audio_frame_rate ();
1125 }
1126
1127 bool
1128 Film::has_audio () const
1129 {
1130         return _playlist->has_audio ();
1131 }
1132
1133 float
1134 Film::video_frame_rate () const
1135 {
1136         return _playlist->video_frame_rate ();
1137 }
1138
1139 libdcp::Size
1140 Film::video_size () const
1141 {
1142         return _playlist->video_size ();
1143 }
1144
1145 ContentVideoFrame
1146 Film::video_length () const
1147 {
1148         return _playlist->video_length ();
1149 }
1150
1151 ContentVideoFrame
1152 Film::content_length () const
1153 {
1154         return _playlist->content_length ();
1155 }
1156
1157 vector<FFmpegSubtitleStream>
1158 Film::ffmpeg_subtitle_streams () const
1159 {
1160         shared_ptr<FFmpegContent> f = _playlist->ffmpeg ();
1161         if (f) {
1162                 return f->subtitle_streams ();
1163         }
1164
1165         return vector<FFmpegSubtitleStream> ();
1166 }
1167
1168 boost::optional<FFmpegSubtitleStream>
1169 Film::ffmpeg_subtitle_stream () const
1170 {
1171         shared_ptr<FFmpegContent> f = _playlist->ffmpeg ();
1172         if (f) {
1173                 return f->subtitle_stream ();
1174         }
1175
1176         return boost::none;
1177 }
1178
1179 vector<FFmpegAudioStream>
1180 Film::ffmpeg_audio_streams () const
1181 {
1182         shared_ptr<FFmpegContent> f = _playlist->ffmpeg ();
1183         if (f) {
1184                 return f->audio_streams ();
1185         }
1186
1187         return vector<FFmpegAudioStream> ();
1188 }
1189
1190 boost::optional<FFmpegAudioStream>
1191 Film::ffmpeg_audio_stream () const
1192 {
1193         shared_ptr<FFmpegContent> f = _playlist->ffmpeg ();
1194         if (f) {
1195                 return f->audio_stream ();
1196         }
1197
1198         return boost::none;
1199 }
1200
1201 void
1202 Film::set_ffmpeg_subtitle_stream (FFmpegSubtitleStream s)
1203 {
1204         shared_ptr<FFmpegContent> f = _playlist->ffmpeg ();
1205         if (f) {
1206                 f->set_subtitle_stream (s);
1207         }
1208 }
1209
1210 void
1211 Film::set_ffmpeg_audio_stream (FFmpegAudioStream s)
1212 {
1213         shared_ptr<FFmpegContent> f = _playlist->ffmpeg ();
1214         if (f) {
1215                 f->set_audio_stream (s);
1216         }
1217 }
1218
1219 void
1220 Film::set_audio_mapping (AudioMapping m)
1221 {
1222         {
1223                 boost::mutex::scoped_lock lm (_state_mutex);
1224                 _audio_mapping = m;
1225         }
1226
1227         signal_changed (AUDIO_MAPPING);
1228 }
1229
1230 void
1231 Film::playlist_content_changed (boost::weak_ptr<Content> c, int p)
1232 {
1233         if (p == VideoContentProperty::VIDEO_FRAME_RATE) {
1234                 set_dcp_frame_rate (best_dcp_frame_rate (video_frame_rate ()));
1235         } else if (p == AudioContentProperty::AUDIO_CHANNELS) {
1236                 set_audio_mapping (_playlist->default_audio_mapping ());
1237         } 
1238
1239         if (ui_signaller) {
1240                 ui_signaller->emit (boost::bind (boost::ref (ContentChanged), c, p));
1241         }
1242 }
1243
1244 void
1245 Film::playlist_changed ()
1246 {
1247         signal_changed (CONTENT);
1248 }       
1249
1250 int
1251 Film::loop () const
1252 {
1253         return _playlist->loop ();
1254 }
1255
1256 void
1257 Film::set_loop (int c)
1258 {
1259         _playlist->set_loop (c);
1260 }