Various little tweaks.
[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         
700         Playlist::ContentList content = _playlist->content ();
701         if (!_trust_content_headers && !content.empty()) {
702                 /* We just said that we don't trust the content's header */
703                 for (Playlist::ContentList::iterator i = content.begin(); i != content.end(); ++i) {
704                         examine_content (*i);
705                 }
706         }
707 }
708                
709 void
710 Film::set_dcp_content_type (DCPContentType const * t)
711 {
712         {
713                 boost::mutex::scoped_lock lm (_state_mutex);
714                 _dcp_content_type = t;
715         }
716         signal_changed (DCP_CONTENT_TYPE);
717 }
718
719 void
720 Film::set_format (Format const * f)
721 {
722         {
723                 boost::mutex::scoped_lock lm (_state_mutex);
724                 _format = f;
725         }
726         signal_changed (FORMAT);
727 }
728
729 void
730 Film::set_crop (Crop c)
731 {
732         {
733                 boost::mutex::scoped_lock lm (_state_mutex);
734                 _crop = c;
735         }
736         signal_changed (CROP);
737 }
738
739 void
740 Film::set_left_crop (int c)
741 {
742         {
743                 boost::mutex::scoped_lock lm (_state_mutex);
744                 
745                 if (_crop.left == c) {
746                         return;
747                 }
748                 
749                 _crop.left = c;
750         }
751         signal_changed (CROP);
752 }
753
754 void
755 Film::set_right_crop (int c)
756 {
757         {
758                 boost::mutex::scoped_lock lm (_state_mutex);
759                 if (_crop.right == c) {
760                         return;
761                 }
762                 
763                 _crop.right = c;
764         }
765         signal_changed (CROP);
766 }
767
768 void
769 Film::set_top_crop (int c)
770 {
771         {
772                 boost::mutex::scoped_lock lm (_state_mutex);
773                 if (_crop.top == c) {
774                         return;
775                 }
776                 
777                 _crop.top = c;
778         }
779         signal_changed (CROP);
780 }
781
782 void
783 Film::set_bottom_crop (int c)
784 {
785         {
786                 boost::mutex::scoped_lock lm (_state_mutex);
787                 if (_crop.bottom == c) {
788                         return;
789                 }
790                 
791                 _crop.bottom = c;
792         }
793         signal_changed (CROP);
794 }
795
796 void
797 Film::set_filters (vector<Filter const *> f)
798 {
799         {
800                 boost::mutex::scoped_lock lm (_state_mutex);
801                 _filters = f;
802         }
803         signal_changed (FILTERS);
804 }
805
806 void
807 Film::set_scaler (Scaler const * s)
808 {
809         {
810                 boost::mutex::scoped_lock lm (_state_mutex);
811                 _scaler = s;
812         }
813         signal_changed (SCALER);
814 }
815
816 void
817 Film::set_trim_start (int t)
818 {
819         {
820                 boost::mutex::scoped_lock lm (_state_mutex);
821                 _trim_start = t;
822         }
823         signal_changed (TRIM_START);
824 }
825
826 void
827 Film::set_trim_end (int t)
828 {
829         {
830                 boost::mutex::scoped_lock lm (_state_mutex);
831                 _trim_end = t;
832         }
833         signal_changed (TRIM_END);
834 }
835
836 void
837 Film::set_trim_type (TrimType t)
838 {
839         {
840                 boost::mutex::scoped_lock lm (_state_mutex);
841                 _trim_type = t;
842         }
843         signal_changed (TRIM_TYPE);
844 }
845
846 void
847 Film::set_ab (bool a)
848 {
849         {
850                 boost::mutex::scoped_lock lm (_state_mutex);
851                 _ab = a;
852         }
853         signal_changed (AB);
854 }
855
856 void
857 Film::set_audio_gain (float g)
858 {
859         {
860                 boost::mutex::scoped_lock lm (_state_mutex);
861                 _audio_gain = g;
862         }
863         signal_changed (AUDIO_GAIN);
864 }
865
866 void
867 Film::set_audio_delay (int d)
868 {
869         {
870                 boost::mutex::scoped_lock lm (_state_mutex);
871                 _audio_delay = d;
872         }
873         signal_changed (AUDIO_DELAY);
874 }
875
876 void
877 Film::set_with_subtitles (bool w)
878 {
879         {
880                 boost::mutex::scoped_lock lm (_state_mutex);
881                 _with_subtitles = w;
882         }
883         signal_changed (WITH_SUBTITLES);
884 }
885
886 void
887 Film::set_subtitle_offset (int o)
888 {
889         {
890                 boost::mutex::scoped_lock lm (_state_mutex);
891                 _subtitle_offset = o;
892         }
893         signal_changed (SUBTITLE_OFFSET);
894 }
895
896 void
897 Film::set_subtitle_scale (float s)
898 {
899         {
900                 boost::mutex::scoped_lock lm (_state_mutex);
901                 _subtitle_scale = s;
902         }
903         signal_changed (SUBTITLE_SCALE);
904 }
905
906 void
907 Film::set_colour_lut (int i)
908 {
909         {
910                 boost::mutex::scoped_lock lm (_state_mutex);
911                 _colour_lut = i;
912         }
913         signal_changed (COLOUR_LUT);
914 }
915
916 void
917 Film::set_j2k_bandwidth (int b)
918 {
919         {
920                 boost::mutex::scoped_lock lm (_state_mutex);
921                 _j2k_bandwidth = b;
922         }
923         signal_changed (J2K_BANDWIDTH);
924 }
925
926 void
927 Film::set_dci_metadata (DCIMetadata m)
928 {
929         {
930                 boost::mutex::scoped_lock lm (_state_mutex);
931                 _dci_metadata = m;
932         }
933         signal_changed (DCI_METADATA);
934 }
935
936
937 void
938 Film::set_dcp_video_frame_rate (int f)
939 {
940         {
941                 boost::mutex::scoped_lock lm (_state_mutex);
942                 _dcp_video_frame_rate = f;
943         }
944         signal_changed (DCP_VIDEO_FRAME_RATE);
945 }
946
947 void
948 Film::signal_changed (Property p)
949 {
950         {
951                 boost::mutex::scoped_lock lm (_state_mutex);
952                 _dirty = true;
953         }
954
955         switch (p) {
956         case Film::CONTENT:
957                 set_dcp_video_frame_rate (_playlist->best_dcp_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 shared_ptr<Playlist>
1037 Film::playlist () const
1038 {
1039         boost::mutex::scoped_lock lm (_state_mutex);
1040         return _playlist;
1041 }
1042
1043 Playlist::ContentList
1044 Film::content () const
1045 {
1046         return _playlist->content ();
1047 }
1048
1049 void
1050 Film::add_content (shared_ptr<Content> c)
1051 {
1052         _playlist->add (c);
1053         examine_content (c);
1054 }
1055
1056 void
1057 Film::remove_content (shared_ptr<Content> c)
1058 {
1059         _playlist->remove (c);
1060 }
1061
1062 Time
1063 Film::length () const
1064 {
1065         return _playlist->length (shared_from_this ());
1066 }
1067
1068 bool
1069 Film::has_subtitles () const
1070 {
1071         return _playlist->has_subtitles ();
1072 }
1073
1074 OutputVideoFrame
1075 Film::best_dcp_video_frame_rate () const
1076 {
1077         return _playlist->best_dcp_frame_rate ();
1078 }
1079
1080 void
1081 Film::playlist_content_changed (boost::weak_ptr<Content> c, int p)
1082 {
1083         if (p == VideoContentProperty::VIDEO_FRAME_RATE) {
1084                 set_dcp_video_frame_rate (_playlist->best_dcp_frame_rate ());
1085         } 
1086
1087         if (ui_signaller) {
1088                 ui_signaller->emit (boost::bind (boost::ref (ContentChanged), c, p));
1089         }
1090 }
1091
1092 void
1093 Film::playlist_changed ()
1094 {
1095         signal_changed (CONTENT);
1096 }       
1097
1098 int
1099 Film::loop () const
1100 {
1101         return _playlist->loop ();
1102 }
1103
1104 void
1105 Film::set_loop (int c)
1106 {
1107         _playlist->set_loop (c);
1108 }
1109
1110 OutputAudioFrame
1111 Film::time_to_audio_frames (Time t) const
1112 {
1113         return t * dcp_audio_frame_rate () / TIME_HZ;
1114 }
1115
1116 OutputVideoFrame
1117 Film::time_to_video_frames (Time t) const
1118 {
1119         return t * dcp_video_frame_rate () / TIME_HZ;
1120 }
1121
1122 Time
1123 Film::audio_frames_to_time (OutputAudioFrame f) const
1124 {
1125         return f * TIME_HZ / dcp_audio_frame_rate ();
1126 }
1127
1128 Time
1129 Film::video_frames_to_time (OutputVideoFrame f) const
1130 {
1131         return f * TIME_HZ / dcp_video_frame_rate ();
1132 }
1133
1134 OutputAudioFrame
1135 Film::dcp_audio_frame_rate () const
1136 {
1137         /* XXX */
1138         return 48000;
1139 }