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