Merge branch '2.0' of git.carlh.net:git/dcpomatic into 2.0
[dcpomatic.git] / src / lib / film.cc
1 /*
2     Copyright (C) 2012-2014 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 #include "film.h"
21 #include "job.h"
22 #include "util.h"
23 #include "job_manager.h"
24 #include "transcode_job.h"
25 #include "scp_dcp_job.h"
26 #include "log.h"
27 #include "exceptions.h"
28 #include "examine_content_job.h"
29 #include "scaler.h"
30 #include "config.h"
31 #include "version.h"
32 #include "ui_signaller.h"
33 #include "playlist.h"
34 #include "player.h"
35 #include "dcp_content_type.h"
36 #include "ratio.h"
37 #include "cross.h"
38 #include "cinema.h"
39 #include "safe_stringstream.h"
40 #include <libcxml/cxml.h>
41 #include <dcp/cpl.h>
42 #include <dcp/signer.h>
43 #include <dcp/util.h>
44 #include <dcp/local_time.h>
45 #include <dcp/raw_convert.h>
46 #include <dcp/decrypted_kdm.h>
47 #include <libxml++/libxml++.h>
48 #include <boost/filesystem.hpp>
49 #include <boost/algorithm/string.hpp>
50 #include <boost/lexical_cast.hpp>
51 #include <unistd.h>
52 #include <stdexcept>
53 #include <iostream>
54 #include <algorithm>
55 #include <fstream>
56 #include <cstdlib>
57 #include <iomanip>
58
59
60 #include "i18n.h"
61
62 using std::string;
63 using std::multimap;
64 using std::pair;
65 using std::map;
66 using std::vector;
67 using std::setfill;
68 using std::min;
69 using std::make_pair;
70 using std::endl;
71 using std::cout;
72 using std::list;
73 using boost::shared_ptr;
74 using boost::weak_ptr;
75 using boost::dynamic_pointer_cast;
76 using boost::to_upper_copy;
77 using boost::ends_with;
78 using boost::starts_with;
79 using boost::optional;
80 using boost::is_any_of;
81 using dcp::Size;
82 using dcp::Signer;
83 using dcp::raw_convert;
84 using dcp::raw_convert;
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         , _scaler (Scaler::from_id ("bicubic"))
117         , _signed (true)
118         , _encrypted (false)
119         , _j2k_bandwidth (Config::instance()->default_j2k_bandwidth ())
120         , _isdcf_metadata (Config::instance()->default_isdcf_metadata ())
121         , _video_frame_rate (24)
122         , _audio_channels (6)
123         , _three_d (false)
124         , _sequence_video (true)
125         , _interop (false)
126         , _burn_subtitles (false)
127         , _state_version (current_state_version)
128         , _dirty (false)
129 {
130         set_isdcf_date_today ();
131
132         _playlist->Changed.connect (bind (&Film::playlist_changed, this));
133         _playlist->ContentChanged.connect (bind (&Film::playlist_content_changed, this, _1, _2));
134         
135         /* Make state.directory a complete path without ..s (where possible)
136            (Code swiped from Adam Bowen on stackoverflow)
137         */
138         
139         boost::filesystem::path p (boost::filesystem::system_complete (dir));
140         boost::filesystem::path result;
141         for (boost::filesystem::path::iterator i = p.begin(); i != p.end(); ++i) {
142                 if (*i == "..") {
143                         if (boost::filesystem::is_symlink (result) || result.filename() == "..") {
144                                 result /= *i;
145                         } else {
146                                 result = result.parent_path ();
147                         }
148                 } else if (*i != ".") {
149                         result /= *i;
150                 }
151         }
152
153         set_directory (result);
154         if (log) {
155                 _log.reset (new FileLog (file ("log")));
156         } else {
157                 _log.reset (new NullLog);
158         }
159
160         _playlist->set_sequence_video (_sequence_video);
161 }
162
163 string
164 Film::video_identifier () const
165 {
166         assert (container ());
167
168         SafeStringStream s;
169         s.imbue (std::locale::classic ());
170         
171         s << container()->id()
172           << "_" << resolution_to_string (_resolution)
173           << "_" << _playlist->video_identifier()
174           << "_" << _video_frame_rate
175           << "_" << scaler()->id()
176           << "_" << j2k_bandwidth();
177
178         if (encrypted ()) {
179                 s << "_E";
180         } else {
181                 s << "_P";
182         }
183
184         if (_interop) {
185                 s << "_I";
186         } else {
187                 s << "_S";
188         }
189
190         if (_burn_subtitles) {
191                 s << "_B";
192         }
193
194         if (_three_d) {
195                 s << "_3D";
196         }
197
198         return s.str ();
199 }
200           
201 /** @return The path to the directory to write video frame info files to */
202 boost::filesystem::path
203 Film::info_dir () const
204 {
205         boost::filesystem::path p;
206         p /= "info";
207         p /= video_identifier ();
208         return dir (p);
209 }
210
211 boost::filesystem::path
212 Film::internal_video_mxf_dir () const
213 {
214         return dir ("video");
215 }
216
217 boost::filesystem::path
218 Film::internal_video_mxf_filename () const
219 {
220         return video_identifier() + ".mxf";
221 }
222
223 boost::filesystem::path
224 Film::video_mxf_filename () const
225 {
226         return filename_safe_name() + "_video.mxf";
227 }
228
229 boost::filesystem::path
230 Film::audio_mxf_filename () const
231 {
232         return filename_safe_name() + "_audio.mxf";
233 }
234
235 boost::filesystem::path
236 Film::subtitle_xml_filename () const
237 {
238         return filename_safe_name() + "_subtitle.xml";
239 }
240
241 string
242 Film::filename_safe_name () const
243 {
244         string const n = name ();
245         string o;
246         for (size_t i = 0; i < n.length(); ++i) {
247                 if (isalnum (n[i])) {
248                         o += n[i];
249                 } else {
250                         o += "_";
251                 }
252         }
253
254         return o;
255 }
256
257 boost::filesystem::path
258 Film::audio_analysis_dir () const
259 {
260         return dir ("analysis");
261 }
262
263 /** Add suitable Jobs to the JobManager to create a DCP for this Film */
264 void
265 Film::make_dcp ()
266 {
267         set_isdcf_date_today ();
268         
269         if (dcp_name().find ("/") != string::npos) {
270                 throw BadSettingError (_("name"), _("cannot contain slashes"));
271         }
272
273         /* It seems to make sense to auto-save metadata here, since the make DCP may last
274            a long time, and crashes/power failures are moderately likely.
275          */
276         write_metadata ();
277
278         LOG_GENERAL ("DCP-o-matic %1 git %2 using %3", dcpomatic_version, dcpomatic_git_commit, dependency_version_summary());
279
280         {
281                 char buffer[128];
282                 gethostname (buffer, sizeof (buffer));
283                 LOG_GENERAL ("Starting to make DCP on %1", buffer);
284         }
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 #ifdef DCPOMATIC_DEBUG
294         LOG_GENERAL_NC ("DCP-o-matic built in debug mode.");
295 #else
296         LOG_GENERAL_NC ("DCP-o-matic built in optimised mode.");
297 #endif
298 #ifdef LIBDCP_DEBUG
299         LOG_GENERAL_NC ("libdcp built in debug mode.");
300 #else
301         LOG_GENERAL_NC ("libdcp built in optimised mode.");
302 #endif
303
304 #ifdef DCPOMATIC_WINDOWS
305         OSVERSIONINFO info;
306         info.dwOSVersionInfoSize = sizeof (info);
307         GetVersionEx (&info);
308         LOG_GENERAL ("Windows version %1.%2.%3 SP %4", info.dwMajorVersion, info.dwMinorVersion, info.dwBuildNumber, info.szCSDVersion);
309 #endif  
310         
311         LOG_GENERAL ("CPU: %1, %2 processors", cpu_info(), boost::thread::hardware_concurrency ());
312         list<pair<string, string> > const m = mount_info ();
313         for (list<pair<string, string> >::const_iterator i = m.begin(); i != m.end(); ++i) {
314                 LOG_GENERAL ("Mount: %1 %2", i->first, i->second);
315         }
316         
317         if (container() == 0) {
318                 throw MissingSettingError (_("container"));
319         }
320
321         if (content().empty()) {
322                 throw StringError (_("You must add some content to the DCP before creating it"));
323         }
324
325         if (dcp_content_type() == 0) {
326                 throw MissingSettingError (_("content type"));
327         }
328
329         if (name().empty()) {
330                 throw MissingSettingError (_("name"));
331         }
332
333         JobManager::instance()->add (shared_ptr<Job> (new TranscodeJob (shared_from_this())));
334 }
335
336 /** Start a job to send our DCP to the configured TMS */
337 void
338 Film::send_dcp_to_tms ()
339 {
340         shared_ptr<Job> j (new SCPDCPJob (shared_from_this()));
341         JobManager::instance()->add (j);
342 }
343
344 /** Count the number of frames that have been encoded for this film.
345  *  @return frame count.
346  */
347 int
348 Film::encoded_frames () const
349 {
350         if (container() == 0) {
351                 return 0;
352         }
353
354         int N = 0;
355         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator (info_dir ()); i != boost::filesystem::directory_iterator(); ++i) {
356                 ++N;
357                 boost::this_thread::interruption_point ();
358         }
359
360         return N;
361 }
362
363 shared_ptr<xmlpp::Document>
364 Film::metadata () const
365 {
366         shared_ptr<xmlpp::Document> doc (new xmlpp::Document);
367         xmlpp::Element* root = doc->create_root_node ("Metadata");
368
369         root->add_child("Version")->add_child_text (raw_convert<string> (current_state_version));
370         root->add_child("Name")->add_child_text (_name);
371         root->add_child("UseISDCFName")->add_child_text (_use_isdcf_name ? "1" : "0");
372
373         if (_dcp_content_type) {
374                 root->add_child("DCPContentType")->add_child_text (_dcp_content_type->isdcf_name ());
375         }
376
377         if (_container) {
378                 root->add_child("Container")->add_child_text (_container->id ());
379         }
380
381         root->add_child("Resolution")->add_child_text (resolution_to_string (_resolution));
382         root->add_child("Scaler")->add_child_text (_scaler->id ());
383         root->add_child("J2KBandwidth")->add_child_text (raw_convert<string> (_j2k_bandwidth));
384         _isdcf_metadata.as_xml (root->add_child ("ISDCFMetadata"));
385         root->add_child("VideoFrameRate")->add_child_text (raw_convert<string> (_video_frame_rate));
386         root->add_child("ISDCFDate")->add_child_text (boost::gregorian::to_iso_string (_isdcf_date));
387         root->add_child("AudioChannels")->add_child_text (raw_convert<string> (_audio_channels));
388         root->add_child("ThreeD")->add_child_text (_three_d ? "1" : "0");
389         root->add_child("SequenceVideo")->add_child_text (_sequence_video ? "1" : "0");
390         root->add_child("Interop")->add_child_text (_interop ? "1" : "0");
391         root->add_child("BurnSubtitles")->add_child_text (_burn_subtitles ? "1" : "0");
392         root->add_child("Signed")->add_child_text (_signed ? "1" : "0");
393         root->add_child("Encrypted")->add_child_text (_encrypted ? "1" : "0");
394         root->add_child("Key")->add_child_text (_key.hex ());
395         _playlist->as_xml (root->add_child ("Playlist"));
396
397         return doc;
398 }
399
400 /** Write state to our `metadata' file */
401 void
402 Film::write_metadata () const
403 {
404         boost::filesystem::create_directories (directory ());
405         shared_ptr<xmlpp::Document> doc = metadata ();
406         doc->write_to_file_formatted (file("metadata.xml").string ());
407         _dirty = false;
408 }
409
410 /** Read state from our metadata file.
411  *  @return Notes about things that the user should know about, or empty.
412  */
413 list<string>
414 Film::read_metadata ()
415 {
416         if (boost::filesystem::exists (file ("metadata")) && !boost::filesystem::exists (file ("metadata.xml"))) {
417                 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!"));
418         }
419
420         cxml::Document f ("Metadata");
421         f.read_file (file ("metadata.xml"));
422
423         _state_version = f.number_child<int> ("Version");
424         if (_state_version > current_state_version) {
425                 throw StringError (_("This film was created with a newer version of DCP-o-matic, and it cannot be loaded into this version.  Sorry!"));
426         }
427         
428         _name = f.string_child ("Name");
429         if (_state_version >= 9) {
430                 _use_isdcf_name = f.bool_child ("UseISDCFName");
431                 _isdcf_metadata = ISDCFMetadata (f.node_child ("ISDCFMetadata"));
432                 _isdcf_date = boost::gregorian::from_undelimited_string (f.string_child ("ISDCFDate"));
433         } else {
434                 _use_isdcf_name = f.bool_child ("UseDCIName");
435                 _isdcf_metadata = ISDCFMetadata (f.node_child ("DCIMetadata"));
436                 _isdcf_date = boost::gregorian::from_undelimited_string (f.string_child ("DCIDate"));
437         }
438
439         {
440                 optional<string> c = f.optional_string_child ("DCPContentType");
441                 if (c) {
442                         _dcp_content_type = DCPContentType::from_isdcf_name (c.get ());
443                 }
444         }
445
446         {
447                 optional<string> c = f.optional_string_child ("Container");
448                 if (c) {
449                         _container = Ratio::from_id (c.get ());
450                 }
451         }
452
453         _resolution = string_to_resolution (f.string_child ("Resolution"));
454         _scaler = Scaler::from_id (f.string_child ("Scaler"));
455         _j2k_bandwidth = f.number_child<int> ("J2KBandwidth");
456         _video_frame_rate = f.number_child<int> ("VideoFrameRate");
457         _signed = f.optional_bool_child("Signed").get_value_or (true);
458         _encrypted = f.bool_child ("Encrypted");
459         _audio_channels = f.number_child<int> ("AudioChannels");
460         _sequence_video = f.bool_child ("SequenceVideo");
461         _three_d = f.bool_child ("ThreeD");
462         _interop = f.bool_child ("Interop");
463         if (_state_version >= 32) {
464                 _burn_subtitles = f.bool_child ("BurnSubtitles");
465         }
466         _key = dcp::Key (f.string_child ("Key"));
467
468         list<string> notes;
469         /* This method is the only one that can return notes (so far) */
470         _playlist->set_from_xml (shared_from_this(), f.node_child ("Playlist"), _state_version, notes);
471
472         /* Write backtraces to this film's directory, until another film is loaded */
473         set_backtrace_file (file ("backtrace.txt"));
474
475         _dirty = false;
476         return notes;
477 }
478
479 /** Given a directory name, return its full path within the Film's directory.
480  *  The directory (and its parents) will be created if they do not exist.
481  */
482 boost::filesystem::path
483 Film::dir (boost::filesystem::path d) const
484 {
485         boost::filesystem::path p;
486         p /= _directory;
487         p /= d;
488         
489         boost::filesystem::create_directories (p);
490         
491         return p;
492 }
493
494 /** Given a file or directory name, return its full path within the Film's directory.
495  *  Any required parent directories will be created.
496  */
497 boost::filesystem::path
498 Film::file (boost::filesystem::path f) const
499 {
500         boost::filesystem::path p;
501         p /= _directory;
502         p /= f;
503
504         boost::filesystem::create_directories (p.parent_path ());
505         
506         return p;
507 }
508
509 /** @return a ISDCF-compliant name for a DCP of this film */
510 string
511 Film::isdcf_name (bool if_created_now) const
512 {
513         SafeStringStream d;
514
515         string raw_name = name ();
516
517         /* Split the raw name up into words */
518         vector<string> words;
519         split (words, raw_name, is_any_of (" "));
520
521         string fixed_name;
522         
523         /* Add each word to fixed_name */
524         for (vector<string>::const_iterator i = words.begin(); i != words.end(); ++i) {
525                 string w = *i;
526
527                 /* First letter is always capitalised */
528                 w[0] = toupper (w[0]);
529
530                 /* Count caps in w */
531                 size_t caps = 0;
532                 for (size_t i = 0; i < w.size(); ++i) {
533                         if (isupper (w[i])) {
534                                 ++caps;
535                         }
536                 }
537                 
538                 /* If w is all caps make the rest of it lower case, otherwise
539                    leave it alone.
540                 */
541                 if (caps == w.size ()) {
542                         for (size_t i = 1; i < w.size(); ++i) {
543                                 w[i] = tolower (w[i]);
544                         }
545                 }
546
547                 for (size_t i = 0; i < w.size(); ++i) {
548                         fixed_name += w[i];
549                 }
550         }
551
552         if (fixed_name.length() > 14) {
553                 fixed_name = fixed_name.substr (0, 14);
554         }
555
556         d << fixed_name;
557
558         if (dcp_content_type()) {
559                 d << "_" << dcp_content_type()->isdcf_name();
560                 d << "-" << isdcf_metadata().content_version;
561         }
562
563         ISDCFMetadata const dm = isdcf_metadata ();
564
565         if (dm.temp_version) {
566                 d << "-Temp";
567         }
568         
569         if (dm.pre_release) {
570                 d << "-Pre";
571         }
572         
573         if (dm.red_band) {
574                 d << "-RedBand";
575         }
576         
577         if (!dm.chain.empty ()) {
578                 d << "-" << dm.chain;
579         }
580
581         if (three_d ()) {
582                 d << "-3D";
583         }
584
585         if (dm.two_d_version_of_three_d) {
586                 d << "-2D";
587         }
588
589         if (!dm.mastered_luminance.empty ()) {
590                 d << "-" << dm.mastered_luminance;
591         }
592
593         if (video_frame_rate() != 24) {
594                 d << "-" << video_frame_rate();
595         }
596         
597         if (container()) {
598                 d << "_" << container()->isdcf_name();
599         }
600
601         /* XXX: this uses the first bit of content only */
602
603         /* The standard says we don't do this for trailers, for some strange reason */
604         if (dcp_content_type() && dcp_content_type()->libdcp_kind() != dcp::TRAILER) {
605                 ContentList cl = content ();
606                 Ratio const * content_ratio = 0;
607                 for (ContentList::iterator i = cl.begin(); i != cl.end(); ++i) {
608                         shared_ptr<VideoContent> vc = dynamic_pointer_cast<VideoContent> (*i);
609                         if (vc) {
610                                 /* Here's the first piece of video content */
611                                 if (vc->scale().ratio ()) {
612                                         content_ratio = vc->scale().ratio ();
613                                 } else {
614                                         content_ratio = Ratio::from_ratio (vc->video_size().ratio ());
615                                 }
616                                 break;
617                         }
618                 }
619                 
620                 if (content_ratio && content_ratio != container()) {
621                         d << "-" << content_ratio->isdcf_name();
622                 }
623         }
624
625         if (!dm.audio_language.empty ()) {
626                 d << "_" << dm.audio_language;
627                 if (!dm.subtitle_language.empty()) {
628                         d << "-" << dm.subtitle_language;
629                 } else {
630                         d << "-XX";
631                 }
632         }
633
634         if (!dm.territory.empty ()) {
635                 d << "_" << dm.territory;
636                 if (!dm.rating.empty ()) {
637                         d << "-" << dm.rating;
638                 }
639         }
640
641         switch (audio_channels ()) {
642         case 1:
643                 d << "_10";
644                 break;
645         case 2:
646                 d << "_20";
647                 break;
648         case 3:
649                 d << "_30";
650                 break;
651         case 4:
652                 d << "_40";
653                 break;
654         case 5:
655                 d << "_50";
656                 break;
657         case 6:
658                 d << "_51";
659                 break;
660         }
661
662         /* XXX: HI/VI */
663
664         d << "_" << resolution_to_string (_resolution);
665         
666         if (!dm.studio.empty ()) {
667                 d << "_" << dm.studio;
668         }
669
670         if (if_created_now) {
671                 d << "_" << boost::gregorian::to_iso_string (boost::gregorian::day_clock::local_day ());
672         } else {
673                 d << "_" << boost::gregorian::to_iso_string (_isdcf_date);
674         }
675
676         if (!dm.facility.empty ()) {
677                 d << "_" << dm.facility;
678         }
679
680         if (_interop) {
681                 d << "_IOP";
682         } else {
683                 d << "_SMPTE";
684         }
685         
686         if (three_d ()) {
687                 d << "-3D";
688         }
689
690         if (!dm.package_type.empty ()) {
691                 d << "_" << dm.package_type;
692         }
693
694         return d.str ();
695 }
696
697 /** @return name to give the DCP */
698 string
699 Film::dcp_name (bool if_created_now) const
700 {
701         if (use_isdcf_name()) {
702                 return isdcf_name (if_created_now);
703         }
704
705         return name();
706 }
707
708 void
709 Film::set_directory (boost::filesystem::path d)
710 {
711         _directory = d;
712         _dirty = true;
713 }
714
715 void
716 Film::set_name (string n)
717 {
718         _name = n;
719         signal_changed (NAME);
720 }
721
722 void
723 Film::set_use_isdcf_name (bool u)
724 {
725         _use_isdcf_name = u;
726         signal_changed (USE_ISDCF_NAME);
727 }
728
729 void
730 Film::set_dcp_content_type (DCPContentType const * t)
731 {
732         _dcp_content_type = t;
733         signal_changed (DCP_CONTENT_TYPE);
734 }
735
736 void
737 Film::set_container (Ratio const * c)
738 {
739         _container = c;
740         signal_changed (CONTAINER);
741 }
742
743 void
744 Film::set_resolution (Resolution r)
745 {
746         _resolution = r;
747         signal_changed (RESOLUTION);
748 }
749
750 void
751 Film::set_scaler (Scaler const * s)
752 {
753         _scaler = s;
754         signal_changed (SCALER);
755 }
756
757 void
758 Film::set_j2k_bandwidth (int b)
759 {
760         _j2k_bandwidth = b;
761         signal_changed (J2K_BANDWIDTH);
762 }
763
764 void
765 Film::set_isdcf_metadata (ISDCFMetadata m)
766 {
767         _isdcf_metadata = m;
768         signal_changed (ISDCF_METADATA);
769 }
770
771 void
772 Film::set_video_frame_rate (int f)
773 {
774         _video_frame_rate = f;
775         signal_changed (VIDEO_FRAME_RATE);
776 }
777
778 void
779 Film::set_audio_channels (int c)
780 {
781         _audio_channels = c;
782         signal_changed (AUDIO_CHANNELS);
783 }
784
785 void
786 Film::set_three_d (bool t)
787 {
788         _three_d = t;
789         signal_changed (THREE_D);
790 }
791
792 void
793 Film::set_interop (bool i)
794 {
795         _interop = i;
796         signal_changed (INTEROP);
797 }
798
799 void
800 Film::set_burn_subtitles (bool b)
801 {
802         _burn_subtitles = b;
803         signal_changed (BURN_SUBTITLES);
804 }
805
806 void
807 Film::signal_changed (Property p)
808 {
809         _dirty = true;
810
811         switch (p) {
812         case Film::CONTENT:
813                 set_video_frame_rate (_playlist->best_dcp_frame_rate ());
814                 break;
815         case Film::VIDEO_FRAME_RATE:
816         case Film::SEQUENCE_VIDEO:
817                 _playlist->maybe_sequence_video ();
818                 break;
819         default:
820                 break;
821         }
822
823         if (ui_signaller) {
824                 ui_signaller->emit (boost::bind (boost::ref (Changed), p));
825         }
826 }
827
828 void
829 Film::set_isdcf_date_today ()
830 {
831         _isdcf_date = boost::gregorian::day_clock::local_day ();
832 }
833
834 boost::filesystem::path
835 Film::info_path (int f, Eyes e) const
836 {
837         boost::filesystem::path p;
838         p /= info_dir ();
839
840         SafeStringStream s;
841         s.width (8);
842         s << setfill('0') << f;
843
844         if (e == EYES_LEFT) {
845                 s << ".L";
846         } else if (e == EYES_RIGHT) {
847                 s << ".R";
848         }
849
850         s << ".md5";
851         
852         p /= s.str();
853
854         /* info_dir() will already have added any initial bit of the path,
855            so don't call file() on this.
856         */
857         return p;
858 }
859
860 boost::filesystem::path
861 Film::j2c_path (int f, Eyes e, bool t) const
862 {
863         boost::filesystem::path p;
864         p /= "j2c";
865         p /= video_identifier ();
866
867         SafeStringStream s;
868         s.width (8);
869         s << setfill('0') << f;
870
871         if (e == EYES_LEFT) {
872                 s << ".L";
873         } else if (e == EYES_RIGHT) {
874                 s << ".R";
875         }
876         
877         s << ".j2c";
878
879         if (t) {
880                 s << ".tmp";
881         }
882
883         p /= s.str();
884         return file (p);
885 }
886
887 /** Find all the DCPs in our directory that can be dcp::DCP::read() and return details of their CPLs */
888 vector<CPLSummary>
889 Film::cpls () const
890 {
891         vector<CPLSummary> out;
892         
893         boost::filesystem::path const dir = directory ();
894         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator(dir); i != boost::filesystem::directory_iterator(); ++i) {
895                 if (
896                         boost::filesystem::is_directory (*i) &&
897                         i->path().leaf() != "j2c" && i->path().leaf() != "video" && i->path().leaf() != "info" && i->path().leaf() != "analysis"
898                         ) {
899
900                         try {
901                                 dcp::DCP dcp (*i);
902                                 dcp.read ();
903                                 out.push_back (
904                                         CPLSummary (
905                                                 i->path().leaf().string(),
906                                                 dcp.cpls().front()->id(),
907                                                 dcp.cpls().front()->annotation_text(),
908                                                 dcp.cpls().front()->file()
909                                                 )
910                                         );
911                         } catch (...) {
912
913                         }
914                 }
915         }
916         
917         return out;
918 }
919
920 shared_ptr<Player>
921 Film::make_player () const
922 {
923         return shared_ptr<Player> (new Player (shared_from_this (), _playlist));
924 }
925
926 void
927 Film::set_signed (bool s)
928 {
929         _signed = s;
930         signal_changed (SIGNED);
931 }
932
933 void
934 Film::set_encrypted (bool e)
935 {
936         _encrypted = e;
937         signal_changed (ENCRYPTED);
938 }
939
940 shared_ptr<Playlist>
941 Film::playlist () const
942 {
943         return _playlist;
944 }
945
946 ContentList
947 Film::content () const
948 {
949         return _playlist->content ();
950 }
951
952 void
953 Film::examine_content (shared_ptr<Content> c, bool calculate_digest)
954 {
955         shared_ptr<Job> j (new ExamineContentJob (shared_from_this(), c, calculate_digest));
956         JobManager::instance()->add (j);
957 }
958
959 void
960 Film::examine_and_add_content (shared_ptr<Content> c, bool calculate_digest)
961 {
962         if (dynamic_pointer_cast<FFmpegContent> (c)) {
963                 run_ffprobe (c->path(0), file ("ffprobe.log"), _log);
964         }
965                         
966         shared_ptr<Job> j (new ExamineContentJob (shared_from_this(), c, calculate_digest));
967         j->Finished.connect (bind (&Film::maybe_add_content, this, boost::weak_ptr<Job> (j), boost::weak_ptr<Content> (c)));
968         JobManager::instance()->add (j);
969 }
970
971 void
972 Film::maybe_add_content (weak_ptr<Job> j, weak_ptr<Content> c)
973 {
974         shared_ptr<Job> job = j.lock ();
975         if (!job || !job->finished_ok ()) {
976                 return;
977         }
978         
979         shared_ptr<Content> content = c.lock ();
980         if (content) {
981                 add_content (content);
982         }
983 }
984
985 void
986 Film::add_content (shared_ptr<Content> c)
987 {
988         /* Add video content after any existing content */
989         if (dynamic_pointer_cast<VideoContent> (c)) {
990                 c->set_position (_playlist->video_end ());
991         }
992
993         _playlist->add (c);
994 }
995
996 void
997 Film::remove_content (shared_ptr<Content> c)
998 {
999         _playlist->remove (c);
1000 }
1001
1002 void
1003 Film::move_content_earlier (shared_ptr<Content> c)
1004 {
1005         _playlist->move_earlier (c);
1006 }
1007
1008 void
1009 Film::move_content_later (shared_ptr<Content> c)
1010 {
1011         _playlist->move_later (c);
1012 }
1013
1014 DCPTime
1015 Film::length () const
1016 {
1017         return _playlist->length ();
1018 }
1019
1020 int
1021 Film::best_video_frame_rate () const
1022 {
1023         return _playlist->best_dcp_frame_rate ();
1024 }
1025
1026 FrameRateChange
1027 Film::active_frame_rate_change (DCPTime t) const
1028 {
1029         return _playlist->active_frame_rate_change (t, video_frame_rate ());
1030 }
1031
1032 void
1033 Film::playlist_content_changed (boost::weak_ptr<Content> c, int p)
1034 {
1035         if (p == VideoContentProperty::VIDEO_FRAME_RATE) {
1036                 set_video_frame_rate (_playlist->best_dcp_frame_rate ());
1037         } 
1038
1039         if (ui_signaller) {
1040                 ui_signaller->emit (boost::bind (boost::ref (ContentChanged), c, p));
1041         }
1042 }
1043
1044 void
1045 Film::playlist_changed ()
1046 {
1047         signal_changed (CONTENT);
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         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 }