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