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