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