Include trimming.
[dcpomatic.git] / src / lib / film.cc
1 /*
2     Copyright (C) 2012 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 <sstream>
26 #include <iomanip>
27 #include <unistd.h>
28 #include <boost/filesystem.hpp>
29 #include <boost/algorithm/string.hpp>
30 #include <boost/lexical_cast.hpp>
31 #include <boost/date_time.hpp>
32 #include <libxml++/libxml++.h>
33 #include <libcxml/cxml.h>
34 #include "film.h"
35 #include "job.h"
36 #include "util.h"
37 #include "job_manager.h"
38 #include "transcode_job.h"
39 #include "scp_dcp_job.h"
40 #include "log.h"
41 #include "exceptions.h"
42 #include "examine_content_job.h"
43 #include "scaler.h"
44 #include "config.h"
45 #include "version.h"
46 #include "ui_signaller.h"
47 #include "playlist.h"
48 #include "player.h"
49 #include "dcp_content_type.h"
50 #include "ratio.h"
51 #include "cross.h"
52
53 #include "i18n.h"
54
55 using std::string;
56 using std::stringstream;
57 using std::multimap;
58 using std::pair;
59 using std::map;
60 using std::vector;
61 using std::ifstream;
62 using std::ofstream;
63 using std::setfill;
64 using std::min;
65 using std::make_pair;
66 using std::endl;
67 using std::cout;
68 using std::list;
69 using boost::shared_ptr;
70 using boost::weak_ptr;
71 using boost::lexical_cast;
72 using boost::dynamic_pointer_cast;
73 using boost::to_upper_copy;
74 using boost::ends_with;
75 using boost::starts_with;
76 using boost::optional;
77 using libdcp::Size;
78
79 int const Film::state_version = 4;
80
81 /** Construct a Film object in a given directory.
82  *
83  *  @param d Film directory.
84  */
85
86 Film::Film (string d)
87         : _playlist (new Playlist)
88         , _use_dci_name (true)
89         , _dcp_content_type (Config::instance()->default_dcp_content_type ())
90         , _container (Config::instance()->default_container ())
91         , _scaler (Scaler::from_id ("bicubic"))
92         , _with_subtitles (false)
93         , _j2k_bandwidth (Config::instance()->default_j2k_bandwidth ())
94         , _dci_metadata (Config::instance()->default_dci_metadata ())
95         , _dcp_video_frame_rate (24)
96         , _dcp_audio_channels (MAX_AUDIO_CHANNELS)
97         , _dirty (false)
98 {
99         set_dci_date_today ();
100
101         _playlist->Changed.connect (bind (&Film::playlist_changed, this));
102         _playlist->ContentChanged.connect (bind (&Film::playlist_content_changed, this, _1, _2));
103         
104         /* Make state.directory a complete path without ..s (where possible)
105            (Code swiped from Adam Bowen on stackoverflow)
106         */
107         
108         boost::filesystem::path p (boost::filesystem::system_complete (d));
109         boost::filesystem::path result;
110         for (boost::filesystem::path::iterator i = p.begin(); i != p.end(); ++i) {
111                 if (*i == "..") {
112                         if (boost::filesystem::is_symlink (result) || result.filename() == "..") {
113                                 result /= *i;
114                         } else {
115                                 result = result.parent_path ();
116                         }
117                 } else if (*i != ".") {
118                         result /= *i;
119                 }
120         }
121
122         set_directory (result.string ());
123         _log.reset (new FileLog ("log"));
124 }
125
126 string
127 Film::video_identifier () const
128 {
129         assert (container ());
130         LocaleGuard lg;
131
132         stringstream s;
133         s << container()->id()
134           << "_" << _playlist->video_identifier()
135           << "_" << _dcp_video_frame_rate
136           << "_" << scaler()->id()
137           << "_" << j2k_bandwidth();
138
139         return s.str ();
140 }
141           
142 /** @return The path to the directory to write video frame info files to */
143 string
144 Film::info_dir () const
145 {
146         boost::filesystem::path p;
147         p /= "info";
148         p /= video_identifier ();
149         return dir (p.string());
150 }
151
152 string
153 Film::internal_video_mxf_dir () const
154 {
155         return dir ("video");
156 }
157
158 string
159 Film::internal_video_mxf_filename () const
160 {
161         return video_identifier() + ".mxf";
162 }
163
164 string
165 Film::dcp_video_mxf_filename () const
166 {
167         return filename_safe_name() + "_video.mxf";
168 }
169
170 string
171 Film::dcp_audio_mxf_filename () const
172 {
173         return filename_safe_name() + "_audio.mxf";
174 }
175
176 string
177 Film::filename_safe_name () const
178 {
179         string const n = name ();
180         string o;
181         for (size_t i = 0; i < n.length(); ++i) {
182                 if (isalnum (n[i])) {
183                         o += n[i];
184                 } else {
185                         o += "_";
186                 }
187         }
188
189         return o;
190 }
191
192 boost::filesystem::path
193 Film::audio_analysis_path (shared_ptr<const AudioContent> c) const
194 {
195         boost::filesystem::path p = dir ("analysis");
196         p /= c->digest();
197         return p;
198 }
199
200 /** Add suitable Jobs to the JobManager to create a DCP for this Film */
201 void
202 Film::make_dcp ()
203 {
204         set_dci_date_today ();
205         
206         if (dcp_name().find ("/") != string::npos) {
207                 throw BadSettingError (_("name"), _("cannot contain slashes"));
208         }
209         
210         log()->log (String::compose ("DCP-o-matic %1 git %2 using %3", dcpomatic_version, dcpomatic_git_commit, dependency_version_summary()));
211
212         {
213                 char buffer[128];
214                 gethostname (buffer, sizeof (buffer));
215                 log()->log (String::compose ("Starting to make DCP on %1", buffer));
216         }
217         
218 //      log()->log (String::compose ("Content is %1; type %2", content_path(), (content_type() == STILL ? _("still") : _("video"))));
219 //      if (length()) {
220 //              log()->log (String::compose ("Content length %1", length().get()));
221 //      }
222 //      log()->log (String::compose ("Content digest %1", content_digest()));
223 //      log()->log (String::compose ("Content at %1 fps, DCP at %2 fps", source_frame_rate(), dcp_frame_rate()));
224         log()->log (String::compose ("%1 threads", Config::instance()->num_local_encoding_threads()));
225         log()->log (String::compose ("J2K bandwidth %1", j2k_bandwidth()));
226 #ifdef DCPOMATIC_DEBUG
227         log()->log ("DCP-o-matic built in debug mode.");
228 #else
229         log()->log ("DCP-o-matic built in optimised mode.");
230 #endif
231 #ifdef LIBDCP_DEBUG
232         log()->log ("libdcp built in debug mode.");
233 #else
234         log()->log ("libdcp built in optimised mode.");
235 #endif
236         pair<string, int> const c = cpu_info ();
237         log()->log (String::compose ("CPU: %1, %2 processors", c.first, c.second));
238         list<pair<string, string> > const m = mount_info ();
239         for (list<pair<string, string> >::const_iterator i = m.begin(); i != m.end(); ++i) {
240                 log()->log (String::compose ("Mount: %1 %2", i->first, i->second));
241         }
242         
243         if (container() == 0) {
244                 throw MissingSettingError (_("container"));
245         }
246
247         if (_playlist->content().empty ()) {
248                 throw StringError (_("You must add some content to the DCP before creating it"));
249         }
250
251         if (dcp_content_type() == 0) {
252                 throw MissingSettingError (_("content type"));
253         }
254
255         if (name().empty()) {
256                 throw MissingSettingError (_("name"));
257         }
258
259         JobManager::instance()->add (shared_ptr<Job> (new TranscodeJob (shared_from_this())));
260 }
261
262 /** Start a job to send our DCP to the configured TMS */
263 void
264 Film::send_dcp_to_tms ()
265 {
266         shared_ptr<Job> j (new SCPDCPJob (shared_from_this()));
267         JobManager::instance()->add (j);
268 }
269
270 /** Count the number of frames that have been encoded for this film.
271  *  @return frame count.
272  */
273 int
274 Film::encoded_frames () const
275 {
276         if (container() == 0) {
277                 return 0;
278         }
279
280         int N = 0;
281         for (boost::filesystem::directory_iterator i = boost::filesystem::directory_iterator (info_dir ()); i != boost::filesystem::directory_iterator(); ++i) {
282                 ++N;
283                 boost::this_thread::interruption_point ();
284         }
285
286         return N;
287 }
288
289 /** Write state to our `metadata' file */
290 void
291 Film::write_metadata () const
292 {
293         if (!boost::filesystem::exists (directory())) {
294                 boost::filesystem::create_directory (directory());
295         }
296         
297         boost::mutex::scoped_lock lm (_state_mutex);
298         LocaleGuard lg;
299
300         boost::filesystem::create_directories (directory());
301
302         xmlpp::Document doc;
303         xmlpp::Element* root = doc.create_root_node ("Metadata");
304
305         root->add_child("Version")->add_child_text (lexical_cast<string> (state_version));
306         root->add_child("Name")->add_child_text (_name);
307         root->add_child("UseDCIName")->add_child_text (_use_dci_name ? "1" : "0");
308
309         if (_dcp_content_type) {
310                 root->add_child("DCPContentType")->add_child_text (_dcp_content_type->dci_name ());
311         }
312
313         if (_container) {
314                 root->add_child("Container")->add_child_text (_container->id ());
315         }
316
317         root->add_child("Scaler")->add_child_text (_scaler->id ());
318         root->add_child("WithSubtitles")->add_child_text (_with_subtitles ? "1" : "0");
319         root->add_child("J2KBandwidth")->add_child_text (lexical_cast<string> (_j2k_bandwidth));
320         _dci_metadata.as_xml (root->add_child ("DCIMetadata"));
321         root->add_child("DCPVideoFrameRate")->add_child_text (lexical_cast<string> (_dcp_video_frame_rate));
322         root->add_child("DCIDate")->add_child_text (boost::gregorian::to_iso_string (_dci_date));
323         root->add_child("DCPAudioChannels")->add_child_text (lexical_cast<string> (_dcp_audio_channels));
324         _playlist->as_xml (root->add_child ("Playlist"));
325
326         doc.write_to_file_formatted (file ("metadata.xml"));
327         
328         _dirty = false;
329 }
330
331 /** Read state from our metadata file */
332 void
333 Film::read_metadata ()
334 {
335         boost::mutex::scoped_lock lm (_state_mutex);
336         LocaleGuard lg;
337
338         if (boost::filesystem::exists (file ("metadata")) && !boost::filesystem::exists (file ("metadata.xml"))) {
339                 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!"));
340         }
341
342         cxml::File f (file ("metadata.xml"), "Metadata");
343         
344         _name = f.string_child ("Name");
345         _use_dci_name = f.bool_child ("UseDCIName");
346
347         {
348                 optional<string> c = f.optional_string_child ("DCPContentType");
349                 if (c) {
350                         _dcp_content_type = DCPContentType::from_dci_name (c.get ());
351                 }
352         }
353
354         {
355                 optional<string> c = f.optional_string_child ("Container");
356                 if (c) {
357                         _container = Ratio::from_id (c.get ());
358                 }
359         }
360
361         _scaler = Scaler::from_id (f.string_child ("Scaler"));
362         _with_subtitles = f.bool_child ("WithSubtitles");
363         _j2k_bandwidth = f.number_child<int> ("J2KBandwidth");
364         _dci_metadata = DCIMetadata (f.node_child ("DCIMetadata"));
365         _dcp_video_frame_rate = f.number_child<int> ("DCPVideoFrameRate");
366         _dci_date = boost::gregorian::from_undelimited_string (f.string_child ("DCIDate"));
367         _dcp_audio_channels = f.number_child<int> ("DCPAudioChannels");
368
369         _playlist->set_from_xml (shared_from_this(), f.node_child ("Playlist"));
370
371         _dirty = false;
372 }
373
374 /** Given a directory name, return its full path within the Film's directory.
375  *  The directory (and its parents) will be created if they do not exist.
376  */
377 string
378 Film::dir (string d) const
379 {
380         boost::mutex::scoped_lock lm (_directory_mutex);
381         
382         boost::filesystem::path p;
383         p /= _directory;
384         p /= d;
385         
386         boost::filesystem::create_directories (p);
387         
388         return p.string ();
389 }
390
391 /** Given a file or directory name, return its full path within the Film's directory.
392  *  _directory_mutex must not be locked on entry.
393  *  Any required parent directories will be created.
394  */
395 string
396 Film::file (string f) const
397 {
398         boost::mutex::scoped_lock lm (_directory_mutex);
399
400         boost::filesystem::path p;
401         p /= _directory;
402         p /= f;
403
404         boost::filesystem::create_directories (p.parent_path ());
405         
406         return p.string ();
407 }
408
409 /** @return a DCI-compliant name for a DCP of this film */
410 string
411 Film::dci_name (bool if_created_now) const
412 {
413         stringstream d;
414
415         string fixed_name = to_upper_copy (name());
416         for (size_t i = 0; i < fixed_name.length(); ++i) {
417                 if (fixed_name[i] == ' ') {
418                         fixed_name[i] = '-';
419                 }
420         }
421
422         /* Spec is that the name part should be maximum 14 characters, as I understand it */
423         if (fixed_name.length() > 14) {
424                 fixed_name = fixed_name.substr (0, 14);
425         }
426
427         d << fixed_name;
428
429         if (dcp_content_type()) {
430                 d << "_" << dcp_content_type()->dci_name();
431         }
432
433         if (container()) {
434                 d << "_" << container()->dci_name();
435         }
436
437         DCIMetadata const dm = dci_metadata ();
438
439         if (!dm.audio_language.empty ()) {
440                 d << "_" << dm.audio_language;
441                 if (!dm.subtitle_language.empty()) {
442                         d << "-" << dm.subtitle_language;
443                 } else {
444                         d << "-XX";
445                 }
446         }
447
448         if (!dm.territory.empty ()) {
449                 d << "_" << dm.territory;
450                 if (!dm.rating.empty ()) {
451                         d << "-" << dm.rating;
452                 }
453         }
454
455         d << "_51_2K";
456
457         if (!dm.studio.empty ()) {
458                 d << "_" << dm.studio;
459         }
460
461         if (if_created_now) {
462                 d << "_" << boost::gregorian::to_iso_string (boost::gregorian::day_clock::local_day ());
463         } else {
464                 d << "_" << boost::gregorian::to_iso_string (_dci_date);
465         }
466
467         if (!dm.facility.empty ()) {
468                 d << "_" << dm.facility;
469         }
470
471         if (!dm.package_type.empty ()) {
472                 d << "_" << dm.package_type;
473         }
474
475         return d.str ();
476 }
477
478 /** @return name to give the DCP */
479 string
480 Film::dcp_name (bool if_created_now) const
481 {
482         if (use_dci_name()) {
483                 return dci_name (if_created_now);
484         }
485
486         return name();
487 }
488
489
490 void
491 Film::set_directory (string d)
492 {
493         boost::mutex::scoped_lock lm (_state_mutex);
494         _directory = d;
495         _dirty = true;
496 }
497
498 void
499 Film::set_name (string n)
500 {
501         {
502                 boost::mutex::scoped_lock lm (_state_mutex);
503                 _name = n;
504         }
505         signal_changed (NAME);
506 }
507
508 void
509 Film::set_use_dci_name (bool u)
510 {
511         {
512                 boost::mutex::scoped_lock lm (_state_mutex);
513                 _use_dci_name = u;
514         }
515         signal_changed (USE_DCI_NAME);
516 }
517
518 void
519 Film::set_dcp_content_type (DCPContentType const * t)
520 {
521         {
522                 boost::mutex::scoped_lock lm (_state_mutex);
523                 _dcp_content_type = t;
524         }
525         signal_changed (DCP_CONTENT_TYPE);
526 }
527
528 void
529 Film::set_container (Ratio const * c)
530 {
531         {
532                 boost::mutex::scoped_lock lm (_state_mutex);
533                 _container = c;
534         }
535         signal_changed (CONTAINER);
536 }
537
538 void
539 Film::set_scaler (Scaler const * s)
540 {
541         {
542                 boost::mutex::scoped_lock lm (_state_mutex);
543                 _scaler = s;
544         }
545         signal_changed (SCALER);
546 }
547
548 void
549 Film::set_with_subtitles (bool w)
550 {
551         {
552                 boost::mutex::scoped_lock lm (_state_mutex);
553                 _with_subtitles = w;
554         }
555         signal_changed (WITH_SUBTITLES);
556 }
557
558 void
559 Film::set_j2k_bandwidth (int b)
560 {
561         {
562                 boost::mutex::scoped_lock lm (_state_mutex);
563                 _j2k_bandwidth = b;
564         }
565         signal_changed (J2K_BANDWIDTH);
566 }
567
568 void
569 Film::set_dci_metadata (DCIMetadata m)
570 {
571         {
572                 boost::mutex::scoped_lock lm (_state_mutex);
573                 _dci_metadata = m;
574         }
575         signal_changed (DCI_METADATA);
576 }
577
578 void
579 Film::set_dcp_video_frame_rate (int f)
580 {
581         {
582                 boost::mutex::scoped_lock lm (_state_mutex);
583                 _dcp_video_frame_rate = f;
584         }
585         signal_changed (DCP_VIDEO_FRAME_RATE);
586 }
587
588 void
589 Film::set_dcp_audio_channels (int c)
590 {
591         {
592                 boost::mutex::scoped_lock lm (_state_mutex);
593                 _dcp_audio_channels = c;
594         }
595         signal_changed (DCP_AUDIO_CHANNELS);
596 }
597
598 void
599 Film::signal_changed (Property p)
600 {
601         {
602                 boost::mutex::scoped_lock lm (_state_mutex);
603                 _dirty = true;
604         }
605
606         switch (p) {
607         case Film::CONTENT:
608                 set_dcp_video_frame_rate (_playlist->best_dcp_frame_rate ());
609                 break;
610         case Film::DCP_VIDEO_FRAME_RATE:
611                 _playlist->maybe_sequence_video ();
612                 break;
613         default:
614                 break;
615         }
616
617         if (ui_signaller) {
618                 ui_signaller->emit (boost::bind (boost::ref (Changed), p));
619         }
620 }
621
622 void
623 Film::set_dci_date_today ()
624 {
625         _dci_date = boost::gregorian::day_clock::local_day ();
626 }
627
628 string
629 Film::info_path (int f) const
630 {
631         boost::filesystem::path p;
632         p /= info_dir ();
633
634         stringstream s;
635         s.width (8);
636         s << setfill('0') << f << ".md5";
637
638         p /= s.str();
639
640         /* info_dir() will already have added any initial bit of the path,
641            so don't call file() on this.
642         */
643         return p.string ();
644 }
645
646 string
647 Film::j2c_path (int f, bool t) const
648 {
649         boost::filesystem::path p;
650         p /= "j2c";
651         p /= video_identifier ();
652
653         stringstream s;
654         s.width (8);
655         s << setfill('0') << f << ".j2c";
656
657         if (t) {
658                 s << ".tmp";
659         }
660
661         p /= s.str();
662         return file (p.string ());
663 }
664
665 /** Make an educated guess as to whether we have a complete DCP
666  *  or not.
667  *  @return true if we do.
668  */
669
670 bool
671 Film::have_dcp () const
672 {
673         try {
674                 libdcp::DCP dcp (dir (dcp_name()));
675                 dcp.read ();
676         } catch (...) {
677                 return false;
678         }
679
680         return true;
681 }
682
683 shared_ptr<Player>
684 Film::make_player () const
685 {
686         return shared_ptr<Player> (new Player (shared_from_this (), _playlist));
687 }
688
689 shared_ptr<Playlist>
690 Film::playlist () const
691 {
692         boost::mutex::scoped_lock lm (_state_mutex);
693         return _playlist;
694 }
695
696 Playlist::ContentList
697 Film::content () const
698 {
699         return _playlist->content ();
700 }
701
702 void
703 Film::examine_and_add_content (shared_ptr<Content> c)
704 {
705         shared_ptr<Job> j (new ExamineContentJob (shared_from_this(), c));
706         j->Finished.connect (bind (&Film::add_content_weak, this, boost::weak_ptr<Content> (c)));
707         JobManager::instance()->add (j);
708 }
709
710 void
711 Film::add_content_weak (weak_ptr<Content> c)
712 {
713         shared_ptr<Content> content = c.lock ();
714         if (content) {
715                 add_content (content);
716         }
717 }
718
719 void
720 Film::add_content (shared_ptr<Content> c)
721 {
722         /* Add video content after any existing content */
723         if (dynamic_pointer_cast<VideoContent> (c)) {
724                 c->set_start (_playlist->video_end ());
725         }
726
727         _playlist->add (c);
728 }
729
730 void
731 Film::remove_content (shared_ptr<Content> c)
732 {
733         _playlist->remove (c);
734 }
735
736 Time
737 Film::length () const
738 {
739         return _playlist->length ();
740 }
741
742 bool
743 Film::has_subtitles () const
744 {
745         return _playlist->has_subtitles ();
746 }
747
748 OutputVideoFrame
749 Film::best_dcp_video_frame_rate () const
750 {
751         return _playlist->best_dcp_frame_rate ();
752 }
753
754 void
755 Film::playlist_content_changed (boost::weak_ptr<Content> c, int p)
756 {
757         if (p == VideoContentProperty::VIDEO_FRAME_RATE) {
758                 set_dcp_video_frame_rate (_playlist->best_dcp_frame_rate ());
759         } 
760
761         if (ui_signaller) {
762                 ui_signaller->emit (boost::bind (boost::ref (ContentChanged), c, p));
763         }
764 }
765
766 void
767 Film::playlist_changed ()
768 {
769         signal_changed (CONTENT);
770 }       
771
772 int
773 Film::loop () const
774 {
775         return _playlist->loop ();
776 }
777
778 void
779 Film::set_loop (int c)
780 {
781         _playlist->set_loop (c);
782 }
783
784 OutputAudioFrame
785 Film::time_to_audio_frames (Time t) const
786 {
787         return t * dcp_audio_frame_rate () / TIME_HZ;
788 }
789
790 OutputVideoFrame
791 Film::time_to_video_frames (Time t) const
792 {
793         return t * dcp_video_frame_rate () / TIME_HZ;
794 }
795
796 Time
797 Film::audio_frames_to_time (OutputAudioFrame f) const
798 {
799         return f * TIME_HZ / dcp_audio_frame_rate ();
800 }
801
802 Time
803 Film::video_frames_to_time (OutputVideoFrame f) const
804 {
805         return f * TIME_HZ / dcp_video_frame_rate ();
806 }
807
808 OutputAudioFrame
809 Film::dcp_audio_frame_rate () const
810 {
811         /* XXX */
812         return 48000;
813 }
814
815 void
816 Film::set_sequence_video (bool s)
817 {
818         _playlist->set_sequence_video (s);
819 }
820
821 libdcp::Size
822 Film::full_frame () const
823 {
824         return libdcp::Size (2048, 1080);
825 }