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