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