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