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