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