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