Use a constexpr and a nullptr.
[dcpomatic.git] / src / lib / film.cc
1 /*
2     Copyright (C) 2012-2021 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21
22 /** @file  src/film.cc
23  *  @brief A representation of some audio, video and subtitle content, and details of
24  *  how they should be presented in a DCP.
25  */
26
27
28 #include "atmos_content.h"
29 #include "audio_content.h"
30 #include "audio_processor.h"
31 #include "change_signaller.h"
32 #include "check_content_change_job.h"
33 #include "cinema.h"
34 #include "compose.hpp"
35 #include "config.h"
36 #include "cross.h"
37 #include "dcp_content.h"
38 #include "dcp_content_type.h"
39 #include "dcp_encoder.h"
40 #include "dcpomatic_log.h"
41 #include "digester.h"
42 #include "environment_info.h"
43 #include "examine_content_job.h"
44 #include "exceptions.h"
45 #include "ffmpeg_content.h"
46 #include "ffmpeg_subtitle_stream.h"
47 #include "file_log.h"
48 #include "film.h"
49 #include "font.h"
50 #include "job.h"
51 #include "job_manager.h"
52 #include "kdm_with_metadata.h"
53 #include "null_log.h"
54 #include "playlist.h"
55 #include "ratio.h"
56 #include "screen.h"
57 #include "text_content.h"
58 #include "transcode_job.h"
59 #include "upload_job.h"
60 #include "util.h"
61 #include "video_content.h"
62 #include <libcxml/cxml.h>
63 #include <dcp/certificate_chain.h>
64 #include <dcp/cpl.h>
65 #include <dcp/decrypted_kdm.h>
66 #include <dcp/local_time.h>
67 #include <dcp/raw_convert.h>
68 #include <dcp/reel_asset.h>
69 #include <dcp/reel_file_asset.h>
70 #include <dcp/util.h>
71 #include <libxml++/libxml++.h>
72 #include <boost/algorithm/string.hpp>
73 #include <boost/filesystem.hpp>
74 #include <boost/regex.hpp>
75 #include <unistd.h>
76 #include <stdexcept>
77 #include <iostream>
78 #include <algorithm>
79 #include <cstdlib>
80 #include <iomanip>
81 #include <set>
82
83 #include "i18n.h"
84
85
86 using std::back_inserter;
87 using std::copy;
88 using std::cout;
89 using std::dynamic_pointer_cast;
90 using std::exception;
91 using std::find;
92 using std::list;
93 using std::make_pair;
94 using std::make_shared;
95 using std::map;
96 using std::max;
97 using std::min;
98 using std::pair;
99 using std::runtime_error;
100 using std::set;
101 using std::setfill;
102 using std::shared_ptr;
103 using std::string;
104 using std::vector;
105 using std::weak_ptr;
106 using boost::optional;
107 using boost::is_any_of;
108 #if BOOST_VERSION >= 106100
109 using namespace boost::placeholders;
110 #endif
111 using dcp::raw_convert;
112 using namespace dcpomatic;
113
114
115 static constexpr char metadata_file[] = "metadata.xml";
116
117
118 /* 5 -> 6
119  * AudioMapping XML changed.
120  * 6 -> 7
121  * Subtitle offset changed to subtitle y offset, and subtitle x offset added.
122  * 7 -> 8
123  * Use <Scale> tag in <VideoContent> rather than <Ratio>.
124  * 8 -> 9
125  * DCI -> ISDCF
126  * 9 -> 10
127  * Subtitle X and Y scale.
128  *
129  * Bumped to 32 for 2.0 branch; some times are expressed in Times rather
130  * than frames now.
131  *
132  * 32 -> 33
133  * Changed <Period> to <Subtitle> in FFmpegSubtitleStream
134  * 33 -> 34
135  * Content only contains audio/subtitle-related tags if those things
136  * are present.
137  * 34 -> 35
138  * VideoFrameType in VideoContent is a string rather than an integer.
139  * 35 -> 36
140  * EffectColour rather than OutlineColour in Subtitle.
141  * 36 -> 37
142  * TextContent can be in a Caption tag, and some of the tag names
143  * have had Subtitle prefixes or suffixes removed.
144  * 37 -> 38
145  * VideoContent scale expressed just as "guess" or "custom"
146  */
147 int const Film::current_state_version = 38;
148
149
150 /** Construct a Film object in a given directory.
151  *
152  *  @param dir Film directory.
153  */
154
155 Film::Film (optional<boost::filesystem::path> dir)
156         : _playlist (new Playlist)
157         , _use_isdcf_name (true)
158         , _dcp_content_type (Config::instance()->default_dcp_content_type ())
159         , _container (Config::instance()->default_container ())
160         , _resolution (Resolution::TWO_K)
161         , _encrypted (false)
162         , _context_id (dcp::make_uuid ())
163         , _j2k_bandwidth (Config::instance()->default_j2k_bandwidth ())
164         , _video_frame_rate (24)
165         , _audio_channels (Config::instance()->default_dcp_audio_channels ())
166         , _three_d (false)
167         , _sequence (true)
168         , _interop (Config::instance()->default_interop ())
169         , _audio_processor (0)
170         , _reel_type (ReelType::SINGLE)
171         , _reel_length (2000000000)
172         , _reencode_j2k (false)
173         , _user_explicit_video_frame_rate (false)
174         , _user_explicit_container (false)
175         , _user_explicit_resolution (false)
176         , _name_language (dcp::LanguageTag("en-US"))
177         , _version_number (1)
178         , _status (dcp::Status::FINAL)
179         , _state_version (current_state_version)
180         , _dirty (false)
181         , _tolerant (false)
182 {
183         set_isdcf_date_today ();
184
185         auto metadata = Config::instance()->default_metadata();
186         if (metadata.find("chain") != metadata.end()) {
187                 _chain = metadata["chain"];
188         }
189         if (metadata.find("distributor") != metadata.end()) {
190                 _distributor = metadata["distributor"];
191         }
192         if (metadata.find("facility") != metadata.end()) {
193                 _facility = metadata["facility"];
194         }
195         if (metadata.find("studio") != metadata.end()) {
196                 _studio = metadata["studio"];
197         }
198
199         _playlist_change_connection = _playlist->Change.connect (bind (&Film::playlist_change, this, _1));
200         _playlist_order_changed_connection = _playlist->OrderChange.connect (bind (&Film::playlist_order_changed, this));
201         _playlist_content_change_connection = _playlist->ContentChange.connect (bind (&Film::playlist_content_change, this, _1, _2, _3, _4));
202         _playlist_length_change_connection = _playlist->LengthChange.connect (bind(&Film::playlist_length_change, this));
203
204         if (dir) {
205                 /* Make state.directory a complete path without ..s (where possible)
206                    (Code swiped from Adam Bowen on stackoverflow)
207                    XXX: couldn't/shouldn't this just be boost::filesystem::canonical?
208                 */
209
210                 boost::filesystem::path p (boost::filesystem::system_complete (dir.get()));
211                 boost::filesystem::path result;
212                 for (auto i: p) {
213                         if (i == "..") {
214                                 boost::system::error_code ec;
215                                 if (boost::filesystem::is_symlink(result, ec) || result.filename() == "..") {
216                                         result /= i;
217                                 } else {
218                                         result = result.parent_path ();
219                                 }
220                         } else if (i != ".") {
221                                 result /= i;
222                         }
223                 }
224
225                 set_directory (result.make_preferred ());
226         }
227
228         if (_directory) {
229                 _log = make_shared<FileLog>(file("log"));
230         } else {
231                 _log = make_shared<NullLog>();
232         }
233
234         _playlist->set_sequence (_sequence);
235 }
236
237 Film::~Film ()
238 {
239         for (auto& i: _job_connections) {
240                 i.disconnect ();
241         }
242
243         for (auto& i: _audio_analysis_connections) {
244                 i.disconnect ();
245         }
246 }
247
248 string
249 Film::video_identifier () const
250 {
251         DCPOMATIC_ASSERT (container ());
252
253         string s = container()->id()
254                 + "_" + resolution_to_string (_resolution)
255                 + "_" + _playlist->video_identifier()
256                 + "_" + raw_convert<string>(_video_frame_rate)
257                 + "_" + raw_convert<string>(j2k_bandwidth());
258
259         if (encrypted ()) {
260                 /* This is insecure but hey, the key is in plaintext in metadata.xml */
261                 s += "_E" + _key.hex();
262         } else {
263                 s += "_P";
264         }
265
266         if (_interop) {
267                 s += "_I";
268         } else {
269                 s += "_S";
270         }
271
272         if (_three_d) {
273                 s += "_3D";
274         }
275
276         if (_reencode_j2k) {
277                 s += "_R";
278         }
279
280         return s;
281 }
282
283 /** @return The file to write video frame info to */
284 boost::filesystem::path
285 Film::info_file (DCPTimePeriod period) const
286 {
287         boost::filesystem::path p;
288         p /= "info";
289         p /= video_identifier () + "_" + raw_convert<string> (period.from.get()) + "_" + raw_convert<string> (period.to.get());
290         return file (p);
291 }
292
293 boost::filesystem::path
294 Film::internal_video_asset_dir () const
295 {
296         return dir ("video");
297 }
298
299 boost::filesystem::path
300 Film::internal_video_asset_filename (DCPTimePeriod p) const
301 {
302         return video_identifier() + "_" + raw_convert<string> (p.from.get()) + "_" + raw_convert<string> (p.to.get()) + ".mxf";
303 }
304
305 boost::filesystem::path
306 Film::audio_analysis_path (shared_ptr<const Playlist> playlist) const
307 {
308         auto p = dir ("analysis");
309
310         Digester digester;
311         for (auto i: playlist->content()) {
312                 if (!i->audio) {
313                         continue;
314                 }
315
316                 digester.add (i->digest());
317                 digester.add (i->audio->mapping().digest());
318                 if (playlist->content().size() != 1) {
319                         /* Analyses should be considered equal regardless of gain
320                            if they were made from just one piece of content.  This
321                            is because we can fake any gain change in a single-content
322                            analysis at the plotting stage rather than having to
323                            recompute it.
324                         */
325                         digester.add (i->audio->gain());
326
327                         /* Likewise we only care about position if we're looking at a
328                          * whole-project view.
329                          */
330                         digester.add (i->position().get());
331                         digester.add (i->trim_start().get());
332                         digester.add (i->trim_end().get());
333                 }
334         }
335
336         if (audio_processor ()) {
337                 digester.add (audio_processor()->id ());
338         }
339
340         digester.add (audio_channels());
341
342         p /= digester.get ();
343         return p;
344 }
345
346
347 boost::filesystem::path
348 Film::subtitle_analysis_path (shared_ptr<const Content> content) const
349 {
350         auto p = dir ("analysis");
351
352         Digester digester;
353         digester.add (content->digest());
354
355         if (!content->text.empty()) {
356                 auto tc = content->text.front();
357                 digester.add (tc->x_scale());
358                 digester.add (tc->y_scale());
359                 for (auto i: tc->fonts()) {
360                         digester.add (i->id());
361                 }
362                 if (tc->effect()) {
363                         digester.add (tc->effect().get());
364                 }
365                 digester.add (tc->line_spacing());
366                 digester.add (tc->outline_width());
367         }
368
369         auto fc = dynamic_pointer_cast<const FFmpegContent>(content);
370         if (fc) {
371                 digester.add (fc->subtitle_stream()->identifier());
372         }
373
374         p /= digester.get ();
375         return p;
376 }
377
378
379 /** Add suitable Jobs to the JobManager to create a DCP for this Film.
380  *  @param gui true if this is being called from a GUI tool.
381  *  @param check true to check the content in the project for changes before making the DCP.
382  */
383 void
384 Film::make_dcp (bool gui, bool check)
385 {
386         if (dcp_name().find ("/") != string::npos) {
387                 throw BadSettingError (_("name"), _("Cannot contain slashes"));
388         }
389
390         if (container() == nullptr) {
391                 throw MissingSettingError (_("container"));
392         }
393
394         if (content().empty()) {
395                 throw runtime_error (_("You must add some content to the DCP before creating it"));
396         }
397
398         if (length() == DCPTime()) {
399                 throw runtime_error (_("The DCP is empty, perhaps because all the content has zero length."));
400         }
401
402         if (dcp_content_type() == nullptr) {
403                 throw MissingSettingError (_("content type"));
404         }
405
406         if (name().empty()) {
407                 set_name ("DCP");
408         }
409
410         for (auto i: content ()) {
411                 if (!i->paths_valid()) {
412                         throw runtime_error (_("some of your content is missing"));
413                 }
414                 auto dcp = dynamic_pointer_cast<const DCPContent>(i);
415                 if (dcp && dcp->needs_kdm()) {
416                         throw runtime_error (_("Some of your content needs a KDM"));
417                 }
418                 if (dcp && dcp->needs_assets()) {
419                         throw runtime_error (_("Some of your content needs an OV"));
420                 }
421         }
422
423         set_isdcf_date_today ();
424
425         for (auto i: environment_info ()) {
426                 LOG_GENERAL_NC (i);
427         }
428
429         for (auto i: content ()) {
430                 LOG_GENERAL ("Content: %1", i->technical_summary());
431         }
432         LOG_GENERAL ("DCP video rate %1 fps", video_frame_rate());
433         if (Config::instance()->only_servers_encode ()) {
434                 LOG_GENERAL_NC ("0 threads: ONLY SERVERS SET TO ENCODE");
435         } else {
436                 LOG_GENERAL ("%1 threads", Config::instance()->master_encoding_threads());
437         }
438         LOG_GENERAL ("J2K bandwidth %1", j2k_bandwidth());
439
440         auto tj = make_shared<TranscodeJob>(shared_from_this());
441         tj->set_encoder (make_shared<DCPEncoder>(shared_from_this(), tj));
442         if (check) {
443                 auto cc = make_shared<CheckContentChangeJob>(shared_from_this(), tj, gui);
444                 JobManager::instance()->add (cc);
445         } else {
446                 JobManager::instance()->add (tj);
447         }
448 }
449
450 /** Start a job to send our DCP to the configured TMS */
451 void
452 Film::send_dcp_to_tms ()
453 {
454         JobManager::instance()->add(make_shared<UploadJob>(shared_from_this()));
455 }
456
457 shared_ptr<xmlpp::Document>
458 Film::metadata (bool with_content_paths) const
459 {
460         auto doc = make_shared<xmlpp::Document>();
461         auto root = doc->create_root_node ("Metadata");
462
463         root->add_child("Version")->add_child_text (raw_convert<string> (current_state_version));
464         root->add_child("Name")->add_child_text (_name);
465         root->add_child("UseISDCFName")->add_child_text (_use_isdcf_name ? "1" : "0");
466
467         if (_dcp_content_type) {
468                 root->add_child("DCPContentType")->add_child_text (_dcp_content_type->isdcf_name ());
469         }
470
471         if (_container) {
472                 root->add_child("Container")->add_child_text (_container->id ());
473         }
474
475         root->add_child("Resolution")->add_child_text (resolution_to_string (_resolution));
476         root->add_child("J2KBandwidth")->add_child_text (raw_convert<string> (_j2k_bandwidth));
477         root->add_child("VideoFrameRate")->add_child_text (raw_convert<string> (_video_frame_rate));
478         root->add_child("ISDCFDate")->add_child_text (boost::gregorian::to_iso_string (_isdcf_date));
479         root->add_child("AudioChannels")->add_child_text (raw_convert<string> (_audio_channels));
480         root->add_child("ThreeD")->add_child_text (_three_d ? "1" : "0");
481         root->add_child("Sequence")->add_child_text (_sequence ? "1" : "0");
482         root->add_child("Interop")->add_child_text (_interop ? "1" : "0");
483         root->add_child("Encrypted")->add_child_text (_encrypted ? "1" : "0");
484         root->add_child("Key")->add_child_text (_key.hex ());
485         root->add_child("ContextID")->add_child_text (_context_id);
486         if (_audio_processor) {
487                 root->add_child("AudioProcessor")->add_child_text (_audio_processor->id ());
488         }
489         root->add_child("ReelType")->add_child_text (raw_convert<string> (static_cast<int> (_reel_type)));
490         root->add_child("ReelLength")->add_child_text (raw_convert<string> (_reel_length));
491         root->add_child("ReencodeJ2K")->add_child_text (_reencode_j2k ? "1" : "0");
492         root->add_child("UserExplicitVideoFrameRate")->add_child_text(_user_explicit_video_frame_rate ? "1" : "0");
493         for (map<dcp::Marker, DCPTime>::const_iterator i = _markers.begin(); i != _markers.end(); ++i) {
494                 auto m = root->add_child("Marker");
495                 m->set_attribute("Type", dcp::marker_to_string(i->first));
496                 m->add_child_text(raw_convert<string>(i->second.get()));
497         }
498         for (auto i: _ratings) {
499                 i.as_xml (root->add_child("Rating"));
500         }
501         for (auto i: _content_versions) {
502                 root->add_child("ContentVersion")->add_child_text(i);
503         }
504         root->add_child("NameLanguage")->add_child_text(_name_language.to_string());
505         if (_release_territory) {
506                 root->add_child("ReleaseTerritory")->add_child_text(_release_territory->subtag());
507         }
508         if (_sign_language_video_language) {
509                 root->add_child("SignLanguageVideoLanguage")->add_child_text(_sign_language_video_language->to_string());
510         }
511         root->add_child("VersionNumber")->add_child_text(raw_convert<string>(_version_number));
512         root->add_child("Status")->add_child_text(dcp::status_to_string(_status));
513         if (_chain) {
514                 root->add_child("Chain")->add_child_text(*_chain);
515         }
516         if (_distributor) {
517                 root->add_child("Distributor")->add_child_text(*_distributor);
518         }
519         if (_facility) {
520                 root->add_child("Facility")->add_child_text(*_facility);
521         }
522         if (_studio) {
523                 root->add_child("Studio")->add_child_text(*_studio);
524         }
525         root->add_child("TempVersion")->add_child_text(_temp_version ? "1" : "0");
526         root->add_child("PreRelease")->add_child_text(_pre_release ? "1" : "0");
527         root->add_child("RedBand")->add_child_text(_red_band ? "1" : "0");
528         root->add_child("TwoDVersionOfThreeD")->add_child_text(_two_d_version_of_three_d ? "1" : "0");
529         if (_luminance) {
530                 root->add_child("LuminanceValue")->add_child_text(raw_convert<string>(_luminance->value()));
531                 root->add_child("LuminanceUnit")->add_child_text(dcp::Luminance::unit_to_string(_luminance->unit()));
532         }
533         root->add_child("UserExplicitContainer")->add_child_text(_user_explicit_container ? "1" : "0");
534         root->add_child("UserExplicitResolution")->add_child_text(_user_explicit_resolution ? "1" : "0");
535         if (_audio_language) {
536                 root->add_child("AudioLanguage")->add_child_text(_audio_language->to_string());
537         }
538         _playlist->as_xml (root->add_child ("Playlist"), with_content_paths);
539
540         return doc;
541 }
542
543 void
544 Film::write_metadata (boost::filesystem::path path) const
545 {
546         metadata()->write_to_file_formatted(path.string());
547 }
548
549 /** Write state to our `metadata' file */
550 void
551 Film::write_metadata () const
552 {
553         DCPOMATIC_ASSERT (directory());
554         boost::filesystem::create_directories (directory().get());
555         metadata()->write_to_file_formatted(file(metadata_file).string());
556         _dirty = false;
557 }
558
559 /** Write a template from this film */
560 void
561 Film::write_template (boost::filesystem::path path) const
562 {
563         boost::filesystem::create_directories (path.parent_path());
564         shared_ptr<xmlpp::Document> doc = metadata (false);
565         metadata(false)->write_to_file_formatted(path.string());
566 }
567
568 /** Read state from our metadata file.
569  *  @return Notes about things that the user should know about, or empty.
570  */
571 list<string>
572 Film::read_metadata (optional<boost::filesystem::path> path)
573 {
574         if (!path) {
575                 if (boost::filesystem::exists (file ("metadata")) && !boost::filesystem::exists (file (metadata_file))) {
576                         throw runtime_error (_("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!"));
577                 }
578
579                 path = file (metadata_file);
580         }
581
582         if (!boost::filesystem::exists(*path)) {
583                 throw FileNotFoundError(*path);
584         }
585
586         cxml::Document f ("Metadata");
587         f.read_file (path.get ());
588
589         _state_version = f.number_child<int> ("Version");
590         if (_state_version > current_state_version) {
591                 throw runtime_error (_("This film was created with a newer version of DCP-o-matic, and it cannot be loaded into this version.  Sorry!"));
592         } else if (_state_version < current_state_version) {
593                 /* This is an older version; save a copy (if we haven't already) */
594                 auto const older = path->parent_path() / String::compose("metadata.%1.xml", _state_version);
595                 if (!boost::filesystem::is_regular_file(older)) {
596                         try {
597                                 boost::filesystem::copy_file(*path, older);
598                         } catch (...) {
599                                 /* Never mind; at least we tried */
600                         }
601                 }
602         }
603
604         _name = f.string_child ("Name");
605         if (_state_version >= 9) {
606                 _use_isdcf_name = f.bool_child ("UseISDCFName");
607                 _isdcf_date = boost::gregorian::from_undelimited_string (f.string_child ("ISDCFDate"));
608         } else {
609                 _use_isdcf_name = f.bool_child ("UseDCIName");
610                 _isdcf_date = boost::gregorian::from_undelimited_string (f.string_child ("DCIDate"));
611         }
612
613
614         {
615                 auto c = f.optional_string_child("DCPContentType");
616                 if (c) {
617                         _dcp_content_type = DCPContentType::from_isdcf_name (c.get ());
618                 }
619         }
620
621         {
622                 auto c = f.optional_string_child("Container");
623                 if (c) {
624                         _container = Ratio::from_id (c.get ());
625                 }
626         }
627
628         _resolution = string_to_resolution (f.string_child ("Resolution"));
629         _j2k_bandwidth = f.number_child<int> ("J2KBandwidth");
630         _video_frame_rate = f.number_child<int> ("VideoFrameRate");
631         _encrypted = f.bool_child ("Encrypted");
632         _audio_channels = f.number_child<int> ("AudioChannels");
633         /* We used to allow odd numbers (and zero) channels, but it's just not worth
634            the pain.
635         */
636         if (_audio_channels == 0) {
637                 _audio_channels = 2;
638         } else if ((_audio_channels % 2) == 1) {
639                 _audio_channels++;
640         }
641
642         if (f.optional_bool_child("SequenceVideo")) {
643                 _sequence = f.bool_child("SequenceVideo");
644         } else {
645                 _sequence = f.bool_child("Sequence");
646         }
647
648         _three_d = f.bool_child ("ThreeD");
649         _interop = f.bool_child ("Interop");
650         _key = dcp::Key (f.string_child ("Key"));
651         _context_id = f.optional_string_child("ContextID").get_value_or (dcp::make_uuid ());
652
653         if (f.optional_string_child ("AudioProcessor")) {
654                 _audio_processor = AudioProcessor::from_id (f.string_child ("AudioProcessor"));
655         } else {
656                 _audio_processor = 0;
657         }
658
659         if (_audio_processor && !Config::instance()->show_experimental_audio_processors()) {
660                 auto ap = AudioProcessor::visible();
661                 if (find(ap.begin(), ap.end(), _audio_processor) == ap.end()) {
662                         Config::instance()->set_show_experimental_audio_processors(true);
663                 }
664         }
665
666         _reel_type = static_cast<ReelType> (f.optional_number_child<int>("ReelType").get_value_or (static_cast<int>(ReelType::SINGLE)));
667         _reel_length = f.optional_number_child<int64_t>("ReelLength").get_value_or (2000000000);
668         _reencode_j2k = f.optional_bool_child("ReencodeJ2K").get_value_or(false);
669         _user_explicit_video_frame_rate = f.optional_bool_child("UserExplicitVideoFrameRate").get_value_or(false);
670
671         for (auto i: f.node_children("Marker")) {
672                 _markers[dcp::marker_from_string(i->string_attribute("Type"))] = DCPTime(dcp::raw_convert<DCPTime::Type>(i->content()));
673         }
674
675         for (auto i: f.node_children("Rating")) {
676                 _ratings.push_back (dcp::Rating(i));
677         }
678
679         for (auto i: f.node_children("ContentVersion")) {
680                 _content_versions.push_back (i->content());
681         }
682
683         auto name_language = f.optional_string_child("NameLanguage");
684         if (name_language) {
685                 _name_language = dcp::LanguageTag (*name_language);
686         }
687         auto release_territory = f.optional_string_child("ReleaseTerritory");
688         if (release_territory) {
689                 _release_territory = dcp::LanguageTag::RegionSubtag (*release_territory);
690         }
691
692         auto sign_language_video_language = f.optional_string_child("SignLanguageVideoLanguage");
693         if (sign_language_video_language) {
694                 _sign_language_video_language = dcp::LanguageTag(*sign_language_video_language);
695         }
696
697         _version_number = f.optional_number_child<int>("VersionNumber").get_value_or(0);
698
699         auto status = f.optional_string_child("Status");
700         if (status) {
701                 _status = dcp::string_to_status (*status);
702         }
703
704         _chain = f.optional_string_child("Chain");
705         _distributor = f.optional_string_child("Distributor");
706         _facility = f.optional_string_child("Facility");
707         _studio = f.optional_string_child("Studio");
708         _temp_version = f.optional_bool_child("TempVersion").get_value_or(false);
709         _pre_release = f.optional_bool_child("PreRelease").get_value_or(false);
710         _red_band = f.optional_bool_child("RedBand").get_value_or(false);
711         _two_d_version_of_three_d = f.optional_bool_child("TwoDVersionOfThreeD").get_value_or(false);
712
713         auto value = f.optional_number_child<float>("LuminanceValue");
714         auto unit = f.optional_string_child("LuminanceUnit");
715         if (value && unit) {
716                 _luminance = dcp::Luminance (*value, dcp::Luminance::string_to_unit(*unit));
717         }
718
719         /* Disable guessing for files made in previous DCP-o-matic versions */
720         _user_explicit_container = f.optional_bool_child("UserExplicitContainer").get_value_or(true);
721         _user_explicit_resolution = f.optional_bool_child("UserExplicitResolution").get_value_or(true);
722
723         auto audio_language = f.optional_string_child("AudioLanguage");
724         if (audio_language) {
725                 _audio_language = dcp::LanguageTag(*audio_language);
726         }
727
728         list<string> notes;
729         _playlist->set_from_xml (shared_from_this(), f.node_child ("Playlist"), _state_version, notes);
730
731         /* Write backtraces to this film's directory, until another film is loaded */
732         if (_directory) {
733                 set_backtrace_file (file ("backtrace.txt"));
734         }
735
736         _dirty = false;
737         return notes;
738 }
739
740 /** Given a directory name, return its full path within the Film's directory.
741  *  @param d directory name within the Film's directory.
742  *  @param create true to create the directory (and its parents) if they do not exist.
743  */
744 boost::filesystem::path
745 Film::dir (boost::filesystem::path d, bool create) const
746 {
747         DCPOMATIC_ASSERT (_directory);
748
749         boost::filesystem::path p;
750         p /= _directory.get();
751         p /= d;
752
753         if (create) {
754                 boost::filesystem::create_directories (p);
755         }
756
757         return p;
758 }
759
760 /** Given a file or directory name, return its full path within the Film's directory.
761  *  Any required parent directories will be created.
762  */
763 boost::filesystem::path
764 Film::file (boost::filesystem::path f) const
765 {
766         DCPOMATIC_ASSERT (_directory);
767
768         boost::filesystem::path p;
769         p /= _directory.get();
770         p /= f;
771
772         boost::filesystem::create_directories (p.parent_path ());
773
774         return p;
775 }
776
777 list<int>
778 Film::mapped_audio_channels () const
779 {
780         list<int> mapped;
781
782         if (audio_processor ()) {
783                 /* Processors are mapped 1:1 to DCP outputs so we can work out mappings from there */
784                 for (int i = 0; i < audio_processor()->out_channels(); ++i) {
785                         mapped.push_back (i);
786                 }
787         } else {
788                 for (auto i: content()) {
789                         if (i->audio) {
790                                 auto c = i->audio->mapping().mapped_output_channels();
791                                 copy (c.begin(), c.end(), back_inserter(mapped));
792                         }
793                 }
794
795                 mapped.sort ();
796                 mapped.unique ();
797         }
798
799         return mapped;
800 }
801
802
803 pair<optional<dcp::LanguageTag>, vector<dcp::LanguageTag>>
804 Film::subtitle_languages () const
805 {
806         pair<optional<dcp::LanguageTag>, vector<dcp::LanguageTag>> result;
807         for (auto i: content()) {
808                 for (auto j: i->text) {
809                         if (j->use() && j->type() == TextType::OPEN_SUBTITLE && j->language()) {
810                                 if (j->language_is_additional()) {
811                                         result.second.push_back (j->language().get());
812                                 } else {
813                                         result.first = j->language().get();
814                                 }
815                         }
816                 }
817                 if (i->video && i->video->burnt_subtitle_language()) {
818                         result.first = i->video->burnt_subtitle_language();
819                 }
820         }
821
822         std::sort (result.second.begin(), result.second.end());
823         auto last = std::unique (result.second.begin(), result.second.end());
824         result.second.erase (last, result.second.end());
825         return result;
826 }
827
828
829 /** @return a ISDCF-compliant name for a DCP of this film */
830 string
831 Film::isdcf_name (bool if_created_now) const
832 {
833         string d;
834
835         auto raw_name = name ();
836
837         /* Split the raw name up into words */
838         vector<string> words;
839         split (words, raw_name, is_any_of (" _-"));
840
841         string fixed_name;
842
843         /* Add each word to fixed_name */
844         for (auto i: words) {
845                 string w = i;
846
847                 /* First letter is always capitalised */
848                 w[0] = toupper (w[0]);
849
850                 /* Count caps in w */
851                 size_t caps = 0;
852                 for (size_t j = 0; j < w.size(); ++j) {
853                         if (isupper (w[j])) {
854                                 ++caps;
855                         }
856                 }
857
858                 /* If w is all caps make the rest of it lower case, otherwise
859                    leave it alone.
860                 */
861                 if (caps == w.size ()) {
862                         for (size_t j = 1; j < w.size(); ++j) {
863                                 w[j] = tolower (w[j]);
864                         }
865                 }
866
867                 for (size_t j = 0; j < w.size(); ++j) {
868                         fixed_name += w[j];
869                 }
870         }
871
872         if (fixed_name.length() > 14) {
873                 fixed_name = fixed_name.substr (0, 14);
874         }
875
876         d += fixed_name;
877
878         if (dcp_content_type()) {
879                 d += "_" + dcp_content_type()->isdcf_name();
880                 string version = "1";
881                 if (_interop) {
882                         if (!_content_versions.empty()) {
883                                 auto cv = _content_versions[0];
884                                 if (!cv.empty() && std::all_of(cv.begin(), cv.end(), isdigit)) {
885                                         version = cv;
886                                 }
887                         }
888                 } else {
889                         version = dcp::raw_convert<string>(_version_number);
890                 }
891                 d += "-" + version;
892         }
893
894         if (_temp_version) {
895                 d += "-Temp";
896         }
897
898         if (_pre_release) {
899                 d += "-Pre";
900         }
901
902         if (_red_band) {
903                 d += "-RedBand";
904         }
905
906         if (_chain && !_chain->empty()) {
907                 d += "-" + *_chain;
908         }
909
910         if (three_d ()) {
911                 d += "-3D";
912         }
913
914         if (_two_d_version_of_three_d) {
915                 d += "-2D";
916         }
917
918         if (_luminance) {
919                 auto fl = _luminance->value_in_foot_lamberts();
920                 char buffer[64];
921                 snprintf (buffer, sizeof(buffer), "%.1f", fl);
922                 d += String::compose("-%1fl", buffer);
923         }
924
925         if (video_frame_rate() != 24) {
926                 d += "-" + raw_convert<string>(video_frame_rate());
927         }
928
929         if (container()) {
930                 d += "_" + container()->isdcf_name();
931         }
932
933         /* XXX: this uses the first bit of content only */
934
935         /* Interior aspect ratio.  The standard says we don't do this for trailers, for some strange reason */
936         if (dcp_content_type() && dcp_content_type()->libdcp_kind() != dcp::ContentKind::TRAILER) {
937                 auto cl = content();
938                 auto first_video = std::find_if(cl.begin(), cl.end(), [](shared_ptr<Content> c) { return static_cast<bool>(c->video); });
939                 if (first_video != cl.end()) {
940                         auto first_ratio = lrintf((*first_video)->video->scaled_size(frame_size()).ratio() * 100);
941                         auto container_ratio = lrintf(container()->ratio() * 100);
942                         if (first_ratio != container_ratio) {
943                                 d += "-" + dcp::raw_convert<string>(first_ratio);
944                         }
945                 }
946         }
947
948         auto audio_language = (_audio_language && _audio_language->language()) ? _audio_language->language()->subtag() : "XX";
949
950         d += "_" + to_upper (audio_language);
951
952         /* I'm not clear on the precise details of the convention for CCAP labelling;
953            for now I'm just appending -CCAP if we have any closed captions.
954         */
955
956         auto burnt_in = true;
957         auto ccap = false;
958         for (auto i: content()) {
959                 for (auto j: i->text) {
960                         if (j->type() == TextType::OPEN_SUBTITLE && j->use() && !j->burn()) {
961                                 burnt_in = false;
962                         } else if (j->type() == TextType::CLOSED_CAPTION && j->use()) {
963                                 ccap = true;
964                         }
965                 }
966         }
967
968         auto sub_langs = subtitle_languages();
969         if (sub_langs.first && sub_langs.first->language()) {
970                 auto lang = sub_langs.first->language()->subtag();
971                 if (burnt_in) {
972                         transform (lang.begin(), lang.end(), lang.begin(), ::tolower);
973                 } else {
974                         lang = to_upper (lang);
975                 }
976
977                 d += "-" + lang;
978                 if (ccap) {
979                         d += "-CCAP";
980                 }
981         } else {
982                 /* No subtitles */
983                 d += "-XX";
984         }
985
986         if (_release_territory) {
987                 auto territory = _release_territory->subtag();
988                 d += "_" + to_upper (territory);
989                 if (_ratings.empty ()) {
990                         d += "-NR";
991                 } else {
992                         d += "-" + _ratings[0].label;
993                 }
994         }
995
996         /* Count mapped audio channels */
997
998         auto mapped = mapped_audio_channels ();
999
1000         auto ch = audio_channel_types (mapped, audio_channels());
1001         if (!ch.first && !ch.second) {
1002                 d += "_MOS";
1003         } else if (ch.first) {
1004                 d += String::compose("_%1%2", ch.first, ch.second);
1005         }
1006
1007         if (audio_channels() > static_cast<int>(dcp::Channel::HI) && find(mapped.begin(), mapped.end(), static_cast<int>(dcp::Channel::HI)) != mapped.end()) {
1008                 d += "-HI";
1009         }
1010         if (audio_channels() > static_cast<int>(dcp::Channel::VI) && find(mapped.begin(), mapped.end(), static_cast<int>(dcp::Channel::VI)) != mapped.end()) {
1011                 d += "-VI";
1012         }
1013
1014         d += "_" + resolution_to_string (_resolution);
1015
1016         if (_studio && _studio->length() >= 2) {
1017                 d += "_" + to_upper (_studio->substr(0, 4));
1018         }
1019
1020         if (if_created_now) {
1021                 d += "_" + boost::gregorian::to_iso_string (boost::gregorian::day_clock::local_day ());
1022         } else {
1023                 d += "_" + boost::gregorian::to_iso_string (_isdcf_date);
1024         }
1025
1026         if (_facility && _facility->length() >= 3) {
1027                 d += "_" + to_upper(_facility->substr(0, 3));
1028         }
1029
1030         if (_interop) {
1031                 d += "_IOP";
1032         } else {
1033                 d += "_SMPTE";
1034         }
1035
1036         if (three_d ()) {
1037                 d += "-3D";
1038         }
1039
1040         auto vf = false;
1041         for (auto i: content()) {
1042                 auto dc = dynamic_pointer_cast<const DCPContent>(i);
1043                 if (!dc) {
1044                         continue;
1045                 }
1046
1047                 bool any_text = false;
1048                 for (int i = 0; i < static_cast<int>(TextType::COUNT); ++i) {
1049                         if (dc->reference_text(static_cast<TextType>(i))) {
1050                                 any_text = true;
1051                         }
1052                 }
1053                 if (dc->reference_video() || dc->reference_audio() || any_text) {
1054                         vf = true;
1055                 }
1056         }
1057
1058         if (vf) {
1059                 d += "_VF";
1060         } else {
1061                 d += "_OV";
1062         }
1063
1064         return d;
1065 }
1066
1067 /** @return name to give the DCP */
1068 string
1069 Film::dcp_name (bool if_created_now) const
1070 {
1071         string unfiltered;
1072         if (use_isdcf_name()) {
1073                 return careful_string_filter (isdcf_name (if_created_now));
1074         }
1075
1076         return careful_string_filter (name ());
1077 }
1078
1079 void
1080 Film::set_directory (boost::filesystem::path d)
1081 {
1082         _directory = d;
1083         _dirty = true;
1084 }
1085
1086 void
1087 Film::set_name (string n)
1088 {
1089         FilmChangeSignaller ch (this, Property::NAME);
1090         _name = n;
1091 }
1092
1093 void
1094 Film::set_use_isdcf_name (bool u)
1095 {
1096         FilmChangeSignaller ch (this, Property::USE_ISDCF_NAME);
1097         _use_isdcf_name = u;
1098 }
1099
1100 void
1101 Film::set_dcp_content_type (DCPContentType const * t)
1102 {
1103         FilmChangeSignaller ch (this, Property::DCP_CONTENT_TYPE);
1104         _dcp_content_type = t;
1105 }
1106
1107
1108 /** @param explicit_user true if this is being set because of
1109  *  a direct user request, false if it is being done because
1110  *  DCP-o-matic is guessing the best container to use.
1111  */
1112 void
1113 Film::set_container (Ratio const * c, bool explicit_user)
1114 {
1115         FilmChangeSignaller ch (this, Property::CONTAINER);
1116         _container = c;
1117
1118         if (explicit_user) {
1119                 _user_explicit_container = true;
1120         }
1121 }
1122
1123
1124 /** @param explicit_user true if this is being set because of
1125  *  a direct user request, false if it is being done because
1126  *  DCP-o-matic is guessing the best resolution to use.
1127  */
1128 void
1129 Film::set_resolution (Resolution r, bool explicit_user)
1130 {
1131         FilmChangeSignaller ch (this, Property::RESOLUTION);
1132         _resolution = r;
1133
1134         if (explicit_user) {
1135                 _user_explicit_resolution = true;
1136         }
1137 }
1138
1139
1140 void
1141 Film::set_j2k_bandwidth (int b)
1142 {
1143         FilmChangeSignaller ch (this, Property::J2K_BANDWIDTH);
1144         _j2k_bandwidth = b;
1145 }
1146
1147 /** @param f New frame rate.
1148  *  @param user_explicit true if this comes from a direct user instruction, false if it is from
1149  *  DCP-o-matic being helpful.
1150  */
1151 void
1152 Film::set_video_frame_rate (int f, bool user_explicit)
1153 {
1154         FilmChangeSignaller ch (this, Property::VIDEO_FRAME_RATE);
1155         _video_frame_rate = f;
1156         if (user_explicit) {
1157                 _user_explicit_video_frame_rate = true;
1158         }
1159 }
1160
1161 void
1162 Film::set_audio_channels (int c)
1163 {
1164         FilmChangeSignaller ch (this, Property::AUDIO_CHANNELS);
1165         _audio_channels = c;
1166 }
1167
1168 void
1169 Film::set_three_d (bool t)
1170 {
1171         FilmChangeSignaller ch (this, Property::THREE_D);
1172         _three_d = t;
1173
1174         if (_three_d && _two_d_version_of_three_d) {
1175                 set_two_d_version_of_three_d (false);
1176         }
1177 }
1178
1179 void
1180 Film::set_interop (bool i)
1181 {
1182         FilmChangeSignaller ch (this, Property::INTEROP);
1183         _interop = i;
1184 }
1185
1186 void
1187 Film::set_audio_processor (AudioProcessor const * processor)
1188 {
1189         FilmChangeSignaller ch1 (this, Property::AUDIO_PROCESSOR);
1190         FilmChangeSignaller ch2 (this, Property::AUDIO_CHANNELS);
1191         _audio_processor = processor;
1192 }
1193
1194 void
1195 Film::set_reel_type (ReelType t)
1196 {
1197         FilmChangeSignaller ch (this, Property::REEL_TYPE);
1198         _reel_type = t;
1199 }
1200
1201 /** @param r Desired reel length in bytes */
1202 void
1203 Film::set_reel_length (int64_t r)
1204 {
1205         FilmChangeSignaller ch (this, Property::REEL_LENGTH);
1206         _reel_length = r;
1207 }
1208
1209 void
1210 Film::set_reencode_j2k (bool r)
1211 {
1212         FilmChangeSignaller ch (this, Property::REENCODE_J2K);
1213         _reencode_j2k = r;
1214 }
1215
1216 void
1217 Film::signal_change (ChangeType type, int p)
1218 {
1219         signal_change (type, static_cast<Property>(p));
1220 }
1221
1222 void
1223 Film::signal_change (ChangeType type, Property p)
1224 {
1225         if (type == ChangeType::DONE) {
1226                 _dirty = true;
1227
1228                 if (p == Property::CONTENT) {
1229                         if (!_user_explicit_video_frame_rate) {
1230                                 set_video_frame_rate (best_video_frame_rate());
1231                         }
1232                 }
1233
1234                 emit (boost::bind (boost::ref (Change), type, p));
1235
1236                 if (p == Property::VIDEO_FRAME_RATE || p == Property::SEQUENCE) {
1237                         /* We want to call Playlist::maybe_sequence but this must happen after the
1238                            main signal emission (since the butler will see that emission and un-suspend itself).
1239                         */
1240                         emit (boost::bind(&Playlist::maybe_sequence, _playlist.get(), shared_from_this()));
1241                 }
1242         } else {
1243                 Change (type, p);
1244         }
1245 }
1246
1247 void
1248 Film::set_isdcf_date_today ()
1249 {
1250         _isdcf_date = boost::gregorian::day_clock::local_day ();
1251 }
1252
1253 boost::filesystem::path
1254 Film::j2c_path (int reel, Frame frame, Eyes eyes, bool tmp) const
1255 {
1256         boost::filesystem::path p;
1257         p /= "j2c";
1258         p /= video_identifier ();
1259
1260         char buffer[256];
1261         snprintf(buffer, sizeof(buffer), "%08d_%08" PRId64, reel, frame);
1262         string s (buffer);
1263
1264         if (eyes == Eyes::LEFT) {
1265                 s += ".L";
1266         } else if (eyes == Eyes::RIGHT) {
1267                 s += ".R";
1268         }
1269
1270         s += ".j2c";
1271
1272         if (tmp) {
1273                 s += ".tmp";
1274         }
1275
1276         p /= s;
1277         return file (p);
1278 }
1279
1280 static
1281 bool
1282 cpl_summary_compare (CPLSummary const & a, CPLSummary const & b)
1283 {
1284         return a.last_write_time > b.last_write_time;
1285 }
1286
1287 /** Find all the DCPs in our directory that can be dcp::DCP::read() and return details of their CPLs.
1288  *  The list will be returned in reverse order of timestamp (i.e. most recent first).
1289  */
1290 vector<CPLSummary>
1291 Film::cpls () const
1292 {
1293         if (!directory ()) {
1294                 return vector<CPLSummary> ();
1295         }
1296
1297         vector<CPLSummary> out;
1298
1299         auto const dir = directory().get();
1300         for (auto i: boost::filesystem::directory_iterator(dir)) {
1301                 if (
1302                         boost::filesystem::is_directory (i) &&
1303                         i.path().leaf() != "j2c" && i.path().leaf() != "video" && i.path().leaf() != "info" && i.path().leaf() != "analysis"
1304                         ) {
1305
1306                         try {
1307                                 out.push_back (CPLSummary(i));
1308                         } catch (...) {
1309
1310                         }
1311                 }
1312         }
1313
1314         sort (out.begin(), out.end(), cpl_summary_compare);
1315
1316         return out;
1317 }
1318
1319 void
1320 Film::set_encrypted (bool e)
1321 {
1322         FilmChangeSignaller ch (this, Property::ENCRYPTED);
1323         _encrypted = e;
1324 }
1325
1326 ContentList
1327 Film::content () const
1328 {
1329         return _playlist->content ();
1330 }
1331
1332 /** @param content Content to add.
1333  *  @param disable_audio_analysis true to never do automatic audio analysis, even if it is enabled in configuration.
1334  */
1335 void
1336 Film::examine_and_add_content (shared_ptr<Content> content, bool disable_audio_analysis)
1337 {
1338         if (dynamic_pointer_cast<FFmpegContent> (content) && _directory) {
1339                 run_ffprobe (content->path(0), file("ffprobe.log"));
1340         }
1341
1342         auto j = make_shared<ExamineContentJob>(shared_from_this(), content);
1343
1344         _job_connections.push_back (
1345                 j->Finished.connect (bind (&Film::maybe_add_content, this, weak_ptr<Job>(j), weak_ptr<Content>(content), disable_audio_analysis))
1346                 );
1347
1348         JobManager::instance()->add (j);
1349 }
1350
1351 void
1352 Film::maybe_add_content (weak_ptr<Job> j, weak_ptr<Content> c, bool disable_audio_analysis)
1353 {
1354         auto job = j.lock ();
1355         if (!job || !job->finished_ok ()) {
1356                 return;
1357         }
1358
1359         auto content = c.lock ();
1360         if (!content) {
1361                 return;
1362         }
1363
1364         add_content (content);
1365
1366         if (Config::instance()->automatic_audio_analysis() && content->audio && !disable_audio_analysis) {
1367                 auto playlist = make_shared<Playlist>();
1368                 playlist->add (shared_from_this(), content);
1369                 boost::signals2::connection c;
1370                 JobManager::instance()->analyse_audio (
1371                         shared_from_this(), playlist, false, c, bind (&Film::audio_analysis_finished, this)
1372                         );
1373                 _audio_analysis_connections.push_back (c);
1374         }
1375 }
1376
1377 void
1378 Film::add_content (shared_ptr<Content> c)
1379 {
1380         /* Add {video,subtitle} content after any existing {video,subtitle} content */
1381         if (c->video) {
1382                 c->set_position (shared_from_this(), _playlist->video_end(shared_from_this()));
1383         } else if (!c->text.empty()) {
1384                 c->set_position (shared_from_this(), _playlist->text_end(shared_from_this()));
1385         }
1386
1387         if (_template_film) {
1388                 /* Take settings from the first piece of content of c's type in _template */
1389                 for (auto i: _template_film->content()) {
1390                         c->take_settings_from (i);
1391                 }
1392         }
1393
1394         _playlist->add (shared_from_this(), c);
1395
1396         maybe_set_container_and_resolution ();
1397         if (c->atmos) {
1398                 set_audio_channels (14);
1399                 set_interop (false);
1400         }
1401 }
1402
1403
1404 void
1405 Film::maybe_set_container_and_resolution ()
1406 {
1407         /* Get the only piece of video content, if there is only one */
1408         shared_ptr<VideoContent> video;
1409         for (auto i: _playlist->content()) {
1410                 if (i->video) {
1411                         if (!video) {
1412                                 video = i->video;
1413                         } else {
1414                                 video.reset ();
1415                         }
1416                 }
1417         }
1418
1419         if (video) {
1420                 /* This is the only piece of video content in this Film.  Use it to make a guess for
1421                  * DCP container size and resolution, unless the user has already explicitly set these
1422                  * things.
1423                  */
1424                 if (!_user_explicit_container) {
1425                         if (video->size().ratio() > 2.3) {
1426                                 set_container (Ratio::from_id("239"), false);
1427                         } else {
1428                                 set_container (Ratio::from_id("185"), false);
1429                         }
1430                 }
1431
1432                 if (!_user_explicit_resolution) {
1433                         if (video->size_after_crop().width > 2048 || video->size_after_crop().height > 1080) {
1434                                 set_resolution (Resolution::FOUR_K, false);
1435                         } else {
1436                                 set_resolution (Resolution::TWO_K, false);
1437                         }
1438                 }
1439         }
1440 }
1441
1442 void
1443 Film::remove_content (shared_ptr<Content> c)
1444 {
1445         _playlist->remove (c);
1446         maybe_set_container_and_resolution ();
1447 }
1448
1449 void
1450 Film::move_content_earlier (shared_ptr<Content> c)
1451 {
1452         _playlist->move_earlier (shared_from_this(), c);
1453 }
1454
1455 void
1456 Film::move_content_later (shared_ptr<Content> c)
1457 {
1458         _playlist->move_later (shared_from_this(), c);
1459 }
1460
1461 /** @return length of the film from time 0 to the last thing on the playlist,
1462  *  with a minimum length of 1 second.
1463  */
1464 DCPTime
1465 Film::length () const
1466 {
1467         return max(DCPTime::from_seconds(1), _playlist->length(shared_from_this()).ceil(video_frame_rate()));
1468 }
1469
1470 int
1471 Film::best_video_frame_rate () const
1472 {
1473         /* Don't default to anything above 30fps (make the user select that explicitly) */
1474         auto best = _playlist->best_video_frame_rate ();
1475         if (best > 30) {
1476                 best /= 2;
1477         }
1478         return best;
1479 }
1480
1481 FrameRateChange
1482 Film::active_frame_rate_change (DCPTime t) const
1483 {
1484         return _playlist->active_frame_rate_change (t, video_frame_rate ());
1485 }
1486
1487 void
1488 Film::playlist_content_change (ChangeType type, weak_ptr<Content> c, int p, bool frequent)
1489 {
1490         if (p == ContentProperty::VIDEO_FRAME_RATE) {
1491                 signal_change (type, Property::CONTENT);
1492         } else if (p == AudioContentProperty::STREAMS) {
1493                 signal_change (type, Property::NAME);
1494         }
1495
1496         if (type == ChangeType::DONE) {
1497                 emit (boost::bind (boost::ref (ContentChange), type, c, p, frequent));
1498                 if (!frequent) {
1499                         check_settings_consistency ();
1500                 }
1501         } else {
1502                 ContentChange (type, c, p, frequent);
1503         }
1504
1505         _dirty = true;
1506 }
1507
1508 void
1509 Film::playlist_length_change ()
1510 {
1511         LengthChange ();
1512 }
1513
1514 void
1515 Film::playlist_change (ChangeType type)
1516 {
1517         signal_change (type, Property::CONTENT);
1518         signal_change (type, Property::NAME);
1519
1520         if (type == ChangeType::DONE) {
1521                 check_settings_consistency ();
1522         }
1523
1524         _dirty = true;
1525 }
1526
1527 /** Check for (and if necessary fix) impossible settings combinations, like
1528  *  video set to being referenced when it can't be.
1529  */
1530 void
1531 Film::check_settings_consistency ()
1532 {
1533         optional<int> atmos_rate;
1534         for (auto i: content()) {
1535
1536                 if (i->atmos) {
1537                         int rate = lrintf (i->atmos->edit_rate().as_float());
1538                         if (atmos_rate && *atmos_rate != rate) {
1539                                 Message (_("You have more than one piece of Atmos content, and they do not have the same frame rate.  You must remove some Atmos content."));
1540                         } else if (!atmos_rate && rate != video_frame_rate()) {
1541                                 atmos_rate = rate;
1542                                 set_video_frame_rate (rate, false);
1543                                 Message (_("DCP-o-matic had to change your settings so that the film's frame rate is the same as that of your Atmos content."));
1544                         }
1545                 }
1546         }
1547
1548         bool change_made = false;
1549         for (auto i: content()) {
1550                 auto d = dynamic_pointer_cast<DCPContent>(i);
1551                 if (!d) {
1552                         continue;
1553                 }
1554
1555                 string why_not;
1556                 if (d->reference_video() && !d->can_reference_video(shared_from_this(), why_not)) {
1557                         d->set_reference_video(false);
1558                         change_made = true;
1559                 }
1560                 if (d->reference_audio() && !d->can_reference_audio(shared_from_this(), why_not)) {
1561                         d->set_reference_audio(false);
1562                         change_made = true;
1563                 }
1564                 if (d->reference_text(TextType::OPEN_SUBTITLE) && !d->can_reference_text(shared_from_this(), TextType::OPEN_SUBTITLE, why_not)) {
1565                         d->set_reference_text(TextType::OPEN_SUBTITLE, false);
1566                         change_made = true;
1567                 }
1568                 if (d->reference_text(TextType::CLOSED_CAPTION) && !d->can_reference_text(shared_from_this(), TextType::CLOSED_CAPTION, why_not)) {
1569                         d->set_reference_text(TextType::CLOSED_CAPTION, false);
1570                         change_made = true;
1571                 }
1572         }
1573
1574         if (change_made) {
1575                 Message (_("DCP-o-matic had to change your settings for referring to DCPs as OV.  Please review those settings to make sure they are what you want."));
1576         }
1577 }
1578
1579 void
1580 Film::playlist_order_changed ()
1581 {
1582         /* XXX: missing PENDING */
1583         signal_change (ChangeType::DONE, Property::CONTENT_ORDER);
1584 }
1585
1586 int
1587 Film::audio_frame_rate () const
1588 {
1589         /* It seems that nobody makes 96kHz DCPs at the moment, so let's avoid them.
1590            See #1436.
1591         */
1592         return 48000;
1593 }
1594
1595 void
1596 Film::set_sequence (bool s)
1597 {
1598         if (s == _sequence) {
1599                 return;
1600         }
1601
1602         FilmChangeSignaller cc (this, Property::SEQUENCE);
1603         _sequence = s;
1604         _playlist->set_sequence (s);
1605 }
1606
1607 /** @return Size of the largest possible image in whatever resolution we are using */
1608 dcp::Size
1609 Film::full_frame () const
1610 {
1611         switch (_resolution) {
1612         case Resolution::TWO_K:
1613                 return dcp::Size (2048, 1080);
1614         case Resolution::FOUR_K:
1615                 return dcp::Size (4096, 2160);
1616         }
1617
1618         DCPOMATIC_ASSERT (false);
1619         return dcp::Size ();
1620 }
1621
1622 /** @return Size of the frame */
1623 dcp::Size
1624 Film::frame_size () const
1625 {
1626         return fit_ratio_within (container()->ratio(), full_frame ());
1627 }
1628
1629
1630 /** @return Area of Film::frame_size() that contains picture rather than pillar/letterboxing */
1631 dcp::Size
1632 Film::active_area () const
1633 {
1634         auto const frame = frame_size ();
1635         dcp::Size active;
1636
1637         for (auto i: content()) {
1638                 if (i->video) {
1639                         dcp::Size s = i->video->scaled_size (frame);
1640                         active.width = max(active.width, s.width);
1641                         active.height = max(active.height, s.height);
1642                 }
1643         }
1644
1645         return active;
1646 }
1647
1648
1649 /** @param recipient KDM recipient certificate.
1650  *  @param trusted_devices Certificate thumbprints of other trusted devices (can be empty).
1651  *  @param cpl_file CPL filename.
1652  *  @param from KDM from time expressed as a local time with an offset from UTC.
1653  *  @param until KDM to time expressed as a local time with an offset from UTC.
1654  *  @param formulation KDM formulation to use.
1655  *  @param disable_forensic_marking_picture true to disable forensic marking of picture.
1656  *  @param disable_forensic_marking_audio if not set, don't disable forensic marking of audio.  If set to 0,
1657  *  disable all forensic marking; if set above 0, disable forensic marking above that channel.
1658  */
1659 dcp::EncryptedKDM
1660 Film::make_kdm (
1661         dcp::Certificate recipient,
1662         vector<string> trusted_devices,
1663         boost::filesystem::path cpl_file,
1664         dcp::LocalTime from,
1665         dcp::LocalTime until,
1666         dcp::Formulation formulation,
1667         bool disable_forensic_marking_picture,
1668         optional<int> disable_forensic_marking_audio
1669         ) const
1670 {
1671         if (!_encrypted) {
1672                 throw runtime_error (_("Cannot make a KDM as this project is not encrypted."));
1673         }
1674
1675         auto cpl = make_shared<dcp::CPL>(cpl_file);
1676         auto signer = Config::instance()->signer_chain();
1677         if (!signer->valid ()) {
1678                 throw InvalidSignerError ();
1679         }
1680
1681         /* Find keys that have been added to imported, encrypted DCP content */
1682         list<dcp::DecryptedKDMKey> imported_keys;
1683         for (auto i: content()) {
1684                 auto d = dynamic_pointer_cast<DCPContent> (i);
1685                 if (d && d->kdm()) {
1686                         dcp::DecryptedKDM kdm (d->kdm().get(), Config::instance()->decryption_chain()->key().get());
1687                         auto keys = kdm.keys ();
1688                         copy (keys.begin(), keys.end(), back_inserter (imported_keys));
1689                 }
1690         }
1691
1692         map<shared_ptr<const dcp::ReelFileAsset>, dcp::Key> keys;
1693
1694         for (auto i: cpl->reel_file_assets()) {
1695                 if (!i->encrypted()) {
1696                         continue;
1697                 }
1698
1699                 /* Get any imported key for this ID */
1700                 bool done = false;
1701                 for (auto j: imported_keys) {
1702                         if (j.id() == i->key_id().get()) {
1703                                 LOG_GENERAL ("Using imported key for %1", i->key_id().get());
1704                                 keys[i] = j.key();
1705                                 done = true;
1706                         }
1707                 }
1708
1709                 if (!done) {
1710                         /* No imported key; it must be an asset that we encrypted */
1711                         LOG_GENERAL ("Using our own key for %1", i->key_id().get());
1712                         keys[i] = key();
1713                 }
1714         }
1715
1716         return dcp::DecryptedKDM (
1717                 cpl->id(), keys, from, until, cpl->content_title_text(), cpl->content_title_text(), dcp::LocalTime().as_string()
1718                 ).encrypt (signer, recipient, trusted_devices, formulation, disable_forensic_marking_picture, disable_forensic_marking_audio);
1719 }
1720
1721
1722 /** @return The approximate disk space required to encode a DCP of this film with the
1723  *  current settings, in bytes.
1724  */
1725 uint64_t
1726 Film::required_disk_space () const
1727 {
1728         return _playlist->required_disk_space (shared_from_this(), j2k_bandwidth(), audio_channels(), audio_frame_rate());
1729 }
1730
1731 /** This method checks the disk that the Film is on and tries to decide whether or not
1732  *  there will be enough space to make a DCP for it.  If so, true is returned; if not,
1733  *  false is returned and required and available are filled in with the amount of disk space
1734  *  required and available respectively (in GB).
1735  *
1736  *  Note: the decision made by this method isn't, of course, 100% reliable.
1737  */
1738 bool
1739 Film::should_be_enough_disk_space (double& required, double& available, bool& can_hard_link) const
1740 {
1741         /* Create a test file and see if we can hard-link it */
1742         boost::filesystem::path test = internal_video_asset_dir() / "test";
1743         boost::filesystem::path test2 = internal_video_asset_dir() / "test2";
1744         can_hard_link = true;
1745         auto f = fopen_boost (test, "w");
1746         if (f) {
1747                 fclose (f);
1748                 boost::system::error_code ec;
1749                 boost::filesystem::create_hard_link (test, test2, ec);
1750                 if (ec) {
1751                         can_hard_link = false;
1752                 }
1753                 boost::filesystem::remove (test);
1754                 boost::filesystem::remove (test2);
1755         }
1756
1757         auto s = boost::filesystem::space (internal_video_asset_dir ());
1758         required = double (required_disk_space ()) / 1073741824.0f;
1759         if (!can_hard_link) {
1760                 required *= 2;
1761         }
1762         available = double (s.available) / 1073741824.0f;
1763         return (available - required) > 1;
1764 }
1765
1766 /** @return The names of the channels that audio contents' outputs are passed into;
1767  *  this is either the DCP or a AudioProcessor.
1768  */
1769 vector<NamedChannel>
1770 Film::audio_output_names () const
1771 {
1772         if (audio_processor ()) {
1773                 return audio_processor()->input_names ();
1774         }
1775
1776         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
1777
1778         vector<NamedChannel> n;
1779
1780         for (int i = 0; i < audio_channels(); ++i) {
1781                 if (i != 8 && i != 9 && i != 15) {
1782                         n.push_back (NamedChannel(short_audio_channel_name(i), i));
1783                 }
1784         }
1785
1786         return n;
1787 }
1788
1789 void
1790 Film::repeat_content (ContentList c, int n)
1791 {
1792         _playlist->repeat (shared_from_this(), c, n);
1793 }
1794
1795 void
1796 Film::remove_content (ContentList c)
1797 {
1798         _playlist->remove (c);
1799 }
1800
1801 void
1802 Film::audio_analysis_finished ()
1803 {
1804         /* XXX */
1805 }
1806
1807 list<DCPTimePeriod>
1808 Film::reels () const
1809 {
1810         list<DCPTimePeriod> p;
1811         auto const len = length();
1812
1813         switch (reel_type ()) {
1814         case ReelType::SINGLE:
1815                 p.push_back (DCPTimePeriod (DCPTime (), len));
1816                 break;
1817         case ReelType::BY_VIDEO_CONTENT:
1818         {
1819                 /* Collect all reel boundaries */
1820                 list<DCPTime> split_points;
1821                 split_points.push_back (DCPTime());
1822                 split_points.push_back (len);
1823                 for (auto c: content()) {
1824                         if (c->video) {
1825                                 for (auto t: c->reel_split_points(shared_from_this())) {
1826                                         split_points.push_back (t);
1827                                 }
1828                                 split_points.push_back (c->end(shared_from_this()));
1829                         }
1830                 }
1831
1832                 split_points.sort ();
1833                 split_points.unique ();
1834
1835                 /* Make them into periods, coalescing any that are less than 1 second long */
1836                 optional<DCPTime> last;
1837                 for (auto t: split_points) {
1838                         if (last && (t - *last) >= DCPTime::from_seconds(1)) {
1839                                 /* Period from *last to t is long enough; use it and start a new one */
1840                                 p.push_back (DCPTimePeriod(*last, t));
1841                                 last = t;
1842                         } else if (!last) {
1843                                 /* That was the first time, so start a new period */
1844                                 last = t;
1845                         }
1846                 }
1847
1848                 if (!p.empty()) {
1849                         p.back().to = split_points.back();
1850                 }
1851                 break;
1852         }
1853         case ReelType::BY_LENGTH:
1854         {
1855                 DCPTime current;
1856                 /* Integer-divide reel length by the size of one frame to give the number of frames per reel,
1857                  * making sure we don't go less than 1s long.
1858                  */
1859                 Frame const reel_in_frames = max(_reel_length / ((j2k_bandwidth() / video_frame_rate()) / 8), static_cast<Frame>(video_frame_rate()));
1860                 while (current < len) {
1861                         DCPTime end = min (len, current + DCPTime::from_frames (reel_in_frames, video_frame_rate ()));
1862                         p.push_back (DCPTimePeriod (current, end));
1863                         current = end;
1864                 }
1865                 break;
1866         }
1867         }
1868
1869         return p;
1870 }
1871
1872 /** @param period A period within the DCP
1873  *  @return Name of the content which most contributes to the given period.
1874  */
1875 string
1876 Film::content_summary (DCPTimePeriod period) const
1877 {
1878         return _playlist->content_summary (shared_from_this(), period);
1879 }
1880
1881 void
1882 Film::use_template (string name)
1883 {
1884         _template_film.reset (new Film (optional<boost::filesystem::path>()));
1885         _template_film->read_metadata (Config::instance()->template_path (name));
1886         _use_isdcf_name = _template_film->_use_isdcf_name;
1887         _dcp_content_type = _template_film->_dcp_content_type;
1888         _container = _template_film->_container;
1889         _resolution = _template_film->_resolution;
1890         _j2k_bandwidth = _template_film->_j2k_bandwidth;
1891         _video_frame_rate = _template_film->_video_frame_rate;
1892         _encrypted = _template_film->_encrypted;
1893         _audio_channels = _template_film->_audio_channels;
1894         _sequence = _template_film->_sequence;
1895         _three_d = _template_film->_three_d;
1896         _interop = _template_film->_interop;
1897         _audio_processor = _template_film->_audio_processor;
1898         _reel_type = _template_film->_reel_type;
1899         _reel_length = _template_film->_reel_length;
1900 }
1901
1902 pair<double, double>
1903 Film::speed_up_range (int dcp_frame_rate) const
1904 {
1905         return _playlist->speed_up_range (dcp_frame_rate);
1906 }
1907
1908 void
1909 Film::copy_from (shared_ptr<const Film> film)
1910 {
1911         read_metadata (film->file (metadata_file));
1912 }
1913
1914 bool
1915 Film::references_dcp_video () const
1916 {
1917         for (auto i: _playlist->content()) {
1918                 auto d = dynamic_pointer_cast<DCPContent>(i);
1919                 if (d && d->reference_video()) {
1920                         return true;
1921                 }
1922         }
1923
1924         return false;
1925 }
1926
1927 bool
1928 Film::references_dcp_audio () const
1929 {
1930         for (auto i: _playlist->content()) {
1931                 auto d = dynamic_pointer_cast<DCPContent>(i);
1932                 if (d && d->reference_audio()) {
1933                         return true;
1934                 }
1935         }
1936
1937         return false;
1938 }
1939
1940
1941 bool
1942 Film::contains_atmos_content () const
1943 {
1944         for (auto i: _playlist->content()) {
1945                 if (i->atmos) {
1946                         return true;
1947                 }
1948         }
1949
1950         return false;
1951 }
1952
1953
1954 list<DCPTextTrack>
1955 Film::closed_caption_tracks () const
1956 {
1957         list<DCPTextTrack> tt;
1958         for (auto i: content()) {
1959                 for (auto j: i->text) {
1960                         /* XXX: Empty DCPTextTrack ends up being a magic value here - the "unknown" or "not specified" track */
1961                         auto dtt = j->dcp_track().get_value_or(DCPTextTrack());
1962                         if (j->type() == TextType::CLOSED_CAPTION && find(tt.begin(), tt.end(), dtt) == tt.end()) {
1963                                 tt.push_back (dtt);
1964                         }
1965                 }
1966         }
1967
1968         return tt;
1969 }
1970
1971 void
1972 Film::set_marker (dcp::Marker type, DCPTime time)
1973 {
1974         FilmChangeSignaller ch (this, Property::MARKERS);
1975         _markers[type] = time;
1976 }
1977
1978
1979 void
1980 Film::unset_marker (dcp::Marker type)
1981 {
1982         FilmChangeSignaller ch (this, Property::MARKERS);
1983         _markers.erase (type);
1984 }
1985
1986
1987 void
1988 Film::clear_markers ()
1989 {
1990         FilmChangeSignaller ch (this, Property::MARKERS);
1991         _markers.clear ();
1992 }
1993
1994
1995 void
1996 Film::set_ratings (vector<dcp::Rating> r)
1997 {
1998         FilmChangeSignaller ch (this, Property::RATINGS);
1999         _ratings = r;
2000 }
2001
2002 void
2003 Film::set_content_versions (vector<string> v)
2004 {
2005         FilmChangeSignaller ch (this, Property::CONTENT_VERSIONS);
2006         _content_versions = v;
2007 }
2008
2009
2010 void
2011 Film::set_name_language (dcp::LanguageTag lang)
2012 {
2013         FilmChangeSignaller ch (this, Property::NAME_LANGUAGE);
2014         _name_language = lang;
2015 }
2016
2017
2018 void
2019 Film::set_release_territory (optional<dcp::LanguageTag::RegionSubtag> region)
2020 {
2021         FilmChangeSignaller ch (this, Property::RELEASE_TERRITORY);
2022         _release_territory = region;
2023 }
2024
2025
2026 void
2027 Film::set_status (dcp::Status s)
2028 {
2029         FilmChangeSignaller ch (this, Property::STATUS);
2030         _status = s;
2031 }
2032
2033
2034 void
2035 Film::set_version_number (int v)
2036 {
2037         FilmChangeSignaller ch (this, Property::VERSION_NUMBER);
2038         _version_number = v;
2039 }
2040
2041
2042 void
2043 Film::set_chain (optional<string> c)
2044 {
2045         FilmChangeSignaller ch (this, Property::CHAIN);
2046         _chain = c;
2047 }
2048
2049
2050 void
2051 Film::set_distributor (optional<string> d)
2052 {
2053         FilmChangeSignaller ch (this, Property::DISTRIBUTOR);
2054         _distributor = d;
2055 }
2056
2057
2058 void
2059 Film::set_luminance (optional<dcp::Luminance> l)
2060 {
2061         FilmChangeSignaller ch (this, Property::LUMINANCE);
2062         _luminance = l;
2063 }
2064
2065
2066 void
2067 Film::set_facility (optional<string> f)
2068 {
2069         FilmChangeSignaller ch (this, Property::FACILITY);
2070         _facility = f;
2071 }
2072
2073
2074 void
2075 Film::set_studio (optional<string> s)
2076 {
2077         FilmChangeSignaller ch (this, Property::STUDIO);
2078         _studio = s;
2079 }
2080
2081
2082 optional<DCPTime>
2083 Film::marker (dcp::Marker type) const
2084 {
2085         auto i = _markers.find (type);
2086         if (i == _markers.end()) {
2087                 return {};
2088         }
2089         return i->second;
2090 }
2091
2092 shared_ptr<InfoFileHandle>
2093 Film::info_file_handle (DCPTimePeriod period, bool read) const
2094 {
2095         return std::make_shared<InfoFileHandle>(_info_file_mutex, info_file(period), read);
2096 }
2097
2098 InfoFileHandle::InfoFileHandle (boost::mutex& mutex, boost::filesystem::path file, bool read)
2099         : _lock (mutex)
2100         , _file (file)
2101 {
2102         if (read) {
2103                 _handle = fopen_boost (file, "rb");
2104                 if (!_handle) {
2105                         throw OpenFileError (file, errno, OpenFileError::READ);
2106                 }
2107         } else {
2108                 auto const exists = boost::filesystem::exists (file);
2109                 if (exists) {
2110                         _handle = fopen_boost (file, "r+b");
2111                 } else {
2112                         _handle = fopen_boost (file, "wb");
2113                 }
2114
2115                 if (!_handle) {
2116                         throw OpenFileError (file, errno, exists ? OpenFileError::READ_WRITE : OpenFileError::WRITE);
2117                 }
2118         }
2119 }
2120
2121 InfoFileHandle::~InfoFileHandle ()
2122 {
2123         fclose (_handle);
2124 }
2125
2126
2127 /** Add FFOC and LFOC markers to a list if they are not already there */
2128 void
2129 Film::add_ffoc_lfoc (Markers& markers) const
2130 {
2131         if (markers.find(dcp::Marker::FFOC) == markers.end()) {
2132                 markers[dcp::Marker::FFOC] = dcpomatic::DCPTime::from_frames(1, video_frame_rate());
2133         }
2134
2135         if (markers.find(dcp::Marker::LFOC) == markers.end()) {
2136                 markers[dcp::Marker::LFOC] = length() - DCPTime::from_frames(1, video_frame_rate());
2137         }
2138 }
2139
2140
2141 void
2142 Film::set_temp_version (bool t)
2143 {
2144         FilmChangeSignaller ch (this, Property::TEMP_VERSION);
2145         _temp_version = t;
2146 }
2147
2148
2149 void
2150 Film::set_pre_release (bool p)
2151 {
2152         FilmChangeSignaller ch (this, Property::PRE_RELEASE);
2153         _pre_release = p;
2154 }
2155
2156
2157 void
2158 Film::set_red_band (bool r)
2159 {
2160         FilmChangeSignaller ch (this, Property::RED_BAND);
2161         _red_band = r;
2162 }
2163
2164
2165 void
2166 Film::set_two_d_version_of_three_d (bool t)
2167 {
2168         FilmChangeSignaller ch (this, Property::TWO_D_VERSION_OF_THREE_D);
2169         _two_d_version_of_three_d = t;
2170 }
2171
2172
2173 void
2174 Film::set_audio_language (optional<dcp::LanguageTag> language)
2175 {
2176         FilmChangeSignaller ch (this, Property::AUDIO_LANGUAGE);
2177         _audio_language = language;
2178 }
2179
2180
2181 bool
2182 Film::has_sign_language_video_channel () const
2183 {
2184         return _audio_channels >= static_cast<int>(dcp::Channel::SIGN_LANGUAGE);
2185 }
2186
2187
2188 void
2189 Film::set_sign_language_video_language (optional<dcp::LanguageTag> lang)
2190 {
2191         FilmChangeSignaller ch (this, Property::SIGN_LANGUAGE_VIDEO_LANGUAGE);
2192         _sign_language_video_language = lang;
2193 }
2194