Add option to analyse audio automatically when content is added (#673).
[dcpomatic.git] / src / lib / job.cc
1 /*
2     Copyright (C) 2012-2015 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 /** @file  src/job.cc
21  *  @brief A parent class to represent long-running tasks which are run in their own thread.
22  */
23
24 #include "job.h"
25 #include "util.h"
26 #include "cross.h"
27 #include "exceptions.h"
28 #include "film.h"
29 #include "log.h"
30 #include "compose.hpp"
31 #include <dcp/exceptions.h>
32 #include <boost/thread.hpp>
33 #include <boost/filesystem.hpp>
34
35 #include "i18n.h"
36
37 using std::string;
38 using std::list;
39 using std::cout;
40 using boost::shared_ptr;
41 using boost::optional;
42 using boost::function;
43
44 #define LOG_ERROR_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_ERROR);
45
46 Job::Job (shared_ptr<const Film> film)
47         : _film (film)
48         , _thread (0)
49         , _state (NEW)
50         , _start_time (0)
51         , _progress (0)
52         , _ran_for (0)
53 {
54
55 }
56
57 Job::~Job ()
58 {
59         if (_thread) {
60                 _thread->interrupt ();
61                 _thread->join ();
62         }
63
64         delete _thread;
65 }
66
67 /** Start the job in a separate thread, returning immediately */
68 void
69 Job::start ()
70 {
71         set_state (RUNNING);
72         _start_time = time (0);
73         _thread = new boost::thread (boost::bind (&Job::run_wrapper, this));
74 }
75
76 /** A wrapper for the ::run() method to catch exceptions */
77 void
78 Job::run_wrapper ()
79 {
80         try {
81
82                 run ();
83
84         } catch (dcp::FileError& e) {
85
86                 string m = String::compose (_("An error occurred whilst handling the file %1."), boost::filesystem::path (e.filename()).leaf());
87
88                 try {
89                         boost::filesystem::space_info const s = boost::filesystem::space (e.filename());
90                         if (s.available < pow (1024, 3)) {
91                                 m += N_("\n\n");
92                                 m += _("The drive that the film is stored on is low in disc space.  Free some more space and try again.");
93                         }
94                 } catch (...) {
95
96                 }
97
98                 set_error (e.what(), m);
99                 set_progress (1);
100                 set_state (FINISHED_ERROR);
101
102         } catch (OpenFileError& e) {
103
104                 set_error (
105                         String::compose (_("Could not open %1"), e.file().string()),
106                         String::compose (_("DCP-o-matic could not open the file %1.  Perhaps it does not exist or is in an unexpected format."), e.file().string())
107                         );
108
109                 set_progress (1);
110                 set_state (FINISHED_ERROR);
111
112         } catch (boost::filesystem::filesystem_error& e) {
113
114                 if (e.code() == boost::system::errc::no_such_file_or_directory) {
115                         set_error (
116                                 String::compose (_("Could not open %1"), e.path1().string ()),
117                                 String::compose (_("DCP-o-matic could not open the file %1.  Perhaps it does not exist or is in an unexpected format."), e.path1().string())
118                                 );
119                 } else {
120                         set_error (
121                                 e.what (),
122                                 string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
123                                 );
124                 }
125
126                 set_progress (1);
127                 set_state (FINISHED_ERROR);
128
129         } catch (boost::thread_interrupted &) {
130
131                 set_state (FINISHED_CANCELLED);
132
133         } catch (std::bad_alloc& e) {
134
135                 set_error (_("Out of memory"), _("There was not enough memory to do this."));
136                 set_progress (1);
137                 set_state (FINISHED_ERROR);
138
139         } catch (std::exception& e) {
140
141                 set_error (
142                         e.what (),
143                         string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
144                         );
145
146                 set_progress (1);
147                 set_state (FINISHED_ERROR);
148
149         } catch (...) {
150
151                 set_error (
152                         _("Unknown error"),
153                         string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
154                         );
155
156                 set_progress (1);
157                 set_state (FINISHED_ERROR);
158         }
159 }
160
161 /** @return true if this job is new (ie has not started running) */
162 bool
163 Job::is_new () const
164 {
165         boost::mutex::scoped_lock lm (_state_mutex);
166         return _state == NEW;
167 }
168
169 /** @return true if the job is running */
170 bool
171 Job::running () const
172 {
173         boost::mutex::scoped_lock lm (_state_mutex);
174         return _state == RUNNING;
175 }
176
177 /** @return true if the job has finished (either successfully or unsuccessfully) */
178 bool
179 Job::finished () const
180 {
181         boost::mutex::scoped_lock lm (_state_mutex);
182         return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
183 }
184
185 /** @return true if the job has finished successfully */
186 bool
187 Job::finished_ok () const
188 {
189         boost::mutex::scoped_lock lm (_state_mutex);
190         return _state == FINISHED_OK;
191 }
192
193 /** @return true if the job has finished unsuccessfully */
194 bool
195 Job::finished_in_error () const
196 {
197         boost::mutex::scoped_lock lm (_state_mutex);
198         return _state == FINISHED_ERROR;
199 }
200
201 bool
202 Job::finished_cancelled () const
203 {
204         boost::mutex::scoped_lock lm (_state_mutex);
205         return _state == FINISHED_CANCELLED;
206 }
207
208 bool
209 Job::paused () const
210 {
211         boost::mutex::scoped_lock lm (_state_mutex);
212         return _state == PAUSED;
213 }
214
215 /** Set the state of this job.
216  *  @param s New state.
217  */
218 void
219 Job::set_state (State s)
220 {
221         bool finished = false;
222
223         {
224                 boost::mutex::scoped_lock lm (_state_mutex);
225                 _state = s;
226
227                 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
228                         _ran_for = elapsed_time ();
229                         finished = true;
230                         _sub_name.clear ();
231                 }
232         }
233
234         if (finished) {
235                 emit (boost::bind (boost::ref (Finished)));
236         }
237 }
238
239 /** @return DCPTime (in seconds) that this sub-job has been running */
240 int
241 Job::elapsed_time () const
242 {
243         if (_start_time == 0) {
244                 return 0;
245         }
246
247         return time (0) - _start_time;
248 }
249
250 /** Set the progress of the current part of the job.
251  *  @param p Progress (from 0 to 1)
252  */
253 void
254 Job::set_progress (float p, bool force)
255 {
256         if (!force && fabs (p - progress().get_value_or(0)) < 0.01) {
257                 /* Calm excessive progress reporting */
258                 return;
259         }
260
261         set_progress_common (p);
262 }
263
264 void
265 Job::set_progress_common (optional<float> p)
266 {
267         boost::mutex::scoped_lock lm (_progress_mutex);
268         _progress = p;
269         boost::this_thread::interruption_point ();
270
271         boost::mutex::scoped_lock lm2 (_state_mutex);
272         while (_state == PAUSED) {
273                 _pause_changed.wait (lm2);
274         }
275
276         lm.unlock ();
277         lm2.unlock ();
278
279         emit (boost::bind (boost::ref (Progress)));
280 }
281
282 /** @return fractional progress of the current sub-job, if known */
283 optional<float>
284 Job::progress () const
285 {
286         boost::mutex::scoped_lock lm (_progress_mutex);
287         return _progress;
288 }
289
290 void
291 Job::sub (string n)
292 {
293         {
294                 boost::mutex::scoped_lock lm (_progress_mutex);
295                 _sub_name = n;
296         }
297
298         set_progress (0, true);
299 }
300
301 string
302 Job::error_details () const
303 {
304         boost::mutex::scoped_lock lm (_state_mutex);
305         return _error_details;
306 }
307
308 /** @return A summary of any error that the job has generated */
309 string
310 Job::error_summary () const
311 {
312         boost::mutex::scoped_lock lm (_state_mutex);
313         return _error_summary;
314 }
315
316 /** Set the current error string.
317  *  @param e New error string.
318  */
319 void
320 Job::set_error (string s, string d)
321 {
322         LOG_ERROR_NC (s);
323         LOG_ERROR_NC (d);
324
325         _film->log()->log (String::compose ("Error in job: %1 (%2)", s, d), Log::TYPE_ERROR);
326         boost::mutex::scoped_lock lm (_state_mutex);
327         _error_summary = s;
328         _error_details = d;
329 }
330
331 /** Say that this job's progress will be unknown until further notice */
332 void
333 Job::set_progress_unknown ()
334 {
335         set_progress_common (optional<float> ());
336 }
337
338 /** @return Human-readable status of this job */
339 string
340 Job::status () const
341 {
342         optional<float> p = progress ();
343         int const t = elapsed_time ();
344         int const r = remaining_time ();
345
346         SafeStringStream s;
347         if (!finished () && p) {
348                 int pc = lrintf (p.get() * 100);
349                 if (pc == 100) {
350                         /* 100% makes it sound like we've finished when we haven't */
351                         pc = 99;
352                 }
353
354                 s << pc << N_("%");
355
356                 if (t > 10 && r > 0) {
357                         /// TRANSLATORS: remaining here follows an amount of time that is remaining
358                         /// on an operation.
359                         s << "; " << seconds_to_approximate_hms (r) << " " << _("remaining");
360                 }
361         } else if (finished_ok ()) {
362                 s << String::compose (_("OK (ran for %1)"), seconds_to_hms (_ran_for));
363         } else if (finished_in_error ()) {
364                 s << String::compose (_("Error: %1"), error_summary ());
365         } else if (finished_cancelled ()) {
366                 s << _("Cancelled");
367         }
368
369         return s.str ();
370 }
371
372 string
373 Job::json_status () const
374 {
375         boost::mutex::scoped_lock lm (_state_mutex);
376
377         switch (_state) {
378         case NEW:
379                 return N_("new");
380         case RUNNING:
381                 return N_("running");
382         case PAUSED:
383                 return N_("paused");
384         case FINISHED_OK:
385                 return N_("finished_ok");
386         case FINISHED_ERROR:
387                 return N_("finished_error");
388         case FINISHED_CANCELLED:
389                 return N_("finished_cancelled");
390         }
391
392         return "";
393 }
394
395 /** @return An estimate of the remaining time for this sub-job, in seconds */
396 int
397 Job::remaining_time () const
398 {
399         if (progress().get_value_or(0) == 0) {
400                 return elapsed_time ();
401         }
402
403         return elapsed_time() / progress().get() - elapsed_time();
404 }
405
406 void
407 Job::cancel ()
408 {
409         if (!_thread) {
410                 return;
411         }
412
413         if (paused ()) {
414                 resume ();
415         }
416
417         _thread->interrupt ();
418         _thread->join ();
419 }
420
421 void
422 Job::pause ()
423 {
424         if (running ()) {
425                 set_state (PAUSED);
426                 _pause_changed.notify_all ();
427         }
428 }
429
430 void
431 Job::resume ()
432 {
433         if (paused ()) {
434                 set_state (RUNNING);
435                 _pause_changed.notify_all ();
436         }
437 }
438
439 void
440 Job::when_finished (boost::signals2::connection& connection, function<void()> finished)
441 {
442         boost::mutex::scoped_lock lm (_state_mutex);
443         if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
444                 finished ();
445         } else {
446                 connection = Finished.connect (finished);
447         }
448 }
449