Merge master.
[dcpomatic.git] / src / lib / film.cc
1 /* -*- c-basic-offset: 8; default-tab-width: 8; -*- */
2
3 /*
4     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20 */
21
22 #include <stdexcept>
23 #include <iostream>
24 #include <algorithm>
25 #include <fstream>
26 #include <cstdlib>
27 #include <sstream>
28 #include <iomanip>
29 #include <unistd.h>
30 #include <boost/filesystem.hpp>
31 #include <boost/algorithm/string.hpp>
32 #include <boost/lexical_cast.hpp>
33 #include <boost/date_time.hpp>
34 #include <libxml++/libxml++.h>
35 #include <libcxml/cxml.h>
36 #include "film.h"
37 #include "format.h"
38 #include "job.h"
39 #include "filter.h"
40 #include "util.h"
41 #include "job_manager.h"
42 #include "ab_transcode_job.h"
43 #include "transcode_job.h"
44 #include "scp_dcp_job.h"
45 #include "log.h"
46 #include "exceptions.h"
47 #include "examine_content_job.h"
48 #include "scaler.h"
49 #include "config.h"
50 #include "version.h"
51 #include "ui_signaller.h"
52 #include "analyse_audio_job.h"
53 #include "playlist.h"
54 #include "player.h"
55 #include "ffmpeg_content.h"
56 #include "imagemagick_content.h"
57 #include "sndfile_content.h"
58 #include "dcp_content_type.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::cout;
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 (Config::instance()->default_dcp_content_type ())
99         , _format (Config::instance()->default_format ())
100         , _scaler (Scaler::from_id ("bicubic"))
101         , _trim_start (0)
102         , _trim_end (0)
103         , _trim_type (CPL)
104         , _ab (false)
105         , _audio_gain (0)
106         , _audio_delay (0)
107         , _with_subtitles (false)
108         , _subtitle_offset (0)
109         , _subtitle_scale (1)
110         , _colour_lut (0)
111         , _j2k_bandwidth (200000000)
112         , _dci_metadata (Config::instance()->default_dci_metadata ())
113         , _dcp_video_frame_rate (0)
114         , _dirty (false)
115 {
116         set_dci_date_today ();
117
118         _playlist->Changed.connect (bind (&Film::playlist_changed, this));
119         _playlist->ContentChanged.connect (bind (&Film::playlist_content_changed, this, _1, _2));
120         
121         /* Make state.directory a complete path without ..s (where possible)
122            (Code swiped from Adam Bowen on stackoverflow)
123         */
124         
125         boost::filesystem::path p (boost::filesystem::system_complete (d));
126         boost::filesystem::path result;
127         for (boost::filesystem::path::iterator i = p.begin(); i != p.end(); ++i) {
128                 if (*i == "..") {
129                         if (boost::filesystem::is_symlink (result) || result.filename() == "..") {
130                                 result /= *i;
131                         } else {
132                                 result = result.parent_path ();
133                         }
134                 } else if (*i != ".") {
135                         result /= *i;
136                 }
137         }
138
139         set_directory (result.string ());
140         
141         if (!boost::filesystem::exists (directory())) {
142                 if (must_exist) {
143                         throw OpenFileError (directory());
144                 } else {
145                         boost::filesystem::create_directory (directory());
146                 }
147         }
148
149         if (must_exist) {
150                 read_metadata ();
151         } else {
152                 write_metadata ();
153         }
154
155         _log.reset (new FileLog (file ("log")));
156 }
157
158 Film::Film (Film const & o)
159         : boost::enable_shared_from_this<Film> (o)
160         /* note: the copied film shares the original's log */
161         , _log               (o._log)
162         , _playlist          (new Playlist (o._playlist))
163         , _directory         (o._directory)
164         , _name              (o._name)
165         , _use_dci_name      (o._use_dci_name)
166         , _trust_content_headers (o._trust_content_headers)
167         , _dcp_content_type  (o._dcp_content_type)
168         , _format            (o._format)
169         , _crop              (o._crop)
170         , _filters           (o._filters)
171         , _scaler            (o._scaler)
172         , _trim_start        (o._trim_start)
173         , _trim_end          (o._trim_end)
174         , _trim_type         (o._trim_type)
175         , _ab                (o._ab)
176         , _audio_gain        (o._audio_gain)
177         , _audio_delay       (o._audio_delay)
178         , _with_subtitles    (o._with_subtitles)
179         , _subtitle_offset   (o._subtitle_offset)
180         , _subtitle_scale    (o._subtitle_scale)
181         , _colour_lut        (o._colour_lut)
182         , _j2k_bandwidth     (o._j2k_bandwidth)
183         , _dci_metadata      (o._dci_metadata)
184         , _dcp_video_frame_rate (o._dcp_video_frame_rate)
185         , _dci_date          (o._dci_date)
186         , _dirty             (o._dirty)
187 {
188         _playlist->ContentChanged.connect (bind (&Film::playlist_content_changed, this, _1, _2));
189 }
190
191 string
192 Film::video_state_identifier () const
193 {
194         assert (format ());
195         LocaleGuard lg;
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_video_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 (_playlist->content().empty ()) {
321                 throw StringError (_("You must add some content to the DCP before creating it"));
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         boost::mutex::scoped_lock lm (_state_mutex);
406         LocaleGuard lg;
407
408         boost::filesystem::create_directories (directory());
409
410         xmlpp::Document doc;
411         xmlpp::Element* root = doc.create_root_node ("Metadata");
412
413         root->add_child("Version")->add_child_text (boost::lexical_cast<string> (state_version));
414         root->add_child("Name")->add_child_text (_name);
415         root->add_child("UseDCIName")->add_child_text (_use_dci_name ? "1" : "0");
416         root->add_child("TrustContentHeaders")->add_child_text (_trust_content_headers ? "1" : "0");
417
418         if (_dcp_content_type) {
419                 root->add_child("DCPContentType")->add_child_text (_dcp_content_type->dci_name ());
420         }
421
422         if (_format) {
423                 root->add_child("Format")->add_child_text (_format->id ());
424         }
425
426         switch (_trim_type) {
427         case CPL:
428                 root->add_child("TrimType")->add_child_text ("CPL");
429                 break;
430         case ENCODE:
431                 root->add_child("TrimType")->add_child_text ("Encode");
432         }
433                         
434         root->add_child("LeftCrop")->add_child_text (boost::lexical_cast<string> (_crop.left));
435         root->add_child("RightCrop")->add_child_text (boost::lexical_cast<string> (_crop.right));
436         root->add_child("TopCrop")->add_child_text (boost::lexical_cast<string> (_crop.top));
437         root->add_child("BottomCrop")->add_child_text (boost::lexical_cast<string> (_crop.bottom));
438
439         for (vector<Filter const *>::const_iterator i = _filters.begin(); i != _filters.end(); ++i) {
440                 root->add_child("Filter")->add_child_text ((*i)->id ());
441         }
442         
443         root->add_child("Scaler")->add_child_text (_scaler->id ());
444         root->add_child("TrimStart")->add_child_text (boost::lexical_cast<string> (_trim_start));
445         root->add_child("TrimEnd")->add_child_text (boost::lexical_cast<string> (_trim_end));
446         root->add_child("AB")->add_child_text (_ab ? "1" : "0");
447         root->add_child("AudioGain")->add_child_text (boost::lexical_cast<string> (_audio_gain));
448         root->add_child("AudioDelay")->add_child_text (boost::lexical_cast<string> (_audio_delay));
449         root->add_child("WithSubtitles")->add_child_text (_with_subtitles ? "1" : "0");
450         root->add_child("SubtitleOffset")->add_child_text (boost::lexical_cast<string> (_subtitle_offset));
451         root->add_child("SubtitleScale")->add_child_text (boost::lexical_cast<string> (_subtitle_scale));
452         root->add_child("ColourLUT")->add_child_text (boost::lexical_cast<string> (_colour_lut));
453         root->add_child("J2KBandwidth")->add_child_text (boost::lexical_cast<string> (_j2k_bandwidth));
454         _dci_metadata.as_xml (root->add_child ("DCIMetadata"));
455         root->add_child("DCPVideoFrameRate")->add_child_text (boost::lexical_cast<string> (_dcp_video_frame_rate));
456         root->add_child("DCIDate")->add_child_text (boost::gregorian::to_iso_string (_dci_date));
457         _playlist->as_xml (root->add_child ("Playlist"));
458
459         doc.write_to_file_formatted (file ("metadata.xml"));
460         
461         _dirty = false;
462 }
463
464 /** Read state from our metadata file */
465 void
466 Film::read_metadata ()
467 {
468         boost::mutex::scoped_lock lm (_state_mutex);
469         LocaleGuard lg;
470
471         if (boost::filesystem::exists (file ("metadata")) && !boost::filesystem::exists (file ("metadata.xml"))) {
472                 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!"));
473         }
474
475         cxml::File f (file ("metadata.xml"), "Metadata");
476         
477         _name = f.string_child ("Name");
478         _use_dci_name = f.bool_child ("UseDCIName");
479         _trust_content_headers = f.bool_child ("TrustContentHeaders");
480
481         {
482                 optional<string> c = f.optional_string_child ("DCPContentType");
483                 if (c) {
484                         _dcp_content_type = DCPContentType::from_dci_name (c.get ());
485                 }
486         }
487
488         {
489                 optional<string> c = f.optional_string_child ("Format");
490                 if (c) {
491                         _format = Format::from_id (c.get ());
492                 }
493         }
494
495         {
496                 optional<string> c = f.optional_string_child ("TrimType");
497                 if (!c || c.get() == "CPL") {
498                         _trim_type = CPL;
499                 } else if (c && c.get() == "Encode") {
500                         _trim_type = ENCODE;
501                 }
502         }
503
504         _crop.left = f.number_child<int> ("LeftCrop");
505         _crop.right = f.number_child<int> ("RightCrop");
506         _crop.top = f.number_child<int> ("TopCrop");
507         _crop.bottom = f.number_child<int> ("BottomCrop");
508
509         {
510                 list<shared_ptr<cxml::Node> > c = f.node_children ("Filter");
511                 for (list<shared_ptr<cxml::Node> >::iterator i = c.begin(); i != c.end(); ++i) {
512                         _filters.push_back (Filter::from_id ((*i)->content ()));
513                 }
514         }
515
516         _scaler = Scaler::from_id (f.string_child ("Scaler"));
517         _trim_start = f.number_child<int> ("TrimStart");
518         _trim_end = f.number_child<int> ("TrimEnd");
519         _ab = f.bool_child ("AB");
520         _audio_gain = f.number_child<float> ("AudioGain");
521         _audio_delay = f.number_child<int> ("AudioDelay");
522         _with_subtitles = f.bool_child ("WithSubtitles");
523         _subtitle_offset = f.number_child<float> ("SubtitleOffset");
524         _subtitle_scale = f.number_child<float> ("SubtitleScale");
525         _colour_lut = f.number_child<int> ("ColourLUT");
526         _j2k_bandwidth = f.number_child<int> ("J2KBandwidth");
527         _dci_metadata = DCIMetadata (f.node_child ("DCIMetadata"));
528         _dcp_video_frame_rate = f.number_child<int> ("DCPVideoFrameRate");
529         _dci_date = boost::gregorian::from_undelimited_string (f.string_child ("DCIDate"));
530
531         _playlist->set_from_xml (f.node_child ("Playlist"));
532
533         _dirty = false;
534 }
535
536 libdcp::Size
537 Film::cropped_size (libdcp::Size s) const
538 {
539         boost::mutex::scoped_lock lm (_state_mutex);
540         s.width -= _crop.left + _crop.right;
541         s.height -= _crop.top + _crop.bottom;
542         return s;
543 }
544
545 /** Given a directory name, return its full path within the Film's directory.
546  *  The directory (and its parents) will be created if they do not exist.
547  */
548 string
549 Film::dir (string d) const
550 {
551         boost::mutex::scoped_lock lm (_directory_mutex);
552         
553         boost::filesystem::path p;
554         p /= _directory;
555         p /= d;
556         
557         boost::filesystem::create_directories (p);
558         
559         return p.string ();
560 }
561
562 /** Given a file or directory name, return its full path within the Film's directory.
563  *  _directory_mutex must not be locked on entry.
564  *  Any required parent directories will be created.
565  */
566 string
567 Film::file (string f) const
568 {
569         boost::mutex::scoped_lock lm (_directory_mutex);
570
571         boost::filesystem::path p;
572         p /= _directory;
573         p /= f;
574
575         boost::filesystem::create_directories (p.parent_path ());
576         
577         return p.string ();
578 }
579
580 /** @return a DCI-compliant name for a DCP of this film */
581 string
582 Film::dci_name (bool if_created_now) const
583 {
584         stringstream d;
585
586         string fixed_name = to_upper_copy (name());
587         for (size_t i = 0; i < fixed_name.length(); ++i) {
588                 if (fixed_name[i] == ' ') {
589                         fixed_name[i] = '-';
590                 }
591         }
592
593         /* Spec is that the name part should be maximum 14 characters, as I understand it */
594         if (fixed_name.length() > 14) {
595                 fixed_name = fixed_name.substr (0, 14);
596         }
597
598         d << fixed_name;
599
600         if (dcp_content_type()) {
601                 d << "_" << dcp_content_type()->dci_name();
602         }
603
604         if (format()) {
605                 d << "_" << format()->dci_name();
606         }
607
608         DCIMetadata const dm = dci_metadata ();
609
610         if (!dm.audio_language.empty ()) {
611                 d << "_" << dm.audio_language;
612                 if (!dm.subtitle_language.empty()) {
613                         d << "-" << dm.subtitle_language;
614                 } else {
615                         d << "-XX";
616                 }
617         }
618
619         if (!dm.territory.empty ()) {
620                 d << "_" << dm.territory;
621                 if (!dm.rating.empty ()) {
622                         d << "-" << dm.rating;
623                 }
624         }
625
626         d << "_51_2K";
627
628         if (!dm.studio.empty ()) {
629                 d << "_" << dm.studio;
630         }
631
632         if (if_created_now) {
633                 d << "_" << boost::gregorian::to_iso_string (boost::gregorian::day_clock::local_day ());
634         } else {
635                 d << "_" << boost::gregorian::to_iso_string (_dci_date);
636         }
637
638         if (!dm.facility.empty ()) {
639                 d << "_" << dm.facility;
640         }
641
642         if (!dm.package_type.empty ()) {
643                 d << "_" << dm.package_type;
644         }
645
646         return d.str ();
647 }
648
649 /** @return name to give the DCP */
650 string
651 Film::dcp_name (bool if_created_now) const
652 {
653         if (use_dci_name()) {
654                 return dci_name (if_created_now);
655         }
656
657         return name();
658 }
659
660
661 void
662 Film::set_directory (string d)
663 {
664         boost::mutex::scoped_lock lm (_state_mutex);
665         _directory = d;
666         _dirty = true;
667 }
668
669 void
670 Film::set_name (string n)
671 {
672         {
673                 boost::mutex::scoped_lock lm (_state_mutex);
674                 _name = n;
675         }
676         signal_changed (NAME);
677 }
678
679 void
680 Film::set_use_dci_name (bool u)
681 {
682         {
683                 boost::mutex::scoped_lock lm (_state_mutex);
684                 _use_dci_name = u;
685         }
686         signal_changed (USE_DCI_NAME);
687 }
688
689 void
690 Film::set_trust_content_headers (bool t)
691 {
692         {
693                 boost::mutex::scoped_lock lm (_state_mutex);
694                 _trust_content_headers = t;
695         }
696         
697         signal_changed (TRUST_CONTENT_HEADERS);
698         
699         Playlist::ContentList content = _playlist->content ();
700         if (!_trust_content_headers && !content.empty()) {
701                 /* We just said that we don't trust the content's header */
702                 for (Playlist::ContentList::iterator i = content.begin(); i != content.end(); ++i) {
703                         examine_content (*i);
704                 }
705         }
706 }
707                
708 void
709 Film::set_dcp_content_type (DCPContentType const * t)
710 {
711         {
712                 boost::mutex::scoped_lock lm (_state_mutex);
713                 _dcp_content_type = t;
714         }
715         signal_changed (DCP_CONTENT_TYPE);
716 }
717
718 void
719 Film::set_format (Format const * f)
720 {
721         {
722                 boost::mutex::scoped_lock lm (_state_mutex);
723                 _format = f;
724         }
725         signal_changed (FORMAT);
726 }
727
728 void
729 Film::set_crop (Crop c)
730 {
731         {
732                 boost::mutex::scoped_lock lm (_state_mutex);
733                 _crop = c;
734         }
735         signal_changed (CROP);
736 }
737
738 void
739 Film::set_left_crop (int c)
740 {
741         {
742                 boost::mutex::scoped_lock lm (_state_mutex);
743                 
744                 if (_crop.left == c) {
745                         return;
746                 }
747                 
748                 _crop.left = c;
749         }
750         signal_changed (CROP);
751 }
752
753 void
754 Film::set_right_crop (int c)
755 {
756         {
757                 boost::mutex::scoped_lock lm (_state_mutex);
758                 if (_crop.right == c) {
759                         return;
760                 }
761                 
762                 _crop.right = c;
763         }
764         signal_changed (CROP);
765 }
766
767 void
768 Film::set_top_crop (int c)
769 {
770         {
771                 boost::mutex::scoped_lock lm (_state_mutex);
772                 if (_crop.top == c) {
773                         return;
774                 }
775                 
776                 _crop.top = c;
777         }
778         signal_changed (CROP);
779 }
780
781 void
782 Film::set_bottom_crop (int c)
783 {
784         {
785                 boost::mutex::scoped_lock lm (_state_mutex);
786                 if (_crop.bottom == c) {
787                         return;
788                 }
789                 
790                 _crop.bottom = c;
791         }
792         signal_changed (CROP);
793 }
794
795 void
796 Film::set_filters (vector<Filter const *> f)
797 {
798         {
799                 boost::mutex::scoped_lock lm (_state_mutex);
800                 _filters = f;
801         }
802         signal_changed (FILTERS);
803 }
804
805 void
806 Film::set_scaler (Scaler const * s)
807 {
808         {
809                 boost::mutex::scoped_lock lm (_state_mutex);
810                 _scaler = s;
811         }
812         signal_changed (SCALER);
813 }
814
815 void
816 Film::set_trim_start (int t)
817 {
818         {
819                 boost::mutex::scoped_lock lm (_state_mutex);
820                 _trim_start = t;
821         }
822         signal_changed (TRIM_START);
823 }
824
825 void
826 Film::set_trim_end (int t)
827 {
828         {
829                 boost::mutex::scoped_lock lm (_state_mutex);
830                 _trim_end = t;
831         }
832         signal_changed (TRIM_END);
833 }
834
835 void
836 Film::set_trim_type (TrimType t)
837 {
838         {
839                 boost::mutex::scoped_lock lm (_state_mutex);
840                 _trim_type = t;
841         }
842         signal_changed (TRIM_TYPE);
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_video_frame_rate (int f)
938 {
939         {
940                 boost::mutex::scoped_lock lm (_state_mutex);
941                 _dcp_video_frame_rate = f;
942         }
943         signal_changed (DCP_VIDEO_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                 set_dcp_video_frame_rate (_playlist->best_dcp_frame_rate ());
957                 break;
958         default:
959                 break;
960         }
961
962         if (ui_signaller) {
963                 ui_signaller->emit (boost::bind (boost::ref (Changed), p));
964         }
965 }
966
967 void
968 Film::set_dci_date_today ()
969 {
970         _dci_date = boost::gregorian::day_clock::local_day ();
971 }
972
973 string
974 Film::info_path (int f) const
975 {
976         boost::filesystem::path p;
977         p /= info_dir ();
978
979         stringstream s;
980         s.width (8);
981         s << setfill('0') << f << ".md5";
982
983         p /= s.str();
984
985         /* info_dir() will already have added any initial bit of the path,
986            so don't call file() on this.
987         */
988         return p.string ();
989 }
990
991 string
992 Film::j2c_path (int f, bool t) const
993 {
994         boost::filesystem::path p;
995         p /= "j2c";
996         p /= video_state_identifier ();
997
998         stringstream s;
999         s.width (8);
1000         s << setfill('0') << f << ".j2c";
1001
1002         if (t) {
1003                 s << ".tmp";
1004         }
1005
1006         p /= s.str();
1007         return file (p.string ());
1008 }
1009
1010 /** Make an educated guess as to whether we have a complete DCP
1011  *  or not.
1012  *  @return true if we do.
1013  */
1014
1015 bool
1016 Film::have_dcp () const
1017 {
1018         try {
1019                 libdcp::DCP dcp (dir (dcp_name()));
1020                 dcp.read ();
1021         } catch (...) {
1022                 return false;
1023         }
1024
1025         return true;
1026 }
1027
1028 shared_ptr<Player>
1029 Film::player () const
1030 {
1031         boost::mutex::scoped_lock lm (_state_mutex);
1032         return shared_ptr<Player> (new Player (shared_from_this (), _playlist));
1033 }
1034
1035 shared_ptr<Playlist>
1036 Film::playlist () const
1037 {
1038         boost::mutex::scoped_lock lm (_state_mutex);
1039         return _playlist;
1040 }
1041
1042 Playlist::ContentList
1043 Film::content () const
1044 {
1045         return _playlist->content ();
1046 }
1047
1048 void
1049 Film::add_content (shared_ptr<Content> c)
1050 {
1051         _playlist->add (c);
1052         examine_content (c);
1053 }
1054
1055 void
1056 Film::remove_content (shared_ptr<Content> c)
1057 {
1058         _playlist->remove (c);
1059 }
1060
1061 Time
1062 Film::length () const
1063 {
1064         return _playlist->length (shared_from_this ());
1065 }
1066
1067 bool
1068 Film::has_subtitles () const
1069 {
1070         return _playlist->has_subtitles ();
1071 }
1072
1073 OutputVideoFrame
1074 Film::best_dcp_video_frame_rate () const
1075 {
1076         return _playlist->best_dcp_frame_rate ();
1077 }
1078
1079 void
1080 Film::playlist_content_changed (boost::weak_ptr<Content> c, int p)
1081 {
1082         if (p == VideoContentProperty::VIDEO_FRAME_RATE) {
1083                 set_dcp_video_frame_rate (_playlist->best_dcp_frame_rate ());
1084         } 
1085
1086         if (ui_signaller) {
1087                 ui_signaller->emit (boost::bind (boost::ref (ContentChanged), c, p));
1088         }
1089 }
1090
1091 void
1092 Film::playlist_changed ()
1093 {
1094         signal_changed (CONTENT);
1095 }       
1096
1097 int
1098 Film::loop () const
1099 {
1100         return _playlist->loop ();
1101 }
1102
1103 void
1104 Film::set_loop (int c)
1105 {
1106         _playlist->set_loop (c);
1107 }
1108
1109 OutputAudioFrame
1110 Film::time_to_audio_frames (Time t) const
1111 {
1112         return t * dcp_audio_frame_rate () / TIME_HZ;
1113 }
1114
1115 OutputVideoFrame
1116 Film::time_to_video_frames (Time t) const
1117 {
1118         return t * dcp_video_frame_rate () / TIME_HZ;
1119 }
1120
1121 Time
1122 Film::audio_frames_to_time (OutputAudioFrame f) const
1123 {
1124         return f * TIME_HZ / dcp_audio_frame_rate ();
1125 }
1126
1127 Time
1128 Film::video_frames_to_time (OutputVideoFrame f) const
1129 {
1130         return f * TIME_HZ / dcp_video_frame_rate ();
1131 }
1132
1133 OutputAudioFrame
1134 Film::dcp_audio_frame_rate () const
1135 {
1136         /* XXX */
1137         return 48000;
1138 }