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