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