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