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