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