Create film directory in constructor.
[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
221         _state.content_digest = md5_digest (s->content_path ());
222         _state.content = c;
223         
224         signal_changed (SIZE);
225         signal_changed (LENGTH);
226         signal_changed (FRAMES_PER_SECOND);
227         signal_changed (AUDIO_CHANNELS);
228         signal_changed (AUDIO_SAMPLE_RATE);
229         signal_changed (CONTENT);
230 }
231
232 /** Set the format that this Film should be shown in */
233 void
234 Film::set_format (Format const * f)
235 {
236         _state.format = f;
237         signal_changed (FORMAT);
238 }
239
240 /** Set the type to specify the DCP as having
241  *  (feature, trailer etc.)
242  */
243 void
244 Film::set_dcp_content_type (DCPContentType const * t)
245 {
246         _state.dcp_content_type = t;
247         signal_changed (DCP_CONTENT_TYPE);
248 }
249
250 /** Set the number of pixels by which to crop the left of the source video */
251 void
252 Film::set_left_crop (int c)
253 {
254         if (c == _state.crop.left) {
255                 return;
256         }
257         
258         _state.crop.left = c;
259         signal_changed (CROP);
260 }
261
262 /** Set the number of pixels by which to crop the right of the source video */
263 void
264 Film::set_right_crop (int c)
265 {
266         if (c == _state.crop.right) {
267                 return;
268         }
269
270         _state.crop.right = c;
271         signal_changed (CROP);
272 }
273
274 /** Set the number of pixels by which to crop the top of the source video */
275 void
276 Film::set_top_crop (int c)
277 {
278         if (c == _state.crop.top) {
279                 return;
280         }
281         
282         _state.crop.top = c;
283         signal_changed (CROP);
284 }
285
286 /** Set the number of pixels by which to crop the bottom of the source video */
287 void
288 Film::set_bottom_crop (int c)
289 {
290         if (c == _state.crop.bottom) {
291                 return;
292         }
293         
294         _state.crop.bottom = c;
295         signal_changed (CROP);
296 }
297
298 /** Set the filters to apply to the image when generating thumbnails
299  *  or a DCP.
300  */
301 void
302 Film::set_filters (vector<Filter const *> const & f)
303 {
304         _state.filters = f;
305         signal_changed (FILTERS);
306 }
307
308 /** Set the number of frames to put in any generated DCP (from
309  *  the start of the film).  0 indicates that all frames should
310  *  be used.
311  */
312 void
313 Film::set_dcp_frames (int n)
314 {
315         _state.dcp_frames = n;
316         signal_changed (DCP_FRAMES);
317 }
318
319 void
320 Film::set_dcp_trim_action (TrimAction a)
321 {
322         _state.dcp_trim_action = a;
323         signal_changed (DCP_TRIM_ACTION);
324 }
325
326 /** Set whether or not to generate a A/B comparison DCP.
327  *  Such a DCP has the left half of its frame as the Film
328  *  content without any filtering or post-processing; the
329  *  right half is rendered with filters and post-processing.
330  */
331 void
332 Film::set_dcp_ab (bool a)
333 {
334         _state.dcp_ab = a;
335         signal_changed (DCP_AB);
336 }
337
338 void
339 Film::set_audio_gain (float g)
340 {
341         _state.audio_gain = g;
342         signal_changed (AUDIO_GAIN);
343 }
344
345 void
346 Film::set_audio_delay (int d)
347 {
348         _state.audio_delay = d;
349         signal_changed (AUDIO_DELAY);
350 }
351
352 /** @return path of metadata file */
353 string
354 Film::metadata_file () const
355 {
356         return _state.file ("metadata");
357 }
358
359 /** @return full path of the content (actual video) file
360  *  of this Film.
361  */
362 string
363 Film::content () const
364 {
365         return _state.content_path ();
366 }
367
368 /** The pre-processing GUI part of a thumbs update.
369  *  Must be called from the GUI thread.
370  */
371 void
372 Film::update_thumbs_pre_gui ()
373 {
374         _state.thumbs.clear ();
375         filesystem::remove_all (_state.dir ("thumbs"));
376
377         /* This call will recreate the directory */
378         _state.dir ("thumbs");
379 }
380
381 /** The post-processing GUI part of a thumbs update.
382  *  Must be called from the GUI thread.
383  */
384 void
385 Film::update_thumbs_post_gui ()
386 {
387         string const tdir = _state.dir ("thumbs");
388         
389         for (filesystem::directory_iterator i = filesystem::directory_iterator (tdir); i != filesystem::directory_iterator(); ++i) {
390
391                 /* Aah, the sweet smell of progress */
392 #if BOOST_FILESYSTEM_VERSION == 3               
393                 string const l = filesystem::path(*i).leaf().generic_string();
394 #else
395                 string const l = i->leaf ();
396 #endif
397                 
398                 size_t const d = l.find (".tiff");
399                 if (d != string::npos) {
400                         _state.thumbs.push_back (atoi (l.substr (0, d).c_str()));
401                 }
402         }
403
404         sort (_state.thumbs.begin(), _state.thumbs.end());
405         
406         write_metadata ();
407         signal_changed (THUMBS);
408 }
409
410 /** @return the number of thumbnail images that we have */
411 int
412 Film::num_thumbs () const
413 {
414         return _state.thumbs.size ();
415 }
416
417 /** @param n A thumb index.
418  *  @return The frame within the Film that it is for.
419  */
420 int
421 Film::thumb_frame (int n) const
422 {
423         return _state.thumb_frame (n);
424 }
425
426 /** @param n A thumb index.
427  *  @return The path to the thumb's image file.
428  */
429 string
430 Film::thumb_file (int n) const
431 {
432         return _state.thumb_file (n);
433 }
434
435 /** @return The path to the directory to write JPEG2000 files to */
436 string
437 Film::j2k_dir () const
438 {
439         assert (format());
440
441         filesystem::path p;
442
443         /* Start with j2c */
444         p /= "j2c";
445
446         pair<string, string> f = Filter::ffmpeg_strings (filters ());
447
448         /* Write stuff to specify the filter / post-processing settings that are in use,
449            so that we don't get confused about J2K files generated using different
450            settings.
451         */
452         stringstream s;
453         s << _state.format->id()
454           << "_" << _state.content_digest
455           << "_" << crop().left << "_" << crop().right << "_" << crop().top << "_" << crop().bottom
456           << "_" << f.first << "_" << f.second
457           << "_" << _state.scaler->id();
458
459         p /= s.str ();
460
461         /* Similarly for the A/B case */
462         if (dcp_ab()) {
463                 stringstream s;
464                 pair<string, string> fa = Filter::ffmpeg_strings (Config::instance()->reference_filters());
465                 s << "ab_" << Config::instance()->reference_scaler()->id() << "_" << fa.first << "_" << fa.second;
466                 p /= s.str ();
467         }
468         
469         return _state.dir (p.string ());
470 }
471
472 /** Handle a change to the Film's metadata */
473 void
474 Film::signal_changed (Property p)
475 {
476         _dirty = true;
477         Changed (p);
478 }
479
480 /** Add suitable Jobs to the JobManager to create a DCP for this Film.
481  *  @param true to transcode, false to use the WAV and J2K files that are already there.
482  */
483 void
484 Film::make_dcp (bool transcode, int freq)
485 {
486         string const t = name ();
487         if (t.find ("/") != string::npos) {
488                 throw BadSettingError ("name", "cannot contain slashes");
489         }
490         
491         log()->log (String::compose ("DVD-o-matic %1 git %2 using %3", dvdomatic_version, dvdomatic_git_commit, dependency_version_summary()));
492
493         {
494                 char buffer[128];
495                 gethostname (buffer, sizeof (buffer));
496                 log()->log (String::compose ("Starting to make DCP on %1", buffer));
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 CheckHashesJob (fs, o, log ())));
549         JobManager::instance()->add (shared_ptr<Job> (new MakeDCPJob (fs, o, log ())));
550 }
551
552 shared_ptr<FilmState>
553 Film::state_copy () const
554 {
555         return shared_ptr<FilmState> (new FilmState (_state));
556 }
557
558 void
559 Film::copy_from_dvd_post_gui ()
560 {
561         const string dvd_dir = _state.dir ("dvd");
562
563         string largest_file;
564         uintmax_t largest_size = 0;
565         for (filesystem::directory_iterator i = filesystem::directory_iterator (dvd_dir); i != filesystem::directory_iterator(); ++i) {
566                 uintmax_t const s = filesystem::file_size (*i);
567                 if (s > largest_size) {
568
569 #if BOOST_FILESYSTEM_VERSION == 3               
570                         largest_file = filesystem::path(*i).generic_string();
571 #else
572                         largest_file = i->string ();
573 #endif
574                         largest_size = s;
575                 }
576         }
577
578         set_content (largest_file);
579 }
580
581 void
582 Film::examine_content ()
583 {
584         if (_examine_content_job) {
585                 return;
586         }
587         
588         _examine_content_job.reset (new ExamineContentJob (state_copy (), log ()));
589         _examine_content_job->Finished.connect (sigc::mem_fun (*this, &Film::examine_content_post_gui));
590         JobManager::instance()->add (_examine_content_job);
591 }
592
593 void
594 Film::examine_content_post_gui ()
595 {
596         _state.length = _examine_content_job->last_video_frame ();
597         signal_changed (LENGTH);
598         
599         _examine_content_job.reset ();
600 }
601
602 void
603 Film::set_scaler (Scaler const * s)
604 {
605         _state.scaler = s;
606         signal_changed (SCALER);
607 }
608
609 /** @return full paths to any audio files that this Film has */
610 vector<string>
611 Film::audio_files () const
612 {
613         vector<string> f;
614         for (filesystem::directory_iterator i = filesystem::directory_iterator (_state.dir("wavs")); i != filesystem::directory_iterator(); ++i) {
615                 f.push_back (i->path().string ());
616         }
617
618         return f;
619 }
620
621 ContentType
622 Film::content_type () const
623 {
624         return _state.content_type ();
625 }
626
627 void
628 Film::set_still_duration (int d)
629 {
630         _state.still_duration = d;
631         signal_changed (STILL_DURATION);
632 }
633
634 void
635 Film::send_dcp_to_tms ()
636 {
637         shared_ptr<Job> j (new SCPDCPJob (state_copy (), log ()));
638         JobManager::instance()->add (j);
639 }
640
641 void
642 Film::copy_from_dvd ()
643 {
644         shared_ptr<Job> j (new CopyFromDVDJob (state_copy (), log ()));
645         j->Finished.connect (sigc::mem_fun (*this, &Film::copy_from_dvd_post_gui));
646         JobManager::instance()->add (j);
647 }
648
649 int
650 Film::encoded_frames () const
651 {
652         if (format() == 0) {
653                 return 0;
654         }
655
656         int N = 0;
657         for (filesystem::directory_iterator i = filesystem::directory_iterator (j2k_dir ()); i != filesystem::directory_iterator(); ++i) {
658                 ++N;
659                 this_thread::interruption_point ();
660         }
661
662         return N;
663 }