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