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