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