Do audio/video pts sync in a hopefully much more sensible way.
[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 {
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         set_directory (result.string ());
87         
88         if (!filesystem::exists (directory())) {
89                 if (must_exist) {
90                         throw OpenFileError (directory());
91                 } else {
92                         filesystem::create_directory (directory());
93                 }
94         }
95
96         read_metadata ();
97
98         _log = new FileLog (file ("log"));
99 }
100
101 Film::~Film ()
102 {
103         delete _log;
104 }
105           
106 /** @return The path to the directory to write JPEG2000 files to */
107 string
108 Film::j2k_dir () const
109 {
110         assert (format());
111
112         filesystem::path p;
113
114         /* Start with j2c */
115         p /= "j2c";
116
117         pair<string, string> f = Filter::ffmpeg_strings (filters());
118
119         /* Write stuff to specify the filter / post-processing settings that are in use,
120            so that we don't get confused about J2K files generated using different
121            settings.
122         */
123         stringstream s;
124         s << format()->id()
125           << "_" << content_digest()
126           << "_" << crop().left << "_" << crop().right << "_" << crop().top << "_" << crop().bottom
127           << "_" << f.first << "_" << f.second
128           << "_" << scaler()->id();
129
130         p /= s.str ();
131
132         /* Similarly for the A/B case */
133         if (dcp_ab()) {
134                 stringstream s;
135                 pair<string, string> fa = Filter::ffmpeg_strings (Config::instance()->reference_filters());
136                 s << "ab_" << Config::instance()->reference_scaler()->id() << "_" << fa.first << "_" << fa.second;
137                 p /= s.str ();
138         }
139         
140         return dir (p.string());
141 }
142
143 /** Add suitable Jobs to the JobManager to create a DCP for this Film.
144  *  @param true to transcode, false to use the WAV and J2K files that are already there.
145  */
146 void
147 Film::make_dcp (bool transcode)
148 {
149         if (dcp_name().find ("/") != string::npos) {
150                 throw BadSettingError ("name", "cannot contain slashes");
151         }
152         
153         log()->log (String::compose ("DVD-o-matic %1 git %2 using %3", dvdomatic_version, dvdomatic_git_commit, dependency_version_summary()));
154
155         {
156                 char buffer[128];
157                 gethostname (buffer, sizeof (buffer));
158                 log()->log (String::compose ("Starting to make DCP on %1", buffer));
159         }
160                 
161         if (format() == 0) {
162                 throw MissingSettingError ("format");
163         }
164
165         if (content().empty ()) {
166                 throw MissingSettingError ("content");
167         }
168
169         if (dcp_content_type() == 0) {
170                 throw MissingSettingError ("content type");
171         }
172
173         if (name().empty()) {
174                 throw MissingSettingError ("name");
175         }
176
177         shared_ptr<const FilmState> fs = state_copy ();
178         shared_ptr<Options> o (new Options (j2k_dir(), ".j2c", dir ("wavs")));
179         o->out_size = format()->dcp_size ();
180         if (dcp_frames() == 0) {
181                 /* Decode the whole film, no blacking */
182                 o->black_after = 0;
183         } else {
184                 switch (dcp_trim_action()) {
185                 case CUT:
186                         /* Decode only part of the film, no blacking */
187                         o->black_after = 0;
188                         break;
189                 case BLACK_OUT:
190                         /* Decode the whole film, but black some frames out */
191                         o->black_after = dcp_frames ();
192                 }
193         }
194         
195         o->padding = format()->dcp_padding (this);
196         o->ratio = format()->ratio_as_float (this);
197         o->decode_subtitles = with_subtitles ();
198
199         shared_ptr<Job> r;
200
201         if (transcode) {
202                 if (dcp_ab()) {
203                         r = JobManager::instance()->add (shared_ptr<Job> (new ABTranscodeJob (fs, o, log(), shared_ptr<Job> ())));
204                 } else {
205                         r = JobManager::instance()->add (shared_ptr<Job> (new TranscodeJob (fs, o, log(), shared_ptr<Job> ())));
206                 }
207         }
208
209         r = JobManager::instance()->add (shared_ptr<Job> (new CheckHashesJob (fs, o, log(), r)));
210         JobManager::instance()->add (shared_ptr<Job> (new MakeDCPJob (fs, o, log(), r)));
211 }
212
213 void
214 Film::copy_from_dvd_post_gui ()
215 {
216         const string dvd_dir = dir ("dvd");
217
218         string largest_file;
219         uintmax_t largest_size = 0;
220         for (filesystem::directory_iterator i = filesystem::directory_iterator (dvd_dir); i != filesystem::directory_iterator(); ++i) {
221                 uintmax_t const s = filesystem::file_size (*i);
222                 if (s > largest_size) {
223
224 #if BOOST_FILESYSTEM_VERSION == 3               
225                         largest_file = filesystem::path(*i).generic_string();
226 #else
227                         largest_file = i->string ();
228 #endif
229                         largest_size = s;
230                 }
231         }
232
233         set_content (largest_file);
234 }
235
236 /** Start a job to examine our content file */
237 void
238 Film::examine_content ()
239 {
240         if (_examine_content_job) {
241                 return;
242         }
243
244         set_thumbs (vector<int> ());
245         filesystem::remove_all (dir ("thumbs"));
246
247         /* This call will recreate the directory */
248         dir ("thumbs");
249         
250         _examine_content_job.reset (new ExamineContentJob (state_copy (), log(), shared_ptr<Job> ()));
251         _examine_content_job->Finished.connect (sigc::mem_fun (*this, &Film::examine_content_post_gui));
252         JobManager::instance()->add (_examine_content_job);
253 }
254
255 void
256 Film::examine_content_post_gui ()
257 {
258         set_length (_examine_content_job->last_video_frame ());
259         _examine_content_job.reset ();
260
261         string const tdir = dir ("thumbs");
262         vector<int> thumbs;
263
264         for (filesystem::directory_iterator i = filesystem::directory_iterator (tdir); i != filesystem::directory_iterator(); ++i) {
265
266                 /* Aah, the sweet smell of progress */
267 #if BOOST_FILESYSTEM_VERSION == 3               
268                 string const l = filesystem::path(*i).leaf().generic_string();
269 #else
270                 string const l = i->leaf ();
271 #endif
272                 
273                 size_t const d = l.find (".png");
274                 size_t const t = l.find (".tmp");
275                 if (d != string::npos && t == string::npos) {
276                         thumbs.push_back (atoi (l.substr (0, d).c_str()));
277                 }
278         }
279
280         sort (thumbs.begin(), thumbs.end());
281         set_thumbs (thumbs);    
282 }
283
284
285 /** @return full paths to any audio files that this Film has */
286 vector<string>
287 Film::audio_files () const
288 {
289         vector<string> f;
290         for (filesystem::directory_iterator i = filesystem::directory_iterator (dir("wavs")); i != filesystem::directory_iterator(); ++i) {
291                 f.push_back (i->path().string ());
292         }
293
294         return f;
295 }
296
297 /** Start a job to send our DCP to the configured TMS */
298 void
299 Film::send_dcp_to_tms ()
300 {
301         shared_ptr<Job> j (new SCPDCPJob (state_copy (), log(), shared_ptr<Job> ()));
302         JobManager::instance()->add (j);
303 }
304
305 void
306 Film::copy_from_dvd ()
307 {
308         shared_ptr<Job> j (new CopyFromDVDJob (state_copy (), log(), shared_ptr<Job> ()));
309         j->Finished.connect (sigc::mem_fun (*this, &Film::copy_from_dvd_post_gui));
310         JobManager::instance()->add (j);
311 }
312
313 /** Count the number of frames that have been encoded for this film.
314  *  @return frame count.
315  */
316 int
317 Film::encoded_frames () const
318 {
319         if (format() == 0) {
320                 return 0;
321         }
322
323         int N = 0;
324         for (filesystem::directory_iterator i = filesystem::directory_iterator (j2k_dir ()); i != filesystem::directory_iterator(); ++i) {
325                 ++N;
326                 this_thread::interruption_point ();
327         }
328
329         return N;
330 }
331
332 /** Return the filename of a subtitle image if one exists for a given thumb index.
333  *  @param Thumbnail index.
334  *  @return Position of the image within the source frame, and the image filename, if one exists.
335  *  Otherwise the filename will be empty.
336  */
337 pair<Position, string>
338 Film::thumb_subtitle (int n) const
339 {
340         string sub_file = thumb_base(n) + ".sub";
341         if (!filesystem::exists (sub_file)) {
342                 return pair<Position, string> ();
343         }
344
345         pair<Position, string> sub;
346         
347         ifstream f (sub_file.c_str ());
348         multimap<string, string> kv = read_key_value (f);
349         for (map<string, string>::const_iterator i = kv.begin(); i != kv.end(); ++i) {
350                 if (i->first == "x") {
351                         sub.first.x = lexical_cast<int> (i->second);
352                 } else if (i->first == "y") {
353                         sub.first.y = lexical_cast<int> (i->second);
354                         sub.second = String::compose ("%1.sub.png", thumb_base(n));
355                 }
356         }
357         
358         return sub;
359 }
360
361 void
362 Film::set_content (string c)
363 {
364         FilmState::set_content (c);
365         examine_content ();
366 }