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