Add only-servers-encode option for debugging / optimisation / testing of servers.
[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         if (Config::instance()->only_servers_encode ()) {
270                 LOG_GENERAL_NC ("0 threads: ONLY SERVERS SET TO ENCODE");
271         } else {
272                 LOG_GENERAL ("%1 threads", Config::instance()->num_local_encoding_threads());
273         }
274         LOG_GENERAL ("J2K bandwidth %1", j2k_bandwidth());
275
276         if (container() == 0) {
277                 throw MissingSettingError (_("container"));
278         }
279
280         if (content().empty()) {
281                 throw StringError (_("You must add some content to the DCP before creating it"));
282         }
283
284         if (dcp_content_type() == 0) {
285                 throw MissingSettingError (_("content type"));
286         }
287
288         if (name().empty()) {
289                 throw MissingSettingError (_("name"));
290         }
291
292         JobManager::instance()->add (shared_ptr<Job> (new TranscodeJob (shared_from_this())));
293 }
294
295 /** Start a job to send our DCP to the configured TMS */
296 void
297 Film::send_dcp_to_tms ()
298 {
299         shared_ptr<Job> j (new UploadJob (shared_from_this()));
300         JobManager::instance()->add (j);
301 }
302
303 shared_ptr<xmlpp::Document>
304 Film::metadata () const
305 {
306         shared_ptr<xmlpp::Document> doc (new xmlpp::Document);
307         xmlpp::Element* root = doc->create_root_node ("Metadata");
308
309         root->add_child("Version")->add_child_text (raw_convert<string> (current_state_version));
310         root->add_child("Name")->add_child_text (_name);
311         root->add_child("UseISDCFName")->add_child_text (_use_isdcf_name ? "1" : "0");
312
313         if (_dcp_content_type) {
314                 root->add_child("DCPContentType")->add_child_text (_dcp_content_type->isdcf_name ());
315         }
316
317         if (_container) {
318                 root->add_child("Container")->add_child_text (_container->id ());
319         }
320
321         root->add_child("Resolution")->add_child_text (resolution_to_string (_resolution));
322         root->add_child("J2KBandwidth")->add_child_text (raw_convert<string> (_j2k_bandwidth));
323         _isdcf_metadata.as_xml (root->add_child ("ISDCFMetadata"));
324         root->add_child("VideoFrameRate")->add_child_text (raw_convert<string> (_video_frame_rate));
325         root->add_child("ISDCFDate")->add_child_text (boost::gregorian::to_iso_string (_isdcf_date));
326         root->add_child("AudioChannels")->add_child_text (raw_convert<string> (_audio_channels));
327         root->add_child("ThreeD")->add_child_text (_three_d ? "1" : "0");
328         root->add_child("SequenceVideo")->add_child_text (_sequence_video ? "1" : "0");
329         root->add_child("Interop")->add_child_text (_interop ? "1" : "0");
330         root->add_child("Signed")->add_child_text (_signed ? "1" : "0");
331         root->add_child("Encrypted")->add_child_text (_encrypted ? "1" : "0");
332         root->add_child("Key")->add_child_text (_key.hex ());
333         if (_audio_processor) {
334                 root->add_child("AudioProcessor")->add_child_text (_audio_processor->id ());
335         }
336         _playlist->as_xml (root->add_child ("Playlist"));
337
338         return doc;
339 }
340
341 /** Write state to our `metadata' file */
342 void
343 Film::write_metadata () const
344 {
345         boost::filesystem::create_directories (directory ());
346         shared_ptr<xmlpp::Document> doc = metadata ();
347         doc->write_to_file_formatted (file("metadata.xml").string ());
348         _dirty = false;
349 }
350
351 /** Read state from our metadata file.
352  *  @return Notes about things that the user should know about, or empty.
353  */
354 list<string>
355 Film::read_metadata ()
356 {
357         if (boost::filesystem::exists (file ("metadata")) && !boost::filesystem::exists (file ("metadata.xml"))) {
358                 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!"));
359         }
360
361         cxml::Document f ("Metadata");
362         f.read_file (file ("metadata.xml"));
363
364         _state_version = f.number_child<int> ("Version");
365         if (_state_version > current_state_version) {
366                 throw StringError (_("This film was created with a newer version of DCP-o-matic, and it cannot be loaded into this version.  Sorry!"));
367         }
368
369         _name = f.string_child ("Name");
370         if (_state_version >= 9) {
371                 _use_isdcf_name = f.bool_child ("UseISDCFName");
372                 _isdcf_metadata = ISDCFMetadata (f.node_child ("ISDCFMetadata"));
373                 _isdcf_date = boost::gregorian::from_undelimited_string (f.string_child ("ISDCFDate"));
374         } else {
375                 _use_isdcf_name = f.bool_child ("UseDCIName");
376                 _isdcf_metadata = ISDCFMetadata (f.node_child ("DCIMetadata"));
377                 _isdcf_date = boost::gregorian::from_undelimited_string (f.string_child ("DCIDate"));
378         }
379
380         {
381                 optional<string> c = f.optional_string_child ("DCPContentType");
382                 if (c) {
383                         _dcp_content_type = DCPContentType::from_isdcf_name (c.get ());
384                 }
385         }
386
387         {
388                 optional<string> c = f.optional_string_child ("Container");
389                 if (c) {
390                         _container = Ratio::from_id (c.get ());
391                 }
392         }
393
394         _resolution = string_to_resolution (f.string_child ("Resolution"));
395         _j2k_bandwidth = f.number_child<int> ("J2KBandwidth");
396         _video_frame_rate = f.number_child<int> ("VideoFrameRate");
397         _signed = f.optional_bool_child("Signed").get_value_or (true);
398         _encrypted = f.bool_child ("Encrypted");
399         _audio_channels = f.number_child<int> ("AudioChannels");
400         /* We used to allow odd numbers (and zero) channels, but it's just not worth
401            the pain.
402         */
403         if (_audio_channels == 0) {
404                 _audio_channels = 2;
405         } else if ((_audio_channels % 2) == 1) {
406                 _audio_channels++;
407         }
408         _sequence_video = f.bool_child ("SequenceVideo");
409         _three_d = f.bool_child ("ThreeD");
410         _interop = f.bool_child ("Interop");
411         _key = dcp::Key (f.string_child ("Key"));
412
413         if (f.optional_string_child ("AudioProcessor")) {
414                 _audio_processor = AudioProcessor::from_id (f.string_child ("AudioProcessor"));
415         } else {
416                 _audio_processor = 0;
417         }
418
419         list<string> notes;
420         /* This method is the only one that can return notes (so far) */
421         _playlist->set_from_xml (shared_from_this(), f.node_child ("Playlist"), _state_version, notes);
422
423         /* Write backtraces to this film's directory, until another film is loaded */
424         set_backtrace_file (file ("backtrace.txt"));
425
426         _dirty = false;
427         return notes;
428 }
429
430 /** Given a directory name, return its full path within the Film's directory.
431  *  The directory (and its parents) will be created if they do not exist.
432  */
433 boost::filesystem::path
434 Film::dir (boost::filesystem::path d) const
435 {
436         boost::filesystem::path p;
437         p /= _directory;
438         p /= d;
439
440         boost::filesystem::create_directories (p);
441
442         return p;
443 }
444
445 /** Given a file or directory name, return its full path within the Film's directory.
446  *  Any required parent directories will be created.
447  */
448 boost::filesystem::path
449 Film::file (boost::filesystem::path f) const
450 {
451         boost::filesystem::path p;
452         p /= _directory;
453         p /= f;
454
455         boost::filesystem::create_directories (p.parent_path ());
456
457         return p;
458 }
459
460 /** @return a ISDCF-compliant name for a DCP of this film */
461 string
462 Film::isdcf_name (bool if_created_now) const
463 {
464         SafeStringStream d;
465
466         string raw_name = name ();
467
468         /* Split the raw name up into words */
469         vector<string> words;
470         split (words, raw_name, is_any_of (" _-"));
471
472         string fixed_name;
473
474         /* Add each word to fixed_name */
475         for (vector<string>::const_iterator i = words.begin(); i != words.end(); ++i) {
476                 string w = *i;
477
478                 /* First letter is always capitalised */
479                 w[0] = toupper (w[0]);
480
481                 /* Count caps in w */
482                 size_t caps = 0;
483                 for (size_t i = 0; i < w.size(); ++i) {
484                         if (isupper (w[i])) {
485                                 ++caps;
486                         }
487                 }
488
489                 /* If w is all caps make the rest of it lower case, otherwise
490                    leave it alone.
491                 */
492                 if (caps == w.size ()) {
493                         for (size_t i = 1; i < w.size(); ++i) {
494                                 w[i] = tolower (w[i]);
495                         }
496                 }
497
498                 for (size_t i = 0; i < w.size(); ++i) {
499                         fixed_name += w[i];
500                 }
501         }
502
503         if (fixed_name.length() > 14) {
504                 fixed_name = fixed_name.substr (0, 14);
505         }
506
507         d << fixed_name;
508
509         if (dcp_content_type()) {
510                 d << "_" << dcp_content_type()->isdcf_name();
511                 d << "-" << isdcf_metadata().content_version;
512         }
513
514         ISDCFMetadata const dm = isdcf_metadata ();
515
516         if (dm.temp_version) {
517                 d << "-Temp";
518         }
519
520         if (dm.pre_release) {
521                 d << "-Pre";
522         }
523
524         if (dm.red_band) {
525                 d << "-RedBand";
526         }
527
528         if (!dm.chain.empty ()) {
529                 d << "-" << dm.chain;
530         }
531
532         if (three_d ()) {
533                 d << "-3D";
534         }
535
536         if (dm.two_d_version_of_three_d) {
537                 d << "-2D";
538         }
539
540         if (!dm.mastered_luminance.empty ()) {
541                 d << "-" << dm.mastered_luminance;
542         }
543
544         if (video_frame_rate() != 24) {
545                 d << "-" << video_frame_rate();
546         }
547
548         if (container()) {
549                 d << "_" << container()->isdcf_name();
550         }
551
552         ContentList cl = content ();
553
554         /* XXX: this uses the first bit of content only */
555
556         /* The standard says we don't do this for trailers, for some strange reason */
557         if (dcp_content_type() && dcp_content_type()->libdcp_kind() != dcp::TRAILER) {
558                 Ratio const * content_ratio = 0;
559                 for (ContentList::iterator i = cl.begin(); i != cl.end(); ++i) {
560                         shared_ptr<VideoContent> vc = dynamic_pointer_cast<VideoContent> (*i);
561                         if (vc) {
562                                 /* Here's the first piece of video content */
563                                 if (vc->scale().ratio ()) {
564                                         content_ratio = vc->scale().ratio ();
565                                 } else {
566                                         content_ratio = Ratio::from_ratio (vc->video_size().ratio ());
567                                 }
568                                 break;
569                         }
570                 }
571
572                 if (content_ratio && content_ratio != container()) {
573                         d << "-" << content_ratio->isdcf_name();
574                 }
575         }
576
577         if (!dm.audio_language.empty ()) {
578                 d << "_" << dm.audio_language;
579                 if (!dm.subtitle_language.empty()) {
580                         d << "-" << dm.subtitle_language;
581                 } else {
582                         d << "-XX";
583                 }
584         }
585
586         if (!dm.territory.empty ()) {
587                 d << "_" << dm.territory;
588                 if (dm.rating.empty ()) {
589                         d << "-NR";
590                 } else {
591                         d << "-" << dm.rating;
592                 }
593         }
594
595         /* Find all mapped channels */
596
597         int non_lfe = 0;
598         int lfe = 0;
599
600         if (audio_processor ()) {
601                 /* Processors are mapped 1:1 to DCP outputs so we can guess the number of LFE/
602                    non-LFE from the channel counts.
603                 */
604                 non_lfe = audio_processor()->out_channels ();
605                 if (non_lfe >= 4) {
606                         --non_lfe;
607                         ++lfe;
608                 }
609         } else {
610                 list<int> mapped;
611                 for (ContentList::const_iterator i = cl.begin(); i != cl.end(); ++i) {
612                         shared_ptr<const AudioContent> ac = dynamic_pointer_cast<const AudioContent> (*i);
613                         if (ac) {
614                                 list<int> c = ac->audio_mapping().mapped_output_channels ();
615                                 copy (c.begin(), c.end(), back_inserter (mapped));
616                         }
617                 }
618
619                 mapped.sort ();
620                 mapped.unique ();
621
622                 /* Count them */
623
624                 for (list<int>::const_iterator i = mapped.begin(); i != mapped.end(); ++i) {
625                         if (*i >= audio_channels()) {
626                                 /* This channel is mapped but is not included in the DCP */
627                                 continue;
628                         }
629
630                         if (static_cast<dcp::Channel> (*i) == dcp::LFE) {
631                                 ++lfe;
632                         } else {
633                                 ++non_lfe;
634                         }
635                 }
636         }
637
638         if (non_lfe) {
639                 d << "_" << non_lfe << lfe;
640         }
641
642         /* XXX: HI/VI */
643
644         d << "_" << resolution_to_string (_resolution);
645
646         if (!dm.studio.empty ()) {
647                 d << "_" << dm.studio;
648         }
649
650         if (if_created_now) {
651                 d << "_" << boost::gregorian::to_iso_string (boost::gregorian::day_clock::local_day ());
652         } else {
653                 d << "_" << boost::gregorian::to_iso_string (_isdcf_date);
654         }
655
656         if (!dm.facility.empty ()) {
657                 d << "_" << dm.facility;
658         }
659
660         if (_interop) {
661                 d << "_IOP";
662         } else {
663                 d << "_SMPTE";
664         }
665
666         if (three_d ()) {
667                 d << "-3D";
668         }
669
670         if (!dm.package_type.empty ()) {
671                 d << "_" << dm.package_type;
672         }
673
674         return d.str ();
675 }
676
677 /** @return name to give the DCP */
678 string
679 Film::dcp_name (bool if_created_now) const
680 {
681         string unfiltered;
682         if (use_isdcf_name()) {
683                 unfiltered = isdcf_name (if_created_now);
684         } else {
685                 unfiltered = name ();
686         }
687
688         /* Filter out `bad' characters which cause problems with some systems.
689            There's no apparent list of what really is allowed, so this is a guess.
690         */
691
692         string filtered;
693         string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";
694         for (size_t i = 0; i < unfiltered.size(); ++i) {
695                 if (allowed.find (unfiltered[i]) != string::npos) {
696                         filtered += unfiltered[i];
697                 }
698         }
699
700         return filtered;
701 }
702
703 void
704 Film::set_directory (boost::filesystem::path d)
705 {
706         _directory = d;
707         _dirty = true;
708 }
709
710 void
711 Film::set_name (string n)
712 {
713         _name = n;
714         signal_changed (NAME);
715 }
716
717 void
718 Film::set_use_isdcf_name (bool u)
719 {
720         _use_isdcf_name = u;
721         signal_changed (USE_ISDCF_NAME);
722 }
723
724 void
725 Film::set_dcp_content_type (DCPContentType const * t)
726 {
727         _dcp_content_type = t;
728         signal_changed (DCP_CONTENT_TYPE);
729 }
730
731 void
732 Film::set_container (Ratio const * c)
733 {
734         _container = c;
735         signal_changed (CONTAINER);
736 }
737
738 void
739 Film::set_resolution (Resolution r)
740 {
741         _resolution = r;
742         signal_changed (RESOLUTION);
743 }
744
745 void
746 Film::set_j2k_bandwidth (int b)
747 {
748         _j2k_bandwidth = b;
749         signal_changed (J2K_BANDWIDTH);
750 }
751
752 void
753 Film::set_isdcf_metadata (ISDCFMetadata m)
754 {
755         _isdcf_metadata = m;
756         signal_changed (ISDCF_METADATA);
757 }
758
759 void
760 Film::set_video_frame_rate (int f)
761 {
762         _video_frame_rate = f;
763         signal_changed (VIDEO_FRAME_RATE);
764 }
765
766 void
767 Film::set_audio_channels (int c)
768 {
769         _audio_channels = c;
770         signal_changed (AUDIO_CHANNELS);
771 }
772
773 void
774 Film::set_three_d (bool t)
775 {
776         _three_d = t;
777         signal_changed (THREE_D);
778
779         if (_three_d && _isdcf_metadata.two_d_version_of_three_d) {
780                 _isdcf_metadata.two_d_version_of_three_d = false;
781                 signal_changed (ISDCF_METADATA);
782         }
783 }
784
785 void
786 Film::set_interop (bool i)
787 {
788         _interop = i;
789         signal_changed (INTEROP);
790 }
791
792 void
793 Film::set_audio_processor (AudioProcessor const * processor)
794 {
795         _audio_processor = processor;
796         signal_changed (AUDIO_PROCESSOR);
797         signal_changed (AUDIO_CHANNELS);
798 }
799
800 void
801 Film::signal_changed (Property p)
802 {
803         _dirty = true;
804
805         switch (p) {
806         case Film::CONTENT:
807                 set_video_frame_rate (_playlist->best_dcp_frame_rate ());
808                 break;
809         case Film::VIDEO_FRAME_RATE:
810         case Film::SEQUENCE_VIDEO:
811                 _playlist->maybe_sequence_video ();
812                 break;
813         default:
814                 break;
815         }
816
817         emit (boost::bind (boost::ref (Changed), p));
818 }
819
820 void
821 Film::set_isdcf_date_today ()
822 {
823         _isdcf_date = boost::gregorian::day_clock::local_day ();
824 }
825
826 boost::filesystem::path
827 Film::j2c_path (int f, Eyes e, bool t) const
828 {
829         boost::filesystem::path p;
830         p /= "j2c";
831         p /= video_identifier ();
832
833         SafeStringStream s;
834         s.width (8);
835         s << setfill('0') << f;
836
837         if (e == EYES_LEFT) {
838                 s << ".L";
839         } else if (e == EYES_RIGHT) {
840                 s << ".R";
841         }
842
843         s << ".j2c";
844
845         if (t) {
846                 s << ".tmp";
847         }
848
849         p /= s.str();
850         return file (p);
851 }
852
853 /** Find all the DCPs in our directory that can be dcp::DCP::read() and return details of their CPLs */
854 vector<CPLSummary>
855 Film::cpls () const
856 {
857         vector<CPLSummary> out;
858
859         boost::filesystem::path const dir = directory ();
860         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator(dir); i != boost::filesystem::directory_iterator(); ++i) {
861                 if (
862                         boost::filesystem::is_directory (*i) &&
863                         i->path().leaf() != "j2c" && i->path().leaf() != "video" && i->path().leaf() != "info" && i->path().leaf() != "analysis"
864                         ) {
865
866                         try {
867                                 dcp::DCP dcp (*i);
868                                 dcp.read ();
869                                 out.push_back (
870                                         CPLSummary (
871                                                 i->path().leaf().string(),
872                                                 dcp.cpls().front()->id(),
873                                                 dcp.cpls().front()->annotation_text(),
874                                                 dcp.cpls().front()->file()
875                                                 )
876                                         );
877                         } catch (...) {
878
879                         }
880                 }
881         }
882
883         return out;
884 }
885
886 void
887 Film::set_signed (bool s)
888 {
889         _signed = s;
890         signal_changed (SIGNED);
891 }
892
893 void
894 Film::set_encrypted (bool e)
895 {
896         _encrypted = e;
897         signal_changed (ENCRYPTED);
898 }
899
900 void
901 Film::set_key (dcp::Key key)
902 {
903         _key = key;
904         signal_changed (KEY);
905 }
906
907 ContentList
908 Film::content () const
909 {
910         return _playlist->content ();
911 }
912
913 void
914 Film::examine_content (shared_ptr<Content> c)
915 {
916         shared_ptr<Job> j (new ExamineContentJob (shared_from_this(), c));
917         JobManager::instance()->add (j);
918 }
919
920 void
921 Film::examine_and_add_content (shared_ptr<Content> c)
922 {
923         if (dynamic_pointer_cast<FFmpegContent> (c) && !_directory.empty ()) {
924                 run_ffprobe (c->path(0), file ("ffprobe.log"), _log);
925         }
926
927         shared_ptr<Job> j (new ExamineContentJob (shared_from_this(), c));
928
929         _job_connections.push_back (
930                 j->Finished.connect (bind (&Film::maybe_add_content, this, weak_ptr<Job> (j), weak_ptr<Content> (c)))
931                 );
932
933         JobManager::instance()->add (j);
934 }
935
936 void
937 Film::maybe_add_content (weak_ptr<Job> j, weak_ptr<Content> c)
938 {
939         shared_ptr<Job> job = j.lock ();
940         if (!job || !job->finished_ok ()) {
941                 return;
942         }
943
944         shared_ptr<Content> content = c.lock ();
945         if (content) {
946                 add_content (content);
947         }
948 }
949
950 void
951 Film::add_content (shared_ptr<Content> c)
952 {
953         /* Add video content after any existing content */
954         if (dynamic_pointer_cast<VideoContent> (c)) {
955                 c->set_position (_playlist->video_end ());
956         }
957
958         _playlist->add (c);
959 }
960
961 void
962 Film::remove_content (shared_ptr<Content> c)
963 {
964         _playlist->remove (c);
965 }
966
967 void
968 Film::move_content_earlier (shared_ptr<Content> c)
969 {
970         _playlist->move_earlier (c);
971 }
972
973 void
974 Film::move_content_later (shared_ptr<Content> c)
975 {
976         _playlist->move_later (c);
977 }
978
979 DCPTime
980 Film::length () const
981 {
982         return _playlist->length ();
983 }
984
985 int
986 Film::best_video_frame_rate () const
987 {
988         return _playlist->best_dcp_frame_rate ();
989 }
990
991 FrameRateChange
992 Film::active_frame_rate_change (DCPTime t) const
993 {
994         return _playlist->active_frame_rate_change (t, video_frame_rate ());
995 }
996
997 void
998 Film::playlist_content_changed (weak_ptr<Content> c, int p, bool frequent)
999 {
1000         _dirty = true;
1001
1002         if (p == VideoContentProperty::VIDEO_FRAME_RATE) {
1003                 set_video_frame_rate (_playlist->best_dcp_frame_rate ());
1004         } else if (p == AudioContentProperty::AUDIO_STREAMS) {
1005                 signal_changed (NAME);
1006         }
1007
1008         emit (boost::bind (boost::ref (ContentChanged), c, p, frequent));
1009 }
1010
1011 void
1012 Film::playlist_changed ()
1013 {
1014         signal_changed (CONTENT);
1015         signal_changed (NAME);
1016 }
1017
1018 int
1019 Film::audio_frame_rate () const
1020 {
1021         BOOST_FOREACH (shared_ptr<Content> i, content ()) {
1022                 shared_ptr<AudioContent> a = dynamic_pointer_cast<AudioContent> (i);
1023                 if (a && a->has_rate_above_48k ()) {
1024                         return 96000;
1025                 }
1026         }
1027
1028         return 48000;
1029 }
1030
1031 void
1032 Film::set_sequence_video (bool s)
1033 {
1034         _sequence_video = s;
1035         _playlist->set_sequence_video (s);
1036         signal_changed (SEQUENCE_VIDEO);
1037 }
1038
1039 /** @return Size of the largest possible image in whatever resolution we are using */
1040 dcp::Size
1041 Film::full_frame () const
1042 {
1043         switch (_resolution) {
1044         case RESOLUTION_2K:
1045                 return dcp::Size (2048, 1080);
1046         case RESOLUTION_4K:
1047                 return dcp::Size (4096, 2160);
1048         }
1049
1050         DCPOMATIC_ASSERT (false);
1051         return dcp::Size ();
1052 }
1053
1054 /** @return Size of the frame */
1055 dcp::Size
1056 Film::frame_size () const
1057 {
1058         return fit_ratio_within (container()->ratio(), full_frame ());
1059 }
1060
1061 dcp::EncryptedKDM
1062 Film::make_kdm (
1063         dcp::Certificate target,
1064         boost::filesystem::path cpl_file,
1065         dcp::LocalTime from,
1066         dcp::LocalTime until,
1067         dcp::Formulation formulation
1068         ) const
1069 {
1070         shared_ptr<const dcp::CPL> cpl (new dcp::CPL (cpl_file));
1071         shared_ptr<const dcp::CertificateChain> signer = Config::instance()->signer_chain ();
1072         if (!signer->valid ()) {
1073                 throw InvalidSignerError ();
1074         }
1075
1076         return dcp::DecryptedKDM (
1077                 cpl, key(), from, until, "DCP-o-matic", cpl->content_title_text(), dcp::LocalTime().as_string()
1078                 ).encrypt (signer, target, formulation);
1079 }
1080
1081 list<dcp::EncryptedKDM>
1082 Film::make_kdms (
1083         list<shared_ptr<Screen> > screens,
1084         boost::filesystem::path dcp,
1085         dcp::LocalTime from,
1086         dcp::LocalTime until,
1087         dcp::Formulation formulation
1088         ) const
1089 {
1090         list<dcp::EncryptedKDM> kdms;
1091
1092         for (list<shared_ptr<Screen> >::iterator i = screens.begin(); i != screens.end(); ++i) {
1093                 if ((*i)->certificate) {
1094                         kdms.push_back (make_kdm ((*i)->certificate.get(), dcp, from, until, formulation));
1095                 }
1096         }
1097
1098         return kdms;
1099 }
1100
1101 /** @return The approximate disk space required to encode a DCP of this film with the
1102  *  current settings, in bytes.
1103  */
1104 uint64_t
1105 Film::required_disk_space () const
1106 {
1107         return uint64_t (j2k_bandwidth() / 8) * length().seconds();
1108 }
1109
1110 /** This method checks the disk that the Film is on and tries to decide whether or not
1111  *  there will be enough space to make a DCP for it.  If so, true is returned; if not,
1112  *  false is returned and required and availabe are filled in with the amount of disk space
1113  *  required and available respectively (in Gb).
1114  *
1115  *  Note: the decision made by this method isn't, of course, 100% reliable.
1116  */
1117 bool
1118 Film::should_be_enough_disk_space (double& required, double& available, bool& can_hard_link) const
1119 {
1120         /* Create a test file and see if we can hard-link it */
1121         boost::filesystem::path test = internal_video_asset_dir() / "test";
1122         boost::filesystem::path test2 = internal_video_asset_dir() / "test2";
1123         can_hard_link = true;
1124         FILE* f = fopen_boost (test, "w");
1125         if (f) {
1126                 fclose (f);
1127                 boost::system::error_code ec;
1128                 boost::filesystem::create_hard_link (test, test2, ec);
1129                 if (ec) {
1130                         can_hard_link = false;
1131                 }
1132                 boost::filesystem::remove (test);
1133                 boost::filesystem::remove (test2);
1134         }
1135
1136         boost::filesystem::space_info s = boost::filesystem::space (internal_video_asset_dir ());
1137         required = double (required_disk_space ()) / 1073741824.0f;
1138         if (!can_hard_link) {
1139                 required *= 2;
1140         }
1141         available = double (s.available) / 1073741824.0f;
1142         return (available - required) > 1;
1143 }
1144
1145 string
1146 Film::subtitle_language () const
1147 {
1148         set<string> languages;
1149
1150         ContentList cl = content ();
1151         BOOST_FOREACH (shared_ptr<Content>& c, cl) {
1152                 shared_ptr<SubtitleContent> sc = dynamic_pointer_cast<SubtitleContent> (c);
1153                 if (sc) {
1154                         languages.insert (sc->subtitle_language ());
1155                 }
1156         }
1157
1158         string all;
1159         BOOST_FOREACH (string s, languages) {
1160                 if (!all.empty ()) {
1161                         all += "/" + s;
1162                 } else {
1163                         all += s;
1164                 }
1165         }
1166
1167         return all;
1168 }
1169
1170 /** Change the gains of the supplied AudioMapping to make it a default
1171  *  for this film.  The defaults are guessed based on what processor (if any)
1172  *  is in use and the number of input channels.
1173  */
1174 void
1175 Film::make_audio_mapping_default (AudioMapping& mapping) const
1176 {
1177         if (audio_processor ()) {
1178                 audio_processor()->make_audio_mapping_default (mapping);
1179         } else {
1180                 mapping.make_zero ();
1181                 if (mapping.input_channels() == 1) {
1182                         /* Mono -> Centre */
1183                         mapping.set (0, static_cast<int> (dcp::CENTRE), 1);
1184                 } else {
1185                         /* 1:1 mapping */
1186                         for (int i = 0; i < min (mapping.input_channels(), mapping.output_channels()); ++i) {
1187                                 mapping.set (i, i, 1);
1188                         }
1189                 }
1190         }
1191 }
1192
1193 /** @return The names of the channels that audio contents' outputs are passed into;
1194  *  this is either the DCP or a AudioProcessor.
1195  */
1196 vector<string>
1197 Film::audio_output_names () const
1198 {
1199         if (audio_processor ()) {
1200                 return audio_processor()->input_names ();
1201         }
1202
1203         vector<string> n;
1204         n.push_back (_("L"));
1205         n.push_back (_("R"));
1206         n.push_back (_("C"));
1207         n.push_back (_("Lfe"));
1208         n.push_back (_("Ls"));
1209         n.push_back (_("Rs"));
1210         n.push_back (_("HI"));
1211         n.push_back (_("VI"));
1212         n.push_back (_("Lc"));
1213         n.push_back (_("Rc"));
1214         n.push_back (_("BsL"));
1215         n.push_back (_("BsR"));
1216
1217         return vector<string> (n.begin(), n.begin() + audio_channels ());
1218 }
1219
1220 void
1221 Film::repeat_content (ContentList c, int n)
1222 {
1223         _playlist->repeat (c, n);
1224 }
1225
1226 void
1227 Film::remove_content (ContentList c)
1228 {
1229         _playlist->remove (c);
1230 }