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