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