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