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