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