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