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