Add option to analyse audio automatically when content is added (#673).
[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         ContentList cl = content ();
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                 for (ContentList::iterator i = cl.begin(); i != cl.end(); ++i) {
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                 for (ContentList::const_iterator i = cl.begin(); i != cl.end(); ++i) {
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         if (!dm.package_type.empty ()) {
680                 d << "_" << dm.package_type;
681         }
682
683         return d.str ();
684 }
685
686 /** @return name to give the DCP */
687 string
688 Film::dcp_name (bool if_created_now) const
689 {
690         string unfiltered;
691         if (use_isdcf_name()) {
692                 unfiltered = isdcf_name (if_created_now);
693         } else {
694                 unfiltered = name ();
695         }
696
697         /* Filter out `bad' characters which cause problems with some systems.
698            There's no apparent list of what really is allowed, so this is a guess.
699         */
700
701         string filtered;
702         string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";
703         for (size_t i = 0; i < unfiltered.size(); ++i) {
704                 if (allowed.find (unfiltered[i]) != string::npos) {
705                         filtered += unfiltered[i];
706                 }
707         }
708
709         return filtered;
710 }
711
712 void
713 Film::set_directory (boost::filesystem::path d)
714 {
715         _directory = d;
716         _dirty = true;
717 }
718
719 void
720 Film::set_name (string n)
721 {
722         _name = n;
723         signal_changed (NAME);
724 }
725
726 void
727 Film::set_use_isdcf_name (bool u)
728 {
729         _use_isdcf_name = u;
730         signal_changed (USE_ISDCF_NAME);
731 }
732
733 void
734 Film::set_dcp_content_type (DCPContentType const * t)
735 {
736         _dcp_content_type = t;
737         signal_changed (DCP_CONTENT_TYPE);
738 }
739
740 void
741 Film::set_container (Ratio const * c)
742 {
743         _container = c;
744         signal_changed (CONTAINER);
745 }
746
747 void
748 Film::set_resolution (Resolution r)
749 {
750         _resolution = r;
751         signal_changed (RESOLUTION);
752 }
753
754 void
755 Film::set_j2k_bandwidth (int b)
756 {
757         _j2k_bandwidth = b;
758         signal_changed (J2K_BANDWIDTH);
759 }
760
761 void
762 Film::set_isdcf_metadata (ISDCFMetadata m)
763 {
764         _isdcf_metadata = m;
765         signal_changed (ISDCF_METADATA);
766 }
767
768 void
769 Film::set_video_frame_rate (int f)
770 {
771         _video_frame_rate = f;
772         signal_changed (VIDEO_FRAME_RATE);
773 }
774
775 void
776 Film::set_audio_channels (int c)
777 {
778         _audio_channels = c;
779         signal_changed (AUDIO_CHANNELS);
780 }
781
782 void
783 Film::set_three_d (bool t)
784 {
785         _three_d = t;
786         signal_changed (THREE_D);
787
788         if (_three_d && _isdcf_metadata.two_d_version_of_three_d) {
789                 _isdcf_metadata.two_d_version_of_three_d = false;
790                 signal_changed (ISDCF_METADATA);
791         }
792 }
793
794 void
795 Film::set_interop (bool i)
796 {
797         _interop = i;
798         signal_changed (INTEROP);
799 }
800
801 void
802 Film::set_audio_processor (AudioProcessor const * processor)
803 {
804         _audio_processor = processor;
805         signal_changed (AUDIO_PROCESSOR);
806         signal_changed (AUDIO_CHANNELS);
807 }
808
809 void
810 Film::signal_changed (Property p)
811 {
812         _dirty = true;
813
814         switch (p) {
815         case Film::CONTENT:
816                 set_video_frame_rate (_playlist->best_dcp_frame_rate ());
817                 break;
818         case Film::VIDEO_FRAME_RATE:
819         case Film::SEQUENCE_VIDEO:
820                 _playlist->maybe_sequence_video ();
821                 break;
822         default:
823                 break;
824         }
825
826         emit (boost::bind (boost::ref (Changed), p));
827 }
828
829 void
830 Film::set_isdcf_date_today ()
831 {
832         _isdcf_date = boost::gregorian::day_clock::local_day ();
833 }
834
835 boost::filesystem::path
836 Film::j2c_path (int f, Eyes e, bool t) const
837 {
838         boost::filesystem::path p;
839         p /= "j2c";
840         p /= video_identifier ();
841
842         SafeStringStream s;
843         s.width (8);
844         s << setfill('0') << f;
845
846         if (e == EYES_LEFT) {
847                 s << ".L";
848         } else if (e == EYES_RIGHT) {
849                 s << ".R";
850         }
851
852         s << ".j2c";
853
854         if (t) {
855                 s << ".tmp";
856         }
857
858         p /= s.str();
859         return file (p);
860 }
861
862 /** Find all the DCPs in our directory that can be dcp::DCP::read() and return details of their CPLs */
863 vector<CPLSummary>
864 Film::cpls () const
865 {
866         vector<CPLSummary> out;
867
868         boost::filesystem::path const dir = directory ();
869         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator(dir); i != boost::filesystem::directory_iterator(); ++i) {
870                 if (
871                         boost::filesystem::is_directory (*i) &&
872                         i->path().leaf() != "j2c" && i->path().leaf() != "video" && i->path().leaf() != "info" && i->path().leaf() != "analysis"
873                         ) {
874
875                         try {
876                                 dcp::DCP dcp (*i);
877                                 dcp.read ();
878                                 out.push_back (
879                                         CPLSummary (
880                                                 i->path().leaf().string(),
881                                                 dcp.cpls().front()->id(),
882                                                 dcp.cpls().front()->annotation_text(),
883                                                 dcp.cpls().front()->file()
884                                                 )
885                                         );
886                         } catch (...) {
887
888                         }
889                 }
890         }
891
892         return out;
893 }
894
895 void
896 Film::set_signed (bool s)
897 {
898         _signed = s;
899         signal_changed (SIGNED);
900 }
901
902 void
903 Film::set_encrypted (bool e)
904 {
905         _encrypted = e;
906         signal_changed (ENCRYPTED);
907 }
908
909 void
910 Film::set_key (dcp::Key key)
911 {
912         _key = key;
913         signal_changed (KEY);
914 }
915
916 ContentList
917 Film::content () const
918 {
919         return _playlist->content ();
920 }
921
922 void
923 Film::examine_content (shared_ptr<Content> c)
924 {
925         shared_ptr<Job> j (new ExamineContentJob (shared_from_this(), c));
926         JobManager::instance()->add (j);
927 }
928
929 void
930 Film::examine_and_add_content (shared_ptr<Content> c)
931 {
932         if (dynamic_pointer_cast<FFmpegContent> (c) && !_directory.empty ()) {
933                 run_ffprobe (c->path(0), file ("ffprobe.log"), _log);
934         }
935
936         shared_ptr<Job> j (new ExamineContentJob (shared_from_this(), c));
937
938         _job_connections.push_back (
939                 j->Finished.connect (bind (&Film::maybe_add_content, this, weak_ptr<Job> (j), weak_ptr<Content> (c)))
940                 );
941
942         JobManager::instance()->add (j);
943 }
944
945 void
946 Film::maybe_add_content (weak_ptr<Job> j, weak_ptr<Content> c)
947 {
948         shared_ptr<Job> job = j.lock ();
949         if (!job || !job->finished_ok ()) {
950                 return;
951         }
952
953         shared_ptr<Content> content = c.lock ();
954         if (!content) {
955                 return;
956         }
957
958         add_content (content);
959         if (Config::instance()->automatic_audio_analysis ()) {
960                 shared_ptr<Playlist> playlist (new Playlist);
961                 playlist->add (content);
962                 boost::signals2::connection c;
963                 JobManager::instance()->analyse_audio (
964                         shared_from_this (), playlist, c, bind (&Film::audio_analysis_finished, this)
965                         );
966                 _audio_analysis_connections.push_back (c);
967         }
968 }
969
970 void
971 Film::add_content (shared_ptr<Content> c)
972 {
973         /* Add video content after any existing content */
974         if (dynamic_pointer_cast<VideoContent> (c)) {
975                 c->set_position (_playlist->video_end ());
976         }
977
978         _playlist->add (c);
979 }
980
981 void
982 Film::remove_content (shared_ptr<Content> c)
983 {
984         _playlist->remove (c);
985 }
986
987 void
988 Film::move_content_earlier (shared_ptr<Content> c)
989 {
990         _playlist->move_earlier (c);
991 }
992
993 void
994 Film::move_content_later (shared_ptr<Content> c)
995 {
996         _playlist->move_later (c);
997 }
998
999 DCPTime
1000 Film::length () const
1001 {
1002         return _playlist->length ();
1003 }
1004
1005 int
1006 Film::best_video_frame_rate () const
1007 {
1008         return _playlist->best_dcp_frame_rate ();
1009 }
1010
1011 FrameRateChange
1012 Film::active_frame_rate_change (DCPTime t) const
1013 {
1014         return _playlist->active_frame_rate_change (t, video_frame_rate ());
1015 }
1016
1017 void
1018 Film::playlist_content_changed (weak_ptr<Content> c, int p, bool frequent)
1019 {
1020         _dirty = true;
1021
1022         if (p == VideoContentProperty::VIDEO_FRAME_RATE) {
1023                 set_video_frame_rate (_playlist->best_dcp_frame_rate ());
1024         } else if (p == AudioContentProperty::AUDIO_STREAMS) {
1025                 signal_changed (NAME);
1026         }
1027
1028         emit (boost::bind (boost::ref (ContentChanged), c, p, frequent));
1029 }
1030
1031 void
1032 Film::playlist_changed ()
1033 {
1034         signal_changed (CONTENT);
1035         signal_changed (NAME);
1036 }
1037
1038 int
1039 Film::audio_frame_rate () const
1040 {
1041         BOOST_FOREACH (shared_ptr<Content> i, content ()) {
1042                 shared_ptr<AudioContent> a = dynamic_pointer_cast<AudioContent> (i);
1043                 if (a && a->has_rate_above_48k ()) {
1044                         return 96000;
1045                 }
1046         }
1047
1048         return 48000;
1049 }
1050
1051 void
1052 Film::set_sequence_video (bool s)
1053 {
1054         _sequence_video = s;
1055         _playlist->set_sequence_video (s);
1056         signal_changed (SEQUENCE_VIDEO);
1057 }
1058
1059 /** @return Size of the largest possible image in whatever resolution we are using */
1060 dcp::Size
1061 Film::full_frame () const
1062 {
1063         switch (_resolution) {
1064         case RESOLUTION_2K:
1065                 return dcp::Size (2048, 1080);
1066         case RESOLUTION_4K:
1067                 return dcp::Size (4096, 2160);
1068         }
1069
1070         DCPOMATIC_ASSERT (false);
1071         return dcp::Size ();
1072 }
1073
1074 /** @return Size of the frame */
1075 dcp::Size
1076 Film::frame_size () const
1077 {
1078         return fit_ratio_within (container()->ratio(), full_frame ());
1079 }
1080
1081 dcp::EncryptedKDM
1082 Film::make_kdm (
1083         dcp::Certificate target,
1084         boost::filesystem::path cpl_file,
1085         dcp::LocalTime from,
1086         dcp::LocalTime until,
1087         dcp::Formulation formulation
1088         ) const
1089 {
1090         shared_ptr<const dcp::CPL> cpl (new dcp::CPL (cpl_file));
1091         shared_ptr<const dcp::CertificateChain> signer = Config::instance()->signer_chain ();
1092         if (!signer->valid ()) {
1093                 throw InvalidSignerError ();
1094         }
1095
1096         return dcp::DecryptedKDM (
1097                 cpl, key(), from, until, "DCP-o-matic", cpl->content_title_text(), dcp::LocalTime().as_string()
1098                 ).encrypt (signer, target, formulation);
1099 }
1100
1101 list<dcp::EncryptedKDM>
1102 Film::make_kdms (
1103         list<shared_ptr<Screen> > screens,
1104         boost::filesystem::path dcp,
1105         dcp::LocalTime from,
1106         dcp::LocalTime until,
1107         dcp::Formulation formulation
1108         ) const
1109 {
1110         list<dcp::EncryptedKDM> kdms;
1111
1112         for (list<shared_ptr<Screen> >::iterator i = screens.begin(); i != screens.end(); ++i) {
1113                 if ((*i)->certificate) {
1114                         kdms.push_back (make_kdm ((*i)->certificate.get(), dcp, from, until, formulation));
1115                 }
1116         }
1117
1118         return kdms;
1119 }
1120
1121 /** @return The approximate disk space required to encode a DCP of this film with the
1122  *  current settings, in bytes.
1123  */
1124 uint64_t
1125 Film::required_disk_space () const
1126 {
1127         return uint64_t (j2k_bandwidth() / 8) * length().seconds();
1128 }
1129
1130 /** This method checks the disk that the Film is on and tries to decide whether or not
1131  *  there will be enough space to make a DCP for it.  If so, true is returned; if not,
1132  *  false is returned and required and availabe are filled in with the amount of disk space
1133  *  required and available respectively (in Gb).
1134  *
1135  *  Note: the decision made by this method isn't, of course, 100% reliable.
1136  */
1137 bool
1138 Film::should_be_enough_disk_space (double& required, double& available, bool& can_hard_link) const
1139 {
1140         /* Create a test file and see if we can hard-link it */
1141         boost::filesystem::path test = internal_video_asset_dir() / "test";
1142         boost::filesystem::path test2 = internal_video_asset_dir() / "test2";
1143         can_hard_link = true;
1144         FILE* f = fopen_boost (test, "w");
1145         if (f) {
1146                 fclose (f);
1147                 boost::system::error_code ec;
1148                 boost::filesystem::create_hard_link (test, test2, ec);
1149                 if (ec) {
1150                         can_hard_link = false;
1151                 }
1152                 boost::filesystem::remove (test);
1153                 boost::filesystem::remove (test2);
1154         }
1155
1156         boost::filesystem::space_info s = boost::filesystem::space (internal_video_asset_dir ());
1157         required = double (required_disk_space ()) / 1073741824.0f;
1158         if (!can_hard_link) {
1159                 required *= 2;
1160         }
1161         available = double (s.available) / 1073741824.0f;
1162         return (available - required) > 1;
1163 }
1164
1165 string
1166 Film::subtitle_language () const
1167 {
1168         set<string> languages;
1169
1170         ContentList cl = content ();
1171         BOOST_FOREACH (shared_ptr<Content>& c, cl) {
1172                 shared_ptr<SubtitleContent> sc = dynamic_pointer_cast<SubtitleContent> (c);
1173                 if (sc) {
1174                         languages.insert (sc->subtitle_language ());
1175                 }
1176         }
1177
1178         string all;
1179         BOOST_FOREACH (string s, languages) {
1180                 if (!all.empty ()) {
1181                         all += "/" + s;
1182                 } else {
1183                         all += s;
1184                 }
1185         }
1186
1187         return all;
1188 }
1189
1190 /** Change the gains of the supplied AudioMapping to make it a default
1191  *  for this film.  The defaults are guessed based on what processor (if any)
1192  *  is in use and the number of input channels.
1193  */
1194 void
1195 Film::make_audio_mapping_default (AudioMapping& mapping) const
1196 {
1197         if (audio_processor ()) {
1198                 audio_processor()->make_audio_mapping_default (mapping);
1199         } else {
1200                 mapping.make_zero ();
1201                 if (mapping.input_channels() == 1) {
1202                         /* Mono -> Centre */
1203                         mapping.set (0, static_cast<int> (dcp::CENTRE), 1);
1204                 } else {
1205                         /* 1:1 mapping */
1206                         for (int i = 0; i < min (mapping.input_channels(), mapping.output_channels()); ++i) {
1207                                 mapping.set (i, i, 1);
1208                         }
1209                 }
1210         }
1211 }
1212
1213 /** @return The names of the channels that audio contents' outputs are passed into;
1214  *  this is either the DCP or a AudioProcessor.
1215  */
1216 vector<string>
1217 Film::audio_output_names () const
1218 {
1219         if (audio_processor ()) {
1220                 return audio_processor()->input_names ();
1221         }
1222
1223         vector<string> n;
1224         n.push_back (_("L"));
1225         n.push_back (_("R"));
1226         n.push_back (_("C"));
1227         n.push_back (_("Lfe"));
1228         n.push_back (_("Ls"));
1229         n.push_back (_("Rs"));
1230         n.push_back (_("HI"));
1231         n.push_back (_("VI"));
1232         n.push_back (_("Lc"));
1233         n.push_back (_("Rc"));
1234         n.push_back (_("BsL"));
1235         n.push_back (_("BsR"));
1236
1237         return vector<string> (n.begin(), n.begin() + audio_channels ());
1238 }
1239
1240 void
1241 Film::repeat_content (ContentList c, int n)
1242 {
1243         _playlist->repeat (c, n);
1244 }
1245
1246 void
1247 Film::remove_content (ContentList c)
1248 {
1249         _playlist->remove (c);
1250 }
1251
1252 void
1253 Film::audio_analysis_finished ()
1254 {
1255         /* XXX */
1256 }