a7be8aea7857265fb0b6b7aff82c9d8726075569
[dcpomatic.git] / src / lib / film.cc
1 /*
2     Copyright (C) 2012-2015 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 /** @file  src/film.cc
21  *  @brief A representation of some audio and video content, and details of
22  *  how they should be presented in a DCP.
23  */
24
25 #include "film.h"
26 #include "job.h"
27 #include "util.h"
28 #include "job_manager.h"
29 #include "transcode_job.h"
30 #include "scp_dcp_job.h"
31 #include "log.h"
32 #include "exceptions.h"
33 #include "examine_content_job.h"
34 #include "config.h"
35 #include "ui_signaller.h"
36 #include "playlist.h"
37 #include "player.h"
38 #include "dcp_content_type.h"
39 #include "ratio.h"
40 #include "cross.h"
41 #include "cinema.h"
42 #include "safe_stringstream.h"
43 #include "environment_info.h"
44 #include "raw_convert.h"
45 #include <libcxml/cxml.h>
46 #include <dcp/cpl.h>
47 #include <dcp/signer.h>
48 #include <dcp/util.h>
49 #include <dcp/local_time.h>
50 #include <dcp/decrypted_kdm.h>
51 #include <libxml++/libxml++.h>
52 #include <boost/filesystem.hpp>
53 #include <boost/algorithm/string.hpp>
54 #include <boost/lexical_cast.hpp>
55 #include <boost/foreach.hpp>
56 #include <unistd.h>
57 #include <stdexcept>
58 #include <iostream>
59 #include <algorithm>
60 #include <fstream>
61 #include <cstdlib>
62 #include <iomanip>
63 #include <set>
64
65 #include "i18n.h"
66
67 using std::string;
68 using std::multimap;
69 using std::pair;
70 using std::map;
71 using std::vector;
72 using std::setfill;
73 using std::min;
74 using std::make_pair;
75 using std::endl;
76 using std::cout;
77 using std::list;
78 using std::set;
79 using boost::shared_ptr;
80 using boost::weak_ptr;
81 using boost::dynamic_pointer_cast;
82 using boost::to_upper_copy;
83 using boost::ends_with;
84 using boost::starts_with;
85 using boost::optional;
86 using boost::is_any_of;
87 using dcp::Size;
88 using dcp::Signer;
89
90 #define LOG_GENERAL(...) log()->log (String::compose (__VA_ARGS__), Log::TYPE_GENERAL);
91 #define LOG_GENERAL_NC(...) log()->log (__VA_ARGS__, Log::TYPE_GENERAL);
92
93 /* 5 -> 6
94  * AudioMapping XML changed.
95  * 6 -> 7
96  * Subtitle offset changed to subtitle y offset, and subtitle x offset added.
97  * 7 -> 8
98  * Use <Scale> tag in <VideoContent> rather than <Ratio>.
99  * 8 -> 9
100  * DCI -> ISDCF
101  * 9 -> 10
102  * Subtitle X and Y scale.
103  *
104  * Bumped to 32 for 2.0 branch; some times are expressed in Times rather
105  * than frames now.
106  */
107 int const Film::current_state_version = 32;
108
109 /** Construct a Film object in a given directory.
110  *
111  *  @param dir Film directory.
112  */
113
114 Film::Film (boost::filesystem::path dir, bool log)
115         : _playlist (new Playlist)
116         , _use_isdcf_name (true)
117         , _dcp_content_type (Config::instance()->default_dcp_content_type ())
118         , _container (Config::instance()->default_container ())
119         , _resolution (RESOLUTION_2K)
120         , _signed (true)
121         , _encrypted (false)
122         , _j2k_bandwidth (Config::instance()->default_j2k_bandwidth ())
123         , _isdcf_metadata (Config::instance()->default_isdcf_metadata ())
124         , _video_frame_rate (24)
125         , _audio_channels (6)
126         , _three_d (false)
127         , _sequence_video (true)
128         , _interop (false)
129         , _burn_subtitles (false)
130         , _state_version (current_state_version)
131         , _dirty (false)
132 {
133         set_isdcf_date_today ();
134
135         _playlist_changed_connection = _playlist->Changed.connect (bind (&Film::playlist_changed, this));
136         _playlist_content_changed_connection = _playlist->ContentChanged.connect (bind (&Film::playlist_content_changed, this, _1, _2));
137         
138         /* Make state.directory a complete path without ..s (where possible)
139            (Code swiped from Adam Bowen on stackoverflow)
140         */
141         
142         boost::filesystem::path p (boost::filesystem::system_complete (dir));
143         boost::filesystem::path result;
144         for (boost::filesystem::path::iterator i = p.begin(); i != p.end(); ++i) {
145                 if (*i == "..") {
146                         if (boost::filesystem::is_symlink (result) || result.filename() == "..") {
147                                 result /= *i;
148                         } else {
149                                 result = result.parent_path ();
150                         }
151                 } else if (*i != ".") {
152                         result /= *i;
153                 }
154         }
155
156         set_directory (result.make_preferred ());
157         if (log) {
158                 _log.reset (new FileLog (file ("log")));
159         } else {
160                 _log.reset (new NullLog);
161         }
162
163         _playlist->set_sequence_video (_sequence_video);
164 }
165
166 Film::~Film ()
167 {
168         for (list<boost::signals2::connection>::const_iterator i = _job_connections.begin(); i != _job_connections.end(); ++i) {
169                 i->disconnect ();
170         }
171 }       
172
173 string
174 Film::video_identifier () const
175 {
176         DCPOMATIC_ASSERT (container ());
177
178         SafeStringStream s;
179         s.imbue (std::locale::classic ());
180         
181         s << container()->id()
182           << "_" << resolution_to_string (_resolution)
183           << "_" << _playlist->video_identifier()
184           << "_" << _video_frame_rate
185           << "_" << j2k_bandwidth();
186
187         if (encrypted ()) {
188                 s << "_E";
189         } else {
190                 s << "_P";
191         }
192
193         if (_interop) {
194                 s << "_I";
195         } else {
196                 s << "_S";
197         }
198
199         if (_burn_subtitles) {
200                 s << "_B";
201         }
202
203         if (_three_d) {
204                 s << "_3D";
205         }
206
207         return s.str ();
208 }
209           
210 /** @return The path to the directory to write video frame info files to */
211 boost::filesystem::path
212 Film::info_dir () const
213 {
214         boost::filesystem::path p;
215         p /= "info";
216         p /= video_identifier ();
217         return dir (p);
218 }
219
220 boost::filesystem::path
221 Film::internal_video_mxf_dir () const
222 {
223         return dir ("video");
224 }
225
226 boost::filesystem::path
227 Film::internal_video_mxf_filename () const
228 {
229         return video_identifier() + ".mxf";
230 }
231
232 boost::filesystem::path
233 Film::video_mxf_filename () const
234 {
235         return filename_safe_name() + "_video.mxf";
236 }
237
238 boost::filesystem::path
239 Film::audio_mxf_filename () const
240 {
241         return filename_safe_name() + "_audio.mxf";
242 }
243
244 boost::filesystem::path
245 Film::subtitle_xml_filename () const
246 {
247         return filename_safe_name() + "_subtitle.xml";
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 boost::filesystem::path
267 Film::audio_analysis_dir () const
268 {
269         return dir ("analysis");
270 }
271
272 /** Add suitable Jobs to the JobManager to create a DCP for this Film */
273 void
274 Film::make_dcp ()
275 {
276         set_isdcf_date_today ();
277         
278         if (dcp_name().find ("/") != string::npos) {
279                 throw BadSettingError (_("name"), _("cannot contain slashes"));
280         }
281
282         environment_info (log ());
283
284         ContentList cl = content ();
285         for (ContentList::const_iterator i = cl.begin(); i != cl.end(); ++i) {
286                 LOG_GENERAL ("Content: %1", (*i)->technical_summary());
287         }
288         LOG_GENERAL ("DCP video rate %1 fps", video_frame_rate());
289         LOG_GENERAL ("%1 threads", Config::instance()->num_local_encoding_threads());
290         LOG_GENERAL ("J2K bandwidth %1", j2k_bandwidth());
291         
292         if (container() == 0) {
293                 throw MissingSettingError (_("container"));
294         }
295
296         if (content().empty()) {
297                 throw StringError (_("You must add some content to the DCP before creating it"));
298         }
299
300         if (dcp_content_type() == 0) {
301                 throw MissingSettingError (_("content type"));
302         }
303
304         if (name().empty()) {
305                 throw MissingSettingError (_("name"));
306         }
307
308         JobManager::instance()->add (shared_ptr<Job> (new TranscodeJob (shared_from_this())));
309 }
310
311 /** Start a job to send our DCP to the configured TMS */
312 void
313 Film::send_dcp_to_tms ()
314 {
315         shared_ptr<Job> j (new SCPDCPJob (shared_from_this()));
316         JobManager::instance()->add (j);
317 }
318
319 /** Count the number of frames that have been encoded for this film.
320  *  @return frame count.
321  */
322 int
323 Film::encoded_frames () const
324 {
325         if (container() == 0) {
326                 return 0;
327         }
328
329         int N = 0;
330         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator (info_dir ()); i != boost::filesystem::directory_iterator(); ++i) {
331                 ++N;
332                 boost::this_thread::interruption_point ();
333         }
334
335         return N;
336 }
337
338 shared_ptr<xmlpp::Document>
339 Film::metadata () const
340 {
341         shared_ptr<xmlpp::Document> doc (new xmlpp::Document);
342         xmlpp::Element* root = doc->create_root_node ("Metadata");
343
344         root->add_child("Version")->add_child_text (raw_convert<string> (current_state_version));
345         root->add_child("Name")->add_child_text (_name);
346         root->add_child("UseISDCFName")->add_child_text (_use_isdcf_name ? "1" : "0");
347
348         if (_dcp_content_type) {
349                 root->add_child("DCPContentType")->add_child_text (_dcp_content_type->isdcf_name ());
350         }
351
352         if (_container) {
353                 root->add_child("Container")->add_child_text (_container->id ());
354         }
355
356         root->add_child("Resolution")->add_child_text (resolution_to_string (_resolution));
357         root->add_child("J2KBandwidth")->add_child_text (raw_convert<string> (_j2k_bandwidth));
358         _isdcf_metadata.as_xml (root->add_child ("ISDCFMetadata"));
359         root->add_child("VideoFrameRate")->add_child_text (raw_convert<string> (_video_frame_rate));
360         root->add_child("ISDCFDate")->add_child_text (boost::gregorian::to_iso_string (_isdcf_date));
361         root->add_child("AudioChannels")->add_child_text (raw_convert<string> (_audio_channels));
362         root->add_child("ThreeD")->add_child_text (_three_d ? "1" : "0");
363         root->add_child("SequenceVideo")->add_child_text (_sequence_video ? "1" : "0");
364         root->add_child("Interop")->add_child_text (_interop ? "1" : "0");
365         root->add_child("BurnSubtitles")->add_child_text (_burn_subtitles ? "1" : "0");
366         root->add_child("Signed")->add_child_text (_signed ? "1" : "0");
367         root->add_child("Encrypted")->add_child_text (_encrypted ? "1" : "0");
368         root->add_child("Key")->add_child_text (_key.hex ());
369         _playlist->as_xml (root->add_child ("Playlist"));
370
371         return doc;
372 }
373
374 /** Write state to our `metadata' file */
375 void
376 Film::write_metadata () const
377 {
378         boost::filesystem::create_directories (directory ());
379         shared_ptr<xmlpp::Document> doc = metadata ();
380         doc->write_to_file_formatted (file("metadata.xml").string ());
381         _dirty = false;
382 }
383
384 /** Read state from our metadata file.
385  *  @return Notes about things that the user should know about, or empty.
386  */
387 list<string>
388 Film::read_metadata ()
389 {
390         if (boost::filesystem::exists (file ("metadata")) && !boost::filesystem::exists (file ("metadata.xml"))) {
391                 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!"));
392         }
393
394         cxml::Document f ("Metadata");
395         f.read_file (file ("metadata.xml"));
396
397         _state_version = f.number_child<int> ("Version");
398         if (_state_version > current_state_version) {
399                 throw StringError (_("This film was created with a newer version of DCP-o-matic, and it cannot be loaded into this version.  Sorry!"));
400         }
401         
402         _name = f.string_child ("Name");
403         if (_state_version >= 9) {
404                 _use_isdcf_name = f.bool_child ("UseISDCFName");
405                 _isdcf_metadata = ISDCFMetadata (f.node_child ("ISDCFMetadata"));
406                 _isdcf_date = boost::gregorian::from_undelimited_string (f.string_child ("ISDCFDate"));
407         } else {
408                 _use_isdcf_name = f.bool_child ("UseDCIName");
409                 _isdcf_metadata = ISDCFMetadata (f.node_child ("DCIMetadata"));
410                 _isdcf_date = boost::gregorian::from_undelimited_string (f.string_child ("DCIDate"));
411         }
412
413         {
414                 optional<string> c = f.optional_string_child ("DCPContentType");
415                 if (c) {
416                         _dcp_content_type = DCPContentType::from_isdcf_name (c.get ());
417                 }
418         }
419
420         {
421                 optional<string> c = f.optional_string_child ("Container");
422                 if (c) {
423                         _container = Ratio::from_id (c.get ());
424                 }
425         }
426
427         _resolution = string_to_resolution (f.string_child ("Resolution"));
428         _j2k_bandwidth = f.number_child<int> ("J2KBandwidth");
429         _video_frame_rate = f.number_child<int> ("VideoFrameRate");
430         _signed = f.optional_bool_child("Signed").get_value_or (true);
431         _encrypted = f.bool_child ("Encrypted");
432         _audio_channels = f.number_child<int> ("AudioChannels");
433         /* We used to allow odd numbers (and zero) channels, but it's just not worth
434            the pain.
435         */
436         if (_audio_channels == 0) {
437                 _audio_channels = 2;
438         } else if ((_audio_channels % 2) == 1) {
439                 _audio_channels++;
440         }
441         _sequence_video = f.bool_child ("SequenceVideo");
442         _three_d = f.bool_child ("ThreeD");
443         _interop = f.bool_child ("Interop");
444         if (_state_version >= 32) {
445                 _burn_subtitles = f.bool_child ("BurnSubtitles");
446         }
447         _key = dcp::Key (f.string_child ("Key"));
448
449         list<string> notes;
450         /* This method is the only one that can return notes (so far) */
451         _playlist->set_from_xml (shared_from_this(), f.node_child ("Playlist"), _state_version, notes);
452
453         /* Write backtraces to this film's directory, until another film is loaded */
454         set_backtrace_file (file ("backtrace.txt"));
455
456         _dirty = false;
457         return notes;
458 }
459
460 /** Given a directory name, return its full path within the Film's directory.
461  *  The directory (and its parents) will be created if they do not exist.
462  */
463 boost::filesystem::path
464 Film::dir (boost::filesystem::path d) const
465 {
466         boost::filesystem::path p;
467         p /= _directory;
468         p /= d;
469         
470         boost::filesystem::create_directories (p);
471         
472         return p;
473 }
474
475 /** Given a file or directory name, return its full path within the Film's directory.
476  *  Any required parent directories will be created.
477  */
478 boost::filesystem::path
479 Film::file (boost::filesystem::path f) const
480 {
481         boost::filesystem::path p;
482         p /= _directory;
483         p /= f;
484
485         boost::filesystem::create_directories (p.parent_path ());
486         
487         return p;
488 }
489
490 /** @return a ISDCF-compliant name for a DCP of this film */
491 string
492 Film::isdcf_name (bool if_created_now) const
493 {
494         SafeStringStream d;
495
496         string raw_name = name ();
497
498         /* Split the raw name up into words */
499         vector<string> words;
500         split (words, raw_name, is_any_of (" "));
501
502         string fixed_name;
503         
504         /* Add each word to fixed_name */
505         for (vector<string>::const_iterator i = words.begin(); i != words.end(); ++i) {
506                 string w = *i;
507
508                 /* First letter is always capitalised */
509                 w[0] = toupper (w[0]);
510
511                 /* Count caps in w */
512                 size_t caps = 0;
513                 for (size_t i = 0; i < w.size(); ++i) {
514                         if (isupper (w[i])) {
515                                 ++caps;
516                         }
517                 }
518                 
519                 /* If w is all caps make the rest of it lower case, otherwise
520                    leave it alone.
521                 */
522                 if (caps == w.size ()) {
523                         for (size_t i = 1; i < w.size(); ++i) {
524                                 w[i] = tolower (w[i]);
525                         }
526                 }
527
528                 for (size_t i = 0; i < w.size(); ++i) {
529                         fixed_name += w[i];
530                 }
531         }
532
533         if (fixed_name.length() > 14) {
534                 fixed_name = fixed_name.substr (0, 14);
535         }
536
537         d << fixed_name;
538
539         if (dcp_content_type()) {
540                 d << "_" << dcp_content_type()->isdcf_name();
541                 d << "-" << isdcf_metadata().content_version;
542         }
543
544         ISDCFMetadata const dm = isdcf_metadata ();
545
546         if (dm.temp_version) {
547                 d << "-Temp";
548         }
549         
550         if (dm.pre_release) {
551                 d << "-Pre";
552         }
553         
554         if (dm.red_band) {
555                 d << "-RedBand";
556         }
557         
558         if (!dm.chain.empty ()) {
559                 d << "-" << dm.chain;
560         }
561
562         if (three_d ()) {
563                 d << "-3D";
564         }
565
566         if (dm.two_d_version_of_three_d) {
567                 d << "-2D";
568         }
569
570         if (!dm.mastered_luminance.empty ()) {
571                 d << "-" << dm.mastered_luminance;
572         }
573
574         if (video_frame_rate() != 24) {
575                 d << "-" << video_frame_rate();
576         }
577         
578         if (container()) {
579                 d << "_" << container()->isdcf_name();
580         }
581
582         ContentList cl = content ();
583         
584         /* XXX: this uses the first bit of content only */
585
586         /* The standard says we don't do this for trailers, for some strange reason */
587         if (dcp_content_type() && dcp_content_type()->libdcp_kind() != dcp::TRAILER) {
588                 Ratio const * content_ratio = 0;
589                 for (ContentList::iterator i = cl.begin(); i != cl.end(); ++i) {
590                         shared_ptr<VideoContent> vc = dynamic_pointer_cast<VideoContent> (*i);
591                         if (vc) {
592                                 /* Here's the first piece of video content */
593                                 if (vc->scale().ratio ()) {
594                                         content_ratio = vc->scale().ratio ();
595                                 } else {
596                                         content_ratio = Ratio::from_ratio (vc->video_size().ratio ());
597                                 }
598                                 break;
599                         }
600                 }
601                 
602                 if (content_ratio && content_ratio != container()) {
603                         d << "-" << content_ratio->isdcf_name();
604                 }
605         }
606
607         if (!dm.audio_language.empty ()) {
608                 d << "_" << dm.audio_language;
609                 if (!dm.subtitle_language.empty()) {
610                         d << "-" << dm.subtitle_language;
611                 } else {
612                         d << "-XX";
613                 }
614         }
615
616         if (!dm.territory.empty ()) {
617                 d << "_" << dm.territory;
618                 if (!dm.rating.empty ()) {
619                         d << "-" << dm.rating;
620                 }
621         }
622
623         /* Find all mapped channels */
624
625         list<dcp::Channel> mapped;
626         for (ContentList::const_iterator i = cl.begin(); i != cl.end(); ++i) {
627                 shared_ptr<const AudioContent> ac = dynamic_pointer_cast<const AudioContent> (*i);
628                 if (ac) {
629                         list<dcp::Channel> c = ac->audio_mapping().mapped_dcp_channels ();
630                         copy (c.begin(), c.end(), back_inserter (mapped));
631                 }
632         }
633
634         mapped.sort ();
635         mapped.unique ();
636         
637         /* Count them */
638                         
639         int non_lfe = 0;
640         int lfe = 0;
641         for (list<dcp::Channel>::const_iterator i = mapped.begin(); i != mapped.end(); ++i) {
642                 if (static_cast<int> (*i) >= audio_channels()) {
643                         /* This channel is mapped but is not included in the DCP */
644                         continue;
645                 }
646                 
647                 if ((*i) == dcp::LFE) {
648                         ++lfe;
649                 } else {
650                         ++non_lfe;
651                 }
652         }
653
654         if (non_lfe) {
655                 d << "_" << non_lfe << lfe;
656         }
657
658         /* XXX: HI/VI */
659
660         d << "_" << resolution_to_string (_resolution);
661         
662         if (!dm.studio.empty ()) {
663                 d << "_" << dm.studio;
664         }
665
666         if (if_created_now) {
667                 d << "_" << boost::gregorian::to_iso_string (boost::gregorian::day_clock::local_day ());
668         } else {
669                 d << "_" << boost::gregorian::to_iso_string (_isdcf_date);
670         }
671
672         if (!dm.facility.empty ()) {
673                 d << "_" << dm.facility;
674         }
675
676         if (_interop) {
677                 d << "_IOP";
678         } else {
679                 d << "_SMPTE";
680         }
681         
682         if (three_d ()) {
683                 d << "-3D";
684         }
685
686         if (!dm.package_type.empty ()) {
687                 d << "_" << dm.package_type;
688         }
689
690         return d.str ();
691 }
692
693 /** @return name to give the DCP */
694 string
695 Film::dcp_name (bool if_created_now) const
696 {
697         if (use_isdcf_name()) {
698                 return isdcf_name (if_created_now);
699         }
700
701         return name();
702 }
703
704 void
705 Film::set_directory (boost::filesystem::path d)
706 {
707         _directory = d;
708         _dirty = true;
709 }
710
711 void
712 Film::set_name (string n)
713 {
714         _name = n;
715         signal_changed (NAME);
716 }
717
718 void
719 Film::set_use_isdcf_name (bool u)
720 {
721         _use_isdcf_name = u;
722         signal_changed (USE_ISDCF_NAME);
723 }
724
725 void
726 Film::set_dcp_content_type (DCPContentType const * t)
727 {
728         _dcp_content_type = t;
729         signal_changed (DCP_CONTENT_TYPE);
730 }
731
732 void
733 Film::set_container (Ratio const * c)
734 {
735         _container = c;
736         signal_changed (CONTAINER);
737 }
738
739 void
740 Film::set_resolution (Resolution r)
741 {
742         _resolution = r;
743         signal_changed (RESOLUTION);
744 }
745
746 void
747 Film::set_j2k_bandwidth (int b)
748 {
749         _j2k_bandwidth = b;
750         signal_changed (J2K_BANDWIDTH);
751 }
752
753 void
754 Film::set_isdcf_metadata (ISDCFMetadata m)
755 {
756         _isdcf_metadata = m;
757         signal_changed (ISDCF_METADATA);
758 }
759
760 void
761 Film::set_video_frame_rate (int f)
762 {
763         _video_frame_rate = f;
764         signal_changed (VIDEO_FRAME_RATE);
765 }
766
767 void
768 Film::set_audio_channels (int c)
769 {
770         _audio_channels = c;
771         signal_changed (AUDIO_CHANNELS);
772 }
773
774 void
775 Film::set_three_d (bool t)
776 {
777         _three_d = t;
778         signal_changed (THREE_D);
779 }
780
781 void
782 Film::set_interop (bool i)
783 {
784         _interop = i;
785         signal_changed (INTEROP);
786 }
787
788 void
789 Film::set_burn_subtitles (bool b)
790 {
791         _burn_subtitles = b;
792         signal_changed (BURN_SUBTITLES);
793 }
794
795 void
796 Film::signal_changed (Property p)
797 {
798         _dirty = true;
799
800         switch (p) {
801         case Film::CONTENT:
802                 set_video_frame_rate (_playlist->best_dcp_frame_rate ());
803                 break;
804         case Film::VIDEO_FRAME_RATE:
805         case Film::SEQUENCE_VIDEO:
806                 _playlist->maybe_sequence_video ();
807                 break;
808         default:
809                 break;
810         }
811
812         if (ui_signaller) {
813                 ui_signaller->emit (boost::bind (boost::ref (Changed), p));
814         }
815 }
816
817 void
818 Film::set_isdcf_date_today ()
819 {
820         _isdcf_date = boost::gregorian::day_clock::local_day ();
821 }
822
823 boost::filesystem::path
824 Film::info_path (int f, Eyes e) const
825 {
826         boost::filesystem::path p;
827         p /= info_dir ();
828
829         SafeStringStream s;
830         s.width (8);
831         s << setfill('0') << f;
832
833         if (e == EYES_LEFT) {
834                 s << ".L";
835         } else if (e == EYES_RIGHT) {
836                 s << ".R";
837         }
838
839         s << ".md5";
840         
841         p /= s.str();
842
843         /* info_dir() will already have added any initial bit of the path,
844            so don't call file() on this.
845         */
846         return p;
847 }
848
849 boost::filesystem::path
850 Film::j2c_path (int f, Eyes e, bool t) const
851 {
852         boost::filesystem::path p;
853         p /= "j2c";
854         p /= video_identifier ();
855
856         SafeStringStream s;
857         s.width (8);
858         s << setfill('0') << f;
859
860         if (e == EYES_LEFT) {
861                 s << ".L";
862         } else if (e == EYES_RIGHT) {
863                 s << ".R";
864         }
865         
866         s << ".j2c";
867
868         if (t) {
869                 s << ".tmp";
870         }
871
872         p /= s.str();
873         return file (p);
874 }
875
876 /** Find all the DCPs in our directory that can be dcp::DCP::read() and return details of their CPLs */
877 vector<CPLSummary>
878 Film::cpls () const
879 {
880         vector<CPLSummary> out;
881         
882         boost::filesystem::path const dir = directory ();
883         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator(dir); i != boost::filesystem::directory_iterator(); ++i) {
884                 if (
885                         boost::filesystem::is_directory (*i) &&
886                         i->path().leaf() != "j2c" && i->path().leaf() != "video" && i->path().leaf() != "info" && i->path().leaf() != "analysis"
887                         ) {
888
889                         try {
890                                 dcp::DCP dcp (*i);
891                                 dcp.read ();
892                                 out.push_back (
893                                         CPLSummary (
894                                                 i->path().leaf().string(),
895                                                 dcp.cpls().front()->id(),
896                                                 dcp.cpls().front()->annotation_text(),
897                                                 dcp.cpls().front()->file()
898                                                 )
899                                         );
900                         } catch (...) {
901
902                         }
903                 }
904         }
905         
906         return out;
907 }
908
909 shared_ptr<Player>
910 Film::make_player () const
911 {
912         return shared_ptr<Player> (new Player (shared_from_this (), _playlist));
913 }
914
915 void
916 Film::set_signed (bool s)
917 {
918         _signed = s;
919         signal_changed (SIGNED);
920 }
921
922 void
923 Film::set_encrypted (bool e)
924 {
925         _encrypted = e;
926         signal_changed (ENCRYPTED);
927 }
928
929 shared_ptr<Playlist>
930 Film::playlist () const
931 {
932         return _playlist;
933 }
934
935 ContentList
936 Film::content () const
937 {
938         return _playlist->content ();
939 }
940
941 void
942 Film::examine_content (shared_ptr<Content> c)
943 {
944         shared_ptr<Job> j (new ExamineContentJob (shared_from_this(), c));
945         JobManager::instance()->add (j);
946 }
947
948 void
949 Film::examine_and_add_content (shared_ptr<Content> c)
950 {
951         if (dynamic_pointer_cast<FFmpegContent> (c)) {
952                 run_ffprobe (c->path(0), file ("ffprobe.log"), _log);
953         }
954                         
955         shared_ptr<Job> j (new ExamineContentJob (shared_from_this(), c));
956
957         _job_connections.push_back (
958                 j->Finished.connect (bind (&Film::maybe_add_content, this, boost::weak_ptr<Job> (j), boost::weak_ptr<Content> (c)))
959                 );
960         
961         JobManager::instance()->add (j);
962 }
963
964 void
965 Film::maybe_add_content (weak_ptr<Job> j, weak_ptr<Content> c)
966 {
967         shared_ptr<Job> job = j.lock ();
968         if (!job || !job->finished_ok ()) {
969                 return;
970         }
971         
972         shared_ptr<Content> content = c.lock ();
973         if (content) {
974                 add_content (content);
975         }
976 }
977
978 void
979 Film::add_content (shared_ptr<Content> c)
980 {
981         /* Add video content after any existing content */
982         if (dynamic_pointer_cast<VideoContent> (c)) {
983                 c->set_position (_playlist->video_end ());
984         }
985
986         _playlist->add (c);
987 }
988
989 void
990 Film::remove_content (shared_ptr<Content> c)
991 {
992         _playlist->remove (c);
993 }
994
995 void
996 Film::move_content_earlier (shared_ptr<Content> c)
997 {
998         _playlist->move_earlier (c);
999 }
1000
1001 void
1002 Film::move_content_later (shared_ptr<Content> c)
1003 {
1004         _playlist->move_later (c);
1005 }
1006
1007 DCPTime
1008 Film::length () const
1009 {
1010         return _playlist->length ();
1011 }
1012
1013 int
1014 Film::best_video_frame_rate () const
1015 {
1016         return _playlist->best_dcp_frame_rate ();
1017 }
1018
1019 FrameRateChange
1020 Film::active_frame_rate_change (DCPTime t) const
1021 {
1022         return _playlist->active_frame_rate_change (t, video_frame_rate ());
1023 }
1024
1025 void
1026 Film::playlist_content_changed (boost::weak_ptr<Content> c, int p)
1027 {
1028         if (p == VideoContentProperty::VIDEO_FRAME_RATE) {
1029                 set_video_frame_rate (_playlist->best_dcp_frame_rate ());
1030         } else if (
1031                 p == AudioContentProperty::AUDIO_MAPPING ||
1032                 p == AudioContentProperty::AUDIO_CHANNELS) {
1033                 signal_changed (NAME);
1034         }
1035
1036         if (ui_signaller) {
1037                 ui_signaller->emit (boost::bind (boost::ref (ContentChanged), c, p));
1038         }
1039 }
1040
1041 void
1042 Film::playlist_changed ()
1043 {
1044         signal_changed (CONTENT);
1045         signal_changed (NAME);
1046 }       
1047
1048 int
1049 Film::audio_frame_rate () const
1050 {
1051         /* XXX */
1052         return 48000;
1053 }
1054
1055 void
1056 Film::set_sequence_video (bool s)
1057 {
1058         _sequence_video = s;
1059         _playlist->set_sequence_video (s);
1060         signal_changed (SEQUENCE_VIDEO);
1061 }
1062
1063 /** @return Size of the largest possible image in whatever resolution we are using */
1064 dcp::Size
1065 Film::full_frame () const
1066 {
1067         switch (_resolution) {
1068         case RESOLUTION_2K:
1069                 return dcp::Size (2048, 1080);
1070         case RESOLUTION_4K:
1071                 return dcp::Size (4096, 2160);
1072         }
1073
1074         DCPOMATIC_ASSERT (false);
1075         return dcp::Size ();
1076 }
1077
1078 /** @return Size of the frame */
1079 dcp::Size
1080 Film::frame_size () const
1081 {
1082         return fit_ratio_within (container()->ratio(), full_frame (), 1);
1083 }
1084
1085 dcp::EncryptedKDM
1086 Film::make_kdm (
1087         dcp::Certificate target,
1088         boost::filesystem::path cpl_file,
1089         dcp::LocalTime from,
1090         dcp::LocalTime until,
1091         dcp::Formulation formulation
1092         ) const
1093 {
1094         shared_ptr<const dcp::CPL> cpl (new dcp::CPL (cpl_file));
1095         shared_ptr<const dcp::Signer> signer = Config::instance()->signer();
1096         if (!signer->valid ()) {
1097                 throw InvalidSignerError ();
1098         }
1099         
1100         return dcp::DecryptedKDM (
1101                 cpl, key(), from, until, "DCP-o-matic", cpl->content_title_text(), dcp::LocalTime().as_string()
1102                 ).encrypt (signer, target, formulation);
1103 }
1104
1105 list<dcp::EncryptedKDM>
1106 Film::make_kdms (
1107         list<shared_ptr<Screen> > screens,
1108         boost::filesystem::path dcp,
1109         dcp::LocalTime from,
1110         dcp::LocalTime until,
1111         dcp::Formulation formulation
1112         ) const
1113 {
1114         list<dcp::EncryptedKDM> kdms;
1115
1116         for (list<shared_ptr<Screen> >::iterator i = screens.begin(); i != screens.end(); ++i) {
1117                 if ((*i)->certificate) {
1118                         kdms.push_back (make_kdm ((*i)->certificate.get(), dcp, from, until, formulation));
1119                 }
1120         }
1121
1122         return kdms;
1123 }
1124
1125 /** @return The approximate disk space required to encode a DCP of this film with the
1126  *  current settings, in bytes.
1127  */
1128 uint64_t
1129 Film::required_disk_space () const
1130 {
1131         return uint64_t (j2k_bandwidth() / 8) * length().seconds();
1132 }
1133
1134 /** This method checks the disk that the Film is on and tries to decide whether or not
1135  *  there will be enough space to make a DCP for it.  If so, true is returned; if not,
1136  *  false is returned and required and availabe are filled in with the amount of disk space
1137  *  required and available respectively (in Gb).
1138  *
1139  *  Note: the decision made by this method isn't, of course, 100% reliable.
1140  */
1141 bool
1142 Film::should_be_enough_disk_space (double& required, double& available) const
1143 {
1144         boost::filesystem::space_info s = boost::filesystem::space (internal_video_mxf_dir ());
1145         required = double (required_disk_space ()) / 1073741824.0f;
1146         available = double (s.available) / 1073741824.0f;
1147         return (available - required) > 1;
1148 }
1149
1150 string
1151 Film::subtitle_language () const
1152 {
1153         set<string> languages;
1154         
1155         ContentList cl = content ();
1156         BOOST_FOREACH (shared_ptr<Content>& c, cl) {
1157                 shared_ptr<SubtitleContent> sc = dynamic_pointer_cast<SubtitleContent> (c);
1158                 if (sc) {
1159                         languages.insert (sc->subtitle_language ());
1160                 }
1161         }
1162
1163         string all;
1164         BOOST_FOREACH (string s, languages) {
1165                 if (!all.empty ()) {
1166                         all += "/" + s;
1167                 } else {
1168                         all += s;
1169                 }
1170         }
1171
1172         return all;
1173 }