e5904ca1e988d3b6da451d62e1bda96154511abe
[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         /* XXX: this uses the first bit of content only */
585
586         /* The standard says we don't do this for trailers, for some strange reason */
587         if (dcp_content_type() && dcp_content_type()->libdcp_kind() != dcp::TRAILER) {
588                 ContentList cl = content ();
589                 Ratio const * content_ratio = 0;
590                 for (ContentList::iterator i = cl.begin(); i != cl.end(); ++i) {
591                         shared_ptr<VideoContent> vc = dynamic_pointer_cast<VideoContent> (*i);
592                         if (vc) {
593                                 /* Here's the first piece of video content */
594                                 if (vc->scale().ratio ()) {
595                                         content_ratio = vc->scale().ratio ();
596                                 } else {
597                                         content_ratio = Ratio::from_ratio (vc->video_size().ratio ());
598                                 }
599                                 break;
600                         }
601                 }
602                 
603                 if (content_ratio && content_ratio != container()) {
604                         d << "-" << content_ratio->isdcf_name();
605                 }
606         }
607
608         if (!dm.audio_language.empty ()) {
609                 d << "_" << dm.audio_language;
610                 if (!dm.subtitle_language.empty()) {
611                         d << "-" << dm.subtitle_language;
612                 } else {
613                         d << "-XX";
614                 }
615         }
616
617         if (!dm.territory.empty ()) {
618                 d << "_" << dm.territory;
619                 if (!dm.rating.empty ()) {
620                         d << "-" << dm.rating;
621                 }
622         }
623
624         switch (audio_channels ()) {
625         case 1:
626                 d << "_10";
627                 break;
628         case 2:
629                 d << "_20";
630                 break;
631         case 3:
632                 d << "_30";
633                 break;
634         case 4:
635                 d << "_40";
636                 break;
637         case 5:
638                 d << "_50";
639                 break;
640         case 6:
641                 d << "_51";
642                 break;
643         }
644
645         /* XXX: HI/VI */
646
647         d << "_" << resolution_to_string (_resolution);
648         
649         if (!dm.studio.empty ()) {
650                 d << "_" << dm.studio;
651         }
652
653         if (if_created_now) {
654                 d << "_" << boost::gregorian::to_iso_string (boost::gregorian::day_clock::local_day ());
655         } else {
656                 d << "_" << boost::gregorian::to_iso_string (_isdcf_date);
657         }
658
659         if (!dm.facility.empty ()) {
660                 d << "_" << dm.facility;
661         }
662
663         if (_interop) {
664                 d << "_IOP";
665         } else {
666                 d << "_SMPTE";
667         }
668         
669         if (three_d ()) {
670                 d << "-3D";
671         }
672
673         if (!dm.package_type.empty ()) {
674                 d << "_" << dm.package_type;
675         }
676
677         return d.str ();
678 }
679
680 /** @return name to give the DCP */
681 string
682 Film::dcp_name (bool if_created_now) const
683 {
684         if (use_isdcf_name()) {
685                 return isdcf_name (if_created_now);
686         }
687
688         return name();
689 }
690
691 void
692 Film::set_directory (boost::filesystem::path d)
693 {
694         _directory = d;
695         _dirty = true;
696 }
697
698 void
699 Film::set_name (string n)
700 {
701         _name = n;
702         signal_changed (NAME);
703 }
704
705 void
706 Film::set_use_isdcf_name (bool u)
707 {
708         _use_isdcf_name = u;
709         signal_changed (USE_ISDCF_NAME);
710 }
711
712 void
713 Film::set_dcp_content_type (DCPContentType const * t)
714 {
715         _dcp_content_type = t;
716         signal_changed (DCP_CONTENT_TYPE);
717 }
718
719 void
720 Film::set_container (Ratio const * c)
721 {
722         _container = c;
723         signal_changed (CONTAINER);
724 }
725
726 void
727 Film::set_resolution (Resolution r)
728 {
729         _resolution = r;
730         signal_changed (RESOLUTION);
731 }
732
733 void
734 Film::set_j2k_bandwidth (int b)
735 {
736         _j2k_bandwidth = b;
737         signal_changed (J2K_BANDWIDTH);
738 }
739
740 void
741 Film::set_isdcf_metadata (ISDCFMetadata m)
742 {
743         _isdcf_metadata = m;
744         signal_changed (ISDCF_METADATA);
745 }
746
747 void
748 Film::set_video_frame_rate (int f)
749 {
750         _video_frame_rate = f;
751         signal_changed (VIDEO_FRAME_RATE);
752 }
753
754 void
755 Film::set_audio_channels (int c)
756 {
757         _audio_channels = c;
758         signal_changed (AUDIO_CHANNELS);
759 }
760
761 void
762 Film::set_three_d (bool t)
763 {
764         _three_d = t;
765         signal_changed (THREE_D);
766 }
767
768 void
769 Film::set_interop (bool i)
770 {
771         _interop = i;
772         signal_changed (INTEROP);
773 }
774
775 void
776 Film::set_burn_subtitles (bool b)
777 {
778         _burn_subtitles = b;
779         signal_changed (BURN_SUBTITLES);
780 }
781
782 void
783 Film::signal_changed (Property p)
784 {
785         _dirty = true;
786
787         switch (p) {
788         case Film::CONTENT:
789                 set_video_frame_rate (_playlist->best_dcp_frame_rate ());
790                 break;
791         case Film::VIDEO_FRAME_RATE:
792         case Film::SEQUENCE_VIDEO:
793                 _playlist->maybe_sequence_video ();
794                 break;
795         default:
796                 break;
797         }
798
799         if (ui_signaller) {
800                 ui_signaller->emit (boost::bind (boost::ref (Changed), p));
801         }
802 }
803
804 void
805 Film::set_isdcf_date_today ()
806 {
807         _isdcf_date = boost::gregorian::day_clock::local_day ();
808 }
809
810 boost::filesystem::path
811 Film::info_path (int f, Eyes e) const
812 {
813         boost::filesystem::path p;
814         p /= info_dir ();
815
816         SafeStringStream s;
817         s.width (8);
818         s << setfill('0') << f;
819
820         if (e == EYES_LEFT) {
821                 s << ".L";
822         } else if (e == EYES_RIGHT) {
823                 s << ".R";
824         }
825
826         s << ".md5";
827         
828         p /= s.str();
829
830         /* info_dir() will already have added any initial bit of the path,
831            so don't call file() on this.
832         */
833         return p;
834 }
835
836 boost::filesystem::path
837 Film::j2c_path (int f, Eyes e, bool t) const
838 {
839         boost::filesystem::path p;
840         p /= "j2c";
841         p /= video_identifier ();
842
843         SafeStringStream s;
844         s.width (8);
845         s << setfill('0') << f;
846
847         if (e == EYES_LEFT) {
848                 s << ".L";
849         } else if (e == EYES_RIGHT) {
850                 s << ".R";
851         }
852         
853         s << ".j2c";
854
855         if (t) {
856                 s << ".tmp";
857         }
858
859         p /= s.str();
860         return file (p);
861 }
862
863 /** Find all the DCPs in our directory that can be dcp::DCP::read() and return details of their CPLs */
864 vector<CPLSummary>
865 Film::cpls () const
866 {
867         vector<CPLSummary> out;
868         
869         boost::filesystem::path const dir = directory ();
870         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator(dir); i != boost::filesystem::directory_iterator(); ++i) {
871                 if (
872                         boost::filesystem::is_directory (*i) &&
873                         i->path().leaf() != "j2c" && i->path().leaf() != "video" && i->path().leaf() != "info" && i->path().leaf() != "analysis"
874                         ) {
875
876                         try {
877                                 dcp::DCP dcp (*i);
878                                 dcp.read ();
879                                 out.push_back (
880                                         CPLSummary (
881                                                 i->path().leaf().string(),
882                                                 dcp.cpls().front()->id(),
883                                                 dcp.cpls().front()->annotation_text(),
884                                                 dcp.cpls().front()->file()
885                                                 )
886                                         );
887                         } catch (...) {
888
889                         }
890                 }
891         }
892         
893         return out;
894 }
895
896 shared_ptr<Player>
897 Film::make_player () const
898 {
899         return shared_ptr<Player> (new Player (shared_from_this (), _playlist));
900 }
901
902 void
903 Film::set_signed (bool s)
904 {
905         _signed = s;
906         signal_changed (SIGNED);
907 }
908
909 void
910 Film::set_encrypted (bool e)
911 {
912         _encrypted = e;
913         signal_changed (ENCRYPTED);
914 }
915
916 shared_ptr<Playlist>
917 Film::playlist () const
918 {
919         return _playlist;
920 }
921
922 ContentList
923 Film::content () const
924 {
925         return _playlist->content ();
926 }
927
928 void
929 Film::examine_content (shared_ptr<Content> c)
930 {
931         shared_ptr<Job> j (new ExamineContentJob (shared_from_this(), c));
932         JobManager::instance()->add (j);
933 }
934
935 void
936 Film::examine_and_add_content (shared_ptr<Content> c)
937 {
938         if (dynamic_pointer_cast<FFmpegContent> (c)) {
939                 run_ffprobe (c->path(0), file ("ffprobe.log"), _log);
940         }
941                         
942         shared_ptr<Job> j (new ExamineContentJob (shared_from_this(), c));
943
944         _job_connections.push_back (
945                 j->Finished.connect (bind (&Film::maybe_add_content, this, boost::weak_ptr<Job> (j), boost::weak_ptr<Content> (c)))
946                 );
947         
948         JobManager::instance()->add (j);
949 }
950
951 void
952 Film::maybe_add_content (weak_ptr<Job> j, weak_ptr<Content> c)
953 {
954         shared_ptr<Job> job = j.lock ();
955         if (!job || !job->finished_ok ()) {
956                 return;
957         }
958         
959         shared_ptr<Content> content = c.lock ();
960         if (content) {
961                 add_content (content);
962         }
963 }
964
965 void
966 Film::add_content (shared_ptr<Content> c)
967 {
968         /* Add video content after any existing content */
969         if (dynamic_pointer_cast<VideoContent> (c)) {
970                 c->set_position (_playlist->video_end ());
971         }
972
973         _playlist->add (c);
974 }
975
976 void
977 Film::remove_content (shared_ptr<Content> c)
978 {
979         _playlist->remove (c);
980 }
981
982 void
983 Film::move_content_earlier (shared_ptr<Content> c)
984 {
985         _playlist->move_earlier (c);
986 }
987
988 void
989 Film::move_content_later (shared_ptr<Content> c)
990 {
991         _playlist->move_later (c);
992 }
993
994 DCPTime
995 Film::length () const
996 {
997         return _playlist->length ();
998 }
999
1000 int
1001 Film::best_video_frame_rate () const
1002 {
1003         return _playlist->best_dcp_frame_rate ();
1004 }
1005
1006 FrameRateChange
1007 Film::active_frame_rate_change (DCPTime t) const
1008 {
1009         return _playlist->active_frame_rate_change (t, video_frame_rate ());
1010 }
1011
1012 void
1013 Film::playlist_content_changed (boost::weak_ptr<Content> c, int p)
1014 {
1015         if (p == VideoContentProperty::VIDEO_FRAME_RATE) {
1016                 set_video_frame_rate (_playlist->best_dcp_frame_rate ());
1017         } 
1018
1019         if (ui_signaller) {
1020                 ui_signaller->emit (boost::bind (boost::ref (ContentChanged), c, p));
1021         }
1022 }
1023
1024 void
1025 Film::playlist_changed ()
1026 {
1027         signal_changed (CONTENT);
1028 }       
1029
1030 int
1031 Film::audio_frame_rate () const
1032 {
1033         /* XXX */
1034         return 48000;
1035 }
1036
1037 void
1038 Film::set_sequence_video (bool s)
1039 {
1040         _sequence_video = s;
1041         _playlist->set_sequence_video (s);
1042         signal_changed (SEQUENCE_VIDEO);
1043 }
1044
1045 /** @return Size of the largest possible image in whatever resolution we are using */
1046 dcp::Size
1047 Film::full_frame () const
1048 {
1049         switch (_resolution) {
1050         case RESOLUTION_2K:
1051                 return dcp::Size (2048, 1080);
1052         case RESOLUTION_4K:
1053                 return dcp::Size (4096, 2160);
1054         }
1055
1056         DCPOMATIC_ASSERT (false);
1057         return dcp::Size ();
1058 }
1059
1060 /** @return Size of the frame */
1061 dcp::Size
1062 Film::frame_size () const
1063 {
1064         return fit_ratio_within (container()->ratio(), full_frame (), 1);
1065 }
1066
1067 dcp::EncryptedKDM
1068 Film::make_kdm (
1069         dcp::Certificate target,
1070         boost::filesystem::path cpl_file,
1071         dcp::LocalTime from,
1072         dcp::LocalTime until,
1073         dcp::Formulation formulation
1074         ) const
1075 {
1076         shared_ptr<const dcp::CPL> cpl (new dcp::CPL (cpl_file));
1077         shared_ptr<const dcp::Signer> signer = Config::instance()->signer();
1078         if (!signer->valid ()) {
1079                 throw InvalidSignerError ();
1080         }
1081         
1082         return dcp::DecryptedKDM (
1083                 cpl, key(), from, until, "DCP-o-matic", cpl->content_title_text(), dcp::LocalTime().as_string()
1084                 ).encrypt (signer, target, formulation);
1085 }
1086
1087 list<dcp::EncryptedKDM>
1088 Film::make_kdms (
1089         list<shared_ptr<Screen> > screens,
1090         boost::filesystem::path dcp,
1091         dcp::LocalTime from,
1092         dcp::LocalTime until,
1093         dcp::Formulation formulation
1094         ) const
1095 {
1096         list<dcp::EncryptedKDM> kdms;
1097
1098         for (list<shared_ptr<Screen> >::iterator i = screens.begin(); i != screens.end(); ++i) {
1099                 if ((*i)->certificate) {
1100                         kdms.push_back (make_kdm ((*i)->certificate.get(), dcp, from, until, formulation));
1101                 }
1102         }
1103
1104         return kdms;
1105 }
1106
1107 /** @return The approximate disk space required to encode a DCP of this film with the
1108  *  current settings, in bytes.
1109  */
1110 uint64_t
1111 Film::required_disk_space () const
1112 {
1113         return uint64_t (j2k_bandwidth() / 8) * length().seconds();
1114 }
1115
1116 /** This method checks the disk that the Film is on and tries to decide whether or not
1117  *  there will be enough space to make a DCP for it.  If so, true is returned; if not,
1118  *  false is returned and required and availabe are filled in with the amount of disk space
1119  *  required and available respectively (in Gb).
1120  *
1121  *  Note: the decision made by this method isn't, of course, 100% reliable.
1122  */
1123 bool
1124 Film::should_be_enough_disk_space (double& required, double& available) const
1125 {
1126         boost::filesystem::space_info s = boost::filesystem::space (internal_video_mxf_dir ());
1127         required = double (required_disk_space ()) / 1073741824.0f;
1128         available = double (s.available) / 1073741824.0f;
1129         return (available - required) > 1;
1130 }
1131
1132 string
1133 Film::subtitle_language () const
1134 {
1135         set<string> languages;
1136         
1137         ContentList cl = content ();
1138         BOOST_FOREACH (shared_ptr<Content>& c, cl) {
1139                 shared_ptr<SubtitleContent> sc = dynamic_pointer_cast<SubtitleContent> (c);
1140                 if (sc) {
1141                         languages.insert (sc->subtitle_language ());
1142                 }
1143         }
1144
1145         string all;
1146         BOOST_FOREACH (string s, languages) {
1147                 if (!all.empty ()) {
1148                         all += "/" + s;
1149                 } else {
1150                         all += s;
1151                 }
1152         }
1153
1154         return all;
1155 }