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