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