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