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