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