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