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