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