9e1640d58661828d2c0d51134beb2c287ec66b8f
[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 "film.h"
32 #include "format.h"
33 #include "imagemagick_encoder.h"
34 #include "job.h"
35 #include "filter.h"
36 #include "transcoder.h"
37 #include "util.h"
38 #include "job_manager.h"
39 #include "ab_transcode_job.h"
40 #include "transcode_job.h"
41 #include "scp_dcp_job.h"
42 #include "copy_from_dvd_job.h"
43 #include "make_dcp_job.h"
44 #include "film_state.h"
45 #include "log.h"
46 #include "options.h"
47 #include "exceptions.h"
48 #include "examine_content_job.h"
49 #include "scaler.h"
50 #include "decoder_factory.h"
51 #include "config.h"
52 #include "check_hashes_job.h"
53 #include "version.h"
54
55 using namespace std;
56 using namespace boost;
57
58 /** Construct a Film object in a given directory, reading any metadata
59  *  file that exists in that directory.  An exception will be thrown if
60  *  must_exist is true, and the specified directory does not exist.
61  *
62  *  @param d Film directory.
63  *  @param must_exist true to throw an exception if does not exist.
64  */
65
66 Film::Film (string d, bool must_exist)
67         : _dirty (false)
68 {
69         /* Make _state.directory a complete path without ..s (where possible)
70            (Code swiped from Adam Bowen on stackoverflow)
71         */
72         
73         filesystem::path p (filesystem::system_complete (d));
74         filesystem::path result;
75         for (filesystem::path::iterator i = p.begin(); i != p.end(); ++i) {
76                 if (*i == "..") {
77                         if (filesystem::is_symlink (result) || result.filename() == "..") {
78                                 result /= *i;
79                         } else {
80                                 result = result.parent_path ();
81                         }
82                 } else if (*i != ".") {
83                         result /= *i;
84                 }
85         }
86
87         _state.directory = result.string ();
88         
89         if (!filesystem::exists (_state.directory)) {
90                 if (must_exist) {
91                         throw OpenFileError (_state.directory);
92                 } else {
93                         filesystem::create_directory (_state.directory);
94                 }
95         }
96
97         read_metadata ();
98
99         _log = new FileLog (_state.file ("log"));
100 }
101
102 /** Copy constructor */
103 Film::Film (Film const & other)
104         : _state (other._state)
105         , _dirty (other._dirty)
106 {
107
108 }
109
110 Film::~Film ()
111 {
112         delete _log;
113 }
114           
115 /** Read the `metadata' file inside this Film's directory, and fill the
116  *  object's data with its content.
117  */
118
119 void
120 Film::read_metadata ()
121 {
122         ifstream f (metadata_file().c_str ());
123         multimap<string, string> kv = read_key_value (f);
124         for (multimap<string, string>::const_iterator i = kv.begin(); i != kv.end(); ++i) {
125                 _state.read_metadata (i->first, i->second);
126         }
127         _dirty = false;
128 }
129
130 /** Write our state to a file `metadata' inside the Film's directory */
131 void
132 Film::write_metadata () const
133 {
134         filesystem::create_directories (_state.directory);
135         
136         ofstream f (metadata_file().c_str ());
137         if (!f.good ()) {
138                 throw CreateFileError (metadata_file ());
139         }
140
141         _state.write_metadata (f);
142
143         _dirty = false;
144 }
145
146 /** Set the name by which DVD-o-matic refers to this Film */
147 void
148 Film::set_name (string n)
149 {
150         _state.name = n;
151         signal_changed (NAME);
152 }
153
154 /** Set the content file for this film.
155  *  @param c New content file; if specified as an absolute path, the content should
156  *  be within the film's _state.directory; if specified as a relative path, the content
157  *  will be assumed to be within the film's _state.directory.
158  */
159 void
160 Film::set_content (string c)
161 {
162         string check = _state.directory;
163
164 #if BOOST_FILESYSTEM_VERSION == 3
165         filesystem::path slash ("/");
166         string platform_slash = slash.make_preferred().string ();
167 #else
168 #ifdef DVDOMATIC_WINDOWS
169         string platform_slash = "\\";
170 #else
171         string platform_slash = "/";
172 #endif
173 #endif  
174
175         if (!ends_with (check, platform_slash)) {
176                 check += platform_slash;
177         }
178         
179         if (filesystem::path(c).has_root_directory () && starts_with (c, check)) {
180                 c = c.substr (_state.directory.length() + 1);
181         }
182
183         if (c == _state.content) {
184                 return;
185         }
186         
187         /* Create a temporary decoder so that we can get information
188            about the content.
189         */
190         shared_ptr<FilmState> s = state_copy ();
191         s->content = c;
192         shared_ptr<Options> o (new Options ("", "", ""));
193         o->out_size = Size (1024, 1024);
194
195         shared_ptr<Decoder> d = decoder_factory (s, o, 0, _log);
196         
197         _state.size = d->native_size ();
198         _state.length = d->length_in_frames ();
199         _state.frames_per_second = d->frames_per_second ();
200         _state.audio_channels = d->audio_channels ();
201         _state.audio_sample_rate = d->audio_sample_rate ();
202         _state.audio_sample_format = d->audio_sample_format ();
203         _state.has_subtitles = d->has_subtitles ();
204         _state.audio_streams = d->audio_streams ();
205         _state.subtitle_streams = d->subtitle_streams ();
206         _state.audio_stream = _state.audio_streams.empty() ? -1 : _state.audio_streams.front().id;
207         _state.subtitle_stream = _state.subtitle_streams.empty() ? -1 : _state.subtitle_streams.front().id;
208
209         _state.content_digest = md5_digest (s->content_path ());
210         _state.content = c;
211         
212         signal_changed (SIZE);
213         signal_changed (LENGTH);
214         signal_changed (FRAMES_PER_SECOND);
215         signal_changed (AUDIO_CHANNELS);
216         signal_changed (AUDIO_SAMPLE_RATE);
217         signal_changed (CONTENT);
218         signal_changed (AUDIO_STREAM);
219         signal_changed (SUBTITLE_STREAM);
220 }
221
222 /** Set the format that this Film should be shown in */
223 void
224 Film::set_format (Format const * f)
225 {
226         _state.format = f;
227         signal_changed (FORMAT);
228 }
229
230 /** Set the type to specify the DCP as having
231  *  (feature, trailer etc.)
232  */
233 void
234 Film::set_dcp_content_type (DCPContentType const * t)
235 {
236         _state.dcp_content_type = t;
237         signal_changed (DCP_CONTENT_TYPE);
238 }
239
240 /** Set the number of pixels by which to crop the left of the source video */
241 void
242 Film::set_left_crop (int c)
243 {
244         if (c == _state.crop.left) {
245                 return;
246         }
247         
248         _state.crop.left = c;
249         signal_changed (CROP);
250 }
251
252 /** Set the number of pixels by which to crop the right of the source video */
253 void
254 Film::set_right_crop (int c)
255 {
256         if (c == _state.crop.right) {
257                 return;
258         }
259
260         _state.crop.right = c;
261         signal_changed (CROP);
262 }
263
264 /** Set the number of pixels by which to crop the top of the source video */
265 void
266 Film::set_top_crop (int c)
267 {
268         if (c == _state.crop.top) {
269                 return;
270         }
271         
272         _state.crop.top = c;
273         signal_changed (CROP);
274 }
275
276 /** Set the number of pixels by which to crop the bottom of the source video */
277 void
278 Film::set_bottom_crop (int c)
279 {
280         if (c == _state.crop.bottom) {
281                 return;
282         }
283         
284         _state.crop.bottom = c;
285         signal_changed (CROP);
286 }
287
288 /** Set the filters to apply to the image when generating thumbnails
289  *  or a DCP.
290  */
291 void
292 Film::set_filters (vector<Filter const *> const & f)
293 {
294         _state.filters = f;
295         signal_changed (FILTERS);
296 }
297
298 /** Set the number of frames to put in any generated DCP (from
299  *  the start of the film).  0 indicates that all frames should
300  *  be used.
301  */
302 void
303 Film::set_dcp_frames (int n)
304 {
305         _state.dcp_frames = n;
306         signal_changed (DCP_FRAMES);
307 }
308
309 void
310 Film::set_dcp_trim_action (TrimAction a)
311 {
312         _state.dcp_trim_action = a;
313         signal_changed (DCP_TRIM_ACTION);
314 }
315
316 /** Set whether or not to generate a A/B comparison DCP.
317  *  Such a DCP has the left half of its frame as the Film
318  *  content without any filtering or post-processing; the
319  *  right half is rendered with filters and post-processing.
320  */
321 void
322 Film::set_dcp_ab (bool a)
323 {
324         _state.dcp_ab = a;
325         signal_changed (DCP_AB);
326 }
327
328 void
329 Film::set_audio_gain (float g)
330 {
331         _state.audio_gain = g;
332         signal_changed (AUDIO_GAIN);
333 }
334
335 void
336 Film::set_audio_delay (int d)
337 {
338         _state.audio_delay = d;
339         signal_changed (AUDIO_DELAY);
340 }
341
342 /** @return path of metadata file */
343 string
344 Film::metadata_file () const
345 {
346         return _state.file ("metadata");
347 }
348
349 /** @return full path of the content (actual video) file
350  *  of this Film.
351  */
352 string
353 Film::content () const
354 {
355         return _state.content_path ();
356 }
357
358 /** The pre-processing GUI part of a thumbs update.
359  *  Must be called from the GUI thread.
360  */
361 void
362 Film::update_thumbs_pre_gui ()
363 {
364         _state.thumbs.clear ();
365         filesystem::remove_all (_state.dir ("thumbs"));
366
367         /* This call will recreate the directory */
368         _state.dir ("thumbs");
369 }
370
371 /** The post-processing GUI part of a thumbs update.
372  *  Must be called from the GUI thread.
373  */
374 void
375 Film::update_thumbs_post_gui ()
376 {
377         string const tdir = _state.dir ("thumbs");
378         
379         for (filesystem::directory_iterator i = filesystem::directory_iterator (tdir); i != filesystem::directory_iterator(); ++i) {
380
381                 /* Aah, the sweet smell of progress */
382 #if BOOST_FILESYSTEM_VERSION == 3               
383                 string const l = filesystem::path(*i).leaf().generic_string();
384 #else
385                 string const l = i->leaf ();
386 #endif
387                 
388                 size_t const d = l.find (".png");
389                 if (d != string::npos) {
390                         _state.thumbs.push_back (atoi (l.substr (0, d).c_str()));
391                 }
392         }
393
394         sort (_state.thumbs.begin(), _state.thumbs.end());
395         
396         write_metadata ();
397         signal_changed (THUMBS);
398 }
399
400 /** @return the number of thumbnail images that we have */
401 int
402 Film::num_thumbs () const
403 {
404         return _state.thumbs.size ();
405 }
406
407 /** @param n A thumb index.
408  *  @return The frame within the Film that it is for.
409  */
410 int
411 Film::thumb_frame (int n) const
412 {
413         return _state.thumb_frame (n);
414 }
415
416 /** @param n A thumb index.
417  *  @return The path to the thumb's image file.
418  */
419 string
420 Film::thumb_file (int n) const
421 {
422         return _state.thumb_file (n);
423 }
424
425 /** @return The path to the directory to write JPEG2000 files to */
426 string
427 Film::j2k_dir () const
428 {
429         assert (format());
430
431         filesystem::path p;
432
433         /* Start with j2c */
434         p /= "j2c";
435
436         pair<string, string> f = Filter::ffmpeg_strings (filters ());
437
438         /* Write stuff to specify the filter / post-processing settings that are in use,
439            so that we don't get confused about J2K files generated using different
440            settings.
441         */
442         stringstream s;
443         s << _state.format->id()
444           << "_" << _state.content_digest
445           << "_" << crop().left << "_" << crop().right << "_" << crop().top << "_" << crop().bottom
446           << "_" << f.first << "_" << f.second
447           << "_" << _state.scaler->id();
448
449         p /= s.str ();
450
451         /* Similarly for the A/B case */
452         if (dcp_ab()) {
453                 stringstream s;
454                 pair<string, string> fa = Filter::ffmpeg_strings (Config::instance()->reference_filters());
455                 s << "ab_" << Config::instance()->reference_scaler()->id() << "_" << fa.first << "_" << fa.second;
456                 p /= s.str ();
457         }
458         
459         return _state.dir (p.string ());
460 }
461
462 /** Handle a change to the Film's metadata */
463 void
464 Film::signal_changed (Property p)
465 {
466         _dirty = true;
467         Changed (p);
468 }
469
470 /** Add suitable Jobs to the JobManager to create a DCP for this Film.
471  *  @param true to transcode, false to use the WAV and J2K files that are already there.
472  */
473 void
474 Film::make_dcp (bool transcode, int freq)
475 {
476         if (dcp_name().find ("/") != string::npos) {
477                 throw BadSettingError ("name", "cannot contain slashes");
478         }
479         
480         log()->log (String::compose ("DVD-o-matic %1 git %2 using %3", dvdomatic_version, dvdomatic_git_commit, dependency_version_summary()));
481
482         {
483                 char buffer[128];
484                 gethostname (buffer, sizeof (buffer));
485                 log()->log (String::compose ("Starting to make DCP on %1", buffer));
486         }
487                 
488         if (format() == 0) {
489                 throw MissingSettingError ("format");
490         }
491
492         if (content().empty ()) {
493                 throw MissingSettingError ("content");
494         }
495
496         if (dcp_content_type() == 0) {
497                 throw MissingSettingError ("content type");
498         }
499
500         if (name().empty()) {
501                 throw MissingSettingError ("name");
502         }
503
504         shared_ptr<const FilmState> fs = state_copy ();
505         shared_ptr<Options> o (new Options (j2k_dir(), ".j2c", _state.dir ("wavs")));
506         o->out_size = format()->dcp_size ();
507         if (dcp_frames() == 0) {
508                 /* Decode the whole film, no blacking */
509                 o->black_after = 0;
510         } else {
511                 switch (dcp_trim_action()) {
512                 case CUT:
513                         /* Decode only part of the film, no blacking */
514                         o->black_after = 0;
515                         break;
516                 case BLACK_OUT:
517                         /* Decode the whole film, but black some frames out */
518                         o->black_after = dcp_frames ();
519                 }
520         }
521         
522         o->decode_video_frequency = freq;
523         o->padding = format()->dcp_padding (this);
524         o->ratio = format()->ratio_as_float (this);
525         o->decode_subtitles = with_subtitles ();
526
527         shared_ptr<Job> r;
528
529         if (transcode) {
530                 if (_state.dcp_ab) {
531                         r = JobManager::instance()->add (shared_ptr<Job> (new ABTranscodeJob (fs, o, log(), shared_ptr<Job> ())));
532                 } else {
533                         r = JobManager::instance()->add (shared_ptr<Job> (new TranscodeJob (fs, o, log(), shared_ptr<Job> ())));
534                 }
535         }
536
537         r = JobManager::instance()->add (shared_ptr<Job> (new CheckHashesJob (fs, o, log(), r)));
538         JobManager::instance()->add (shared_ptr<Job> (new MakeDCPJob (fs, o, log(), r)));
539 }
540
541 shared_ptr<FilmState>
542 Film::state_copy () const
543 {
544         return shared_ptr<FilmState> (new FilmState (_state));
545 }
546
547 void
548 Film::copy_from_dvd_post_gui ()
549 {
550         const string dvd_dir = _state.dir ("dvd");
551
552         string largest_file;
553         uintmax_t largest_size = 0;
554         for (filesystem::directory_iterator i = filesystem::directory_iterator (dvd_dir); i != filesystem::directory_iterator(); ++i) {
555                 uintmax_t const s = filesystem::file_size (*i);
556                 if (s > largest_size) {
557
558 #if BOOST_FILESYSTEM_VERSION == 3               
559                         largest_file = filesystem::path(*i).generic_string();
560 #else
561                         largest_file = i->string ();
562 #endif
563                         largest_size = s;
564                 }
565         }
566
567         set_content (largest_file);
568 }
569
570 void
571 Film::examine_content ()
572 {
573         if (_examine_content_job) {
574                 return;
575         }
576         
577         _examine_content_job.reset (new ExamineContentJob (state_copy (), log(), shared_ptr<Job> ()));
578         _examine_content_job->Finished.connect (sigc::mem_fun (*this, &Film::examine_content_post_gui));
579         JobManager::instance()->add (_examine_content_job);
580 }
581
582 void
583 Film::examine_content_post_gui ()
584 {
585         _state.length = _examine_content_job->last_video_frame ();
586         signal_changed (LENGTH);
587         
588         _examine_content_job.reset ();
589 }
590
591 void
592 Film::set_scaler (Scaler const * s)
593 {
594         _state.scaler = s;
595         signal_changed (SCALER);
596 }
597
598 /** @return full paths to any audio files that this Film has */
599 vector<string>
600 Film::audio_files () const
601 {
602         vector<string> f;
603         for (filesystem::directory_iterator i = filesystem::directory_iterator (_state.dir("wavs")); i != filesystem::directory_iterator(); ++i) {
604                 f.push_back (i->path().string ());
605         }
606
607         return f;
608 }
609
610 ContentType
611 Film::content_type () const
612 {
613         return _state.content_type ();
614 }
615
616 void
617 Film::set_still_duration (int d)
618 {
619         _state.still_duration = d;
620         signal_changed (STILL_DURATION);
621 }
622
623 void
624 Film::send_dcp_to_tms ()
625 {
626         shared_ptr<Job> j (new SCPDCPJob (state_copy (), log(), shared_ptr<Job> ()));
627         JobManager::instance()->add (j);
628 }
629
630 void
631 Film::copy_from_dvd ()
632 {
633         shared_ptr<Job> j (new CopyFromDVDJob (state_copy (), log(), shared_ptr<Job> ()));
634         j->Finished.connect (sigc::mem_fun (*this, &Film::copy_from_dvd_post_gui));
635         JobManager::instance()->add (j);
636 }
637
638 int
639 Film::encoded_frames () const
640 {
641         if (format() == 0) {
642                 return 0;
643         }
644
645         int N = 0;
646         for (filesystem::directory_iterator i = filesystem::directory_iterator (j2k_dir ()); i != filesystem::directory_iterator(); ++i) {
647                 ++N;
648                 this_thread::interruption_point ();
649         }
650
651         return N;
652 }
653
654 void
655 Film::set_with_subtitles (bool w)
656 {
657         _state.with_subtitles = w;
658         signal_changed (WITH_SUBTITLES);
659 }
660
661 void
662 Film::set_subtitle_offset (int o)
663 {
664         _state.subtitle_offset = o;
665         signal_changed (SUBTITLE_OFFSET);
666 }
667
668 void
669 Film::set_subtitle_scale (float s)
670 {
671         _state.subtitle_scale = s;
672         signal_changed (SUBTITLE_SCALE);
673 }
674
675 pair<Position, string>
676 Film::thumb_subtitle (int n) const
677 {
678         string sub_file = _state.thumb_base(n) + ".sub";
679         if (!filesystem::exists (sub_file)) {
680                 return pair<Position, string> ();
681         }
682
683         pair<Position, string> sub;
684         
685         ifstream f (sub_file.c_str ());
686         multimap<string, string> kv = read_key_value (f);
687         for (map<string, string>::const_iterator i = kv.begin(); i != kv.end(); ++i) {
688                 if (i->first == "x") {
689                         sub.first.x = lexical_cast<int> (i->second);
690                 } else if (i->first == "y") {
691                         sub.first.y = lexical_cast<int> (i->second);
692                         sub.second = String::compose ("%1.sub.png", _state.thumb_base(n));
693                 }
694         }
695         
696         return sub;
697 }
698
699 void
700 Film::set_audio_language (string v)
701 {
702         _state.audio_language = v;
703         signal_changed (DCI_METADATA);
704 }
705
706 void
707 Film::set_subtitle_language (string v)
708 {
709         _state.subtitle_language = v;
710         signal_changed (DCI_METADATA);
711 }
712
713 void
714 Film::set_territory (string v)
715 {
716         _state.territory = v;
717         signal_changed (DCI_METADATA);
718 }
719
720 void
721 Film::set_rating (string v)
722 {
723         _state.rating = v;
724         signal_changed (DCI_METADATA);
725 }
726
727 void
728 Film::set_studio (string v)
729 {
730         _state.studio = v;
731         signal_changed (DCI_METADATA);
732 }
733
734 void
735 Film::set_facility (string v)
736 {
737         _state.facility = v;
738         signal_changed (DCI_METADATA);
739 }
740
741 void
742 Film::set_package_type (string v)
743 {
744         _state.package_type = v;
745         signal_changed (DCI_METADATA);
746 }
747
748 void
749 Film::set_use_dci_name (bool v)
750 {
751         _state.use_dci_name = v;
752         signal_changed (USE_DCI_NAME);
753 }