Merge branch 'master' of ssh://git.carlh.net/home/carl/git/dcpomatic
[dcpomatic.git] / src / lib / job.cc
1 /*
2     Copyright (C) 2012-2016 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 <sub/exceptions.h>
34 #include <boost/thread.hpp>
35 #include <boost/filesystem.hpp>
36 #include <boost/foreach.hpp>
37 #include <boost/date_time/posix_time/posix_time.hpp>
38 #include <iostream>
39
40 #include "i18n.h"
41
42 using std::string;
43 using std::list;
44 using std::cout;
45 using boost::shared_ptr;
46 using boost::optional;
47 using boost::function;
48
49 #define LOG_ERROR_NC(...) if (_film) { _film->log()->log (__VA_ARGS__, LogEntry::TYPE_ERROR); }
50 #define LOG_GENERAL(...) if (_film) { _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_GENERAL); }
51
52 /** @param film Associated film, or 0 */
53 Job::Job (shared_ptr<const Film> film)
54         : _film (film)
55         , _thread (0)
56         , _state (NEW)
57         , _start_time (0)
58         , _sub_start_time (0)
59         , _progress (0)
60         , _ran_for (0)
61 {
62
63 }
64
65 Job::~Job ()
66 {
67         if (_thread) {
68                 _thread->interrupt ();
69                 /* We can't use DCPOMATIC_ASSERT here as it may throw an exception */
70                 if (_thread->joinable ()) {
71                         try {
72                                 _thread->join ();
73                         } catch (...) {
74                                 /* Too late to do anything about this */
75                         }
76                 }
77         }
78
79         delete _thread;
80 }
81
82 /** Start the job in a separate thread, returning immediately */
83 void
84 Job::start ()
85 {
86         set_state (RUNNING);
87         _start_time = time (0);
88         _sub_start_time = time (0);
89         _thread = new boost::thread (boost::bind (&Job::run_wrapper, this));
90 }
91
92 /** A wrapper for the ::run() method to catch exceptions */
93 void
94 Job::run_wrapper ()
95 {
96         try {
97
98                 run ();
99
100         } catch (dcp::FileError& e) {
101
102                 string m = String::compose (_("An error occurred whilst handling the file %1."), boost::filesystem::path (e.filename()).leaf());
103
104                 try {
105                         boost::filesystem::space_info const s = boost::filesystem::space (e.filename());
106                         if (s.available < pow (1024, 3)) {
107                                 m += N_("\n\n");
108                                 m += _("The drive that the film is stored on is low in disc space.  Free some more space and try again.");
109                         }
110                 } catch (...) {
111
112                 }
113
114                 set_error (e.what(), m);
115                 set_progress (1);
116                 set_state (FINISHED_ERROR);
117
118         } catch (OpenFileError& e) {
119
120                 set_error (
121                         String::compose (_("Could not open %1"), e.file().string()),
122                         String::compose (
123                                 _("DCP-o-matic could not open the file %1.  Perhaps it does not exist or is in an unexpected format."),
124                                 boost::filesystem::absolute (e.file()).string()
125                                 )
126                         );
127
128                 set_progress (1);
129                 set_state (FINISHED_ERROR);
130
131         } catch (boost::filesystem::filesystem_error& e) {
132
133                 if (e.code() == boost::system::errc::no_such_file_or_directory) {
134                         set_error (
135                                 String::compose (_("Could not open %1"), e.path1().string ()),
136                                 String::compose (
137                                         _("DCP-o-matic could not open the file %1.  Perhaps it does not exist or is in an unexpected format."),
138                                         boost::filesystem::absolute (e.path1()).string()
139                                         )
140                                 );
141                 } else {
142                         set_error (
143                                 e.what (),
144                                 string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
145                                 );
146                 }
147
148                 set_progress (1);
149                 set_state (FINISHED_ERROR);
150
151         } catch (boost::thread_interrupted &) {
152
153                 set_state (FINISHED_CANCELLED);
154
155         } catch (sub::SubripError& e) {
156
157                 string extra = "Error is near:\n";
158                 BOOST_FOREACH (string i, e.context()) {
159                         extra += i + "\n";
160                 }
161
162                 set_error (e.what (), extra);
163                 set_progress (1);
164                 set_state (FINISHED_ERROR);
165
166         } catch (std::bad_alloc& e) {
167
168                 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."));
169                 set_progress (1);
170                 set_state (FINISHED_ERROR);
171
172         } catch (std::exception& e) {
173
174                 set_error (
175                         e.what (),
176                         string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
177                         );
178
179                 set_progress (1);
180                 set_state (FINISHED_ERROR);
181
182         } catch (...) {
183
184                 set_error (
185                         _("Unknown error"),
186                         string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
187                         );
188
189                 set_progress (1);
190                 set_state (FINISHED_ERROR);
191         }
192 }
193
194 /** @return true if this job is new (ie has not started running) */
195 bool
196 Job::is_new () const
197 {
198         boost::mutex::scoped_lock lm (_state_mutex);
199         return _state == NEW;
200 }
201
202 /** @return true if the job is running */
203 bool
204 Job::running () const
205 {
206         boost::mutex::scoped_lock lm (_state_mutex);
207         return _state == RUNNING;
208 }
209
210 /** @return true if the job has finished (either successfully or unsuccessfully) */
211 bool
212 Job::finished () const
213 {
214         boost::mutex::scoped_lock lm (_state_mutex);
215         return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
216 }
217
218 /** @return true if the job has finished successfully */
219 bool
220 Job::finished_ok () const
221 {
222         boost::mutex::scoped_lock lm (_state_mutex);
223         return _state == FINISHED_OK;
224 }
225
226 /** @return true if the job has finished unsuccessfully */
227 bool
228 Job::finished_in_error () const
229 {
230         boost::mutex::scoped_lock lm (_state_mutex);
231         return _state == FINISHED_ERROR;
232 }
233
234 bool
235 Job::finished_cancelled () const
236 {
237         boost::mutex::scoped_lock lm (_state_mutex);
238         return _state == FINISHED_CANCELLED;
239 }
240
241 bool
242 Job::paused_by_user () const
243 {
244         boost::mutex::scoped_lock lm (_state_mutex);
245         return _state == PAUSED_BY_USER;
246 }
247
248 bool
249 Job::paused_by_priority () const
250 {
251         boost::mutex::scoped_lock lm (_state_mutex);
252         return _state == PAUSED_BY_PRIORITY;
253 }
254
255 /** Set the state of this job.
256  *  @param s New state.
257  */
258 void
259 Job::set_state (State s)
260 {
261         bool finished = false;
262
263         {
264                 boost::mutex::scoped_lock lm (_state_mutex);
265                 _state = s;
266
267                 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
268                         _ran_for = time(0) - _start_time;
269                         finished = true;
270                         _sub_name.clear ();
271                 }
272         }
273
274         if (finished) {
275                 emit (boost::bind (boost::ref (Finished)));
276         }
277 }
278
279 /** @return DCPTime (in seconds) that this sub-job has been running */
280 int
281 Job::elapsed_sub_time () const
282 {
283         if (_sub_start_time == 0) {
284                 return 0;
285         }
286
287         return time (0) - _sub_start_time;
288 }
289
290 /** Check to see if this job has been interrupted or paused */
291 void
292 Job::check_for_interruption_or_pause ()
293 {
294         boost::this_thread::interruption_point ();
295
296         boost::mutex::scoped_lock lm (_state_mutex);
297         while (_state == PAUSED_BY_USER || _state == PAUSED_BY_PRIORITY) {
298                 emit (boost::bind (boost::ref (Progress)));
299                 _pause_changed.wait (lm);
300         }
301 }
302
303 /** Set the progress of the current part of the job.
304  *  @param p Progress (from 0 to 1)
305  */
306 void
307 Job::set_progress (float p, bool force)
308 {
309         check_for_interruption_or_pause ();
310
311         if (!force) {
312                 /* Check for excessively frequent progress reporting */
313                 boost::mutex::scoped_lock lm (_progress_mutex);
314                 struct timeval now;
315                 gettimeofday (&now, 0);
316                 if (_last_progress_update && _last_progress_update->tv_sec > 0) {
317                         double const elapsed = (now.tv_sec + now.tv_usec / 1000000.0)
318                                 - (_last_progress_update->tv_sec + _last_progress_update->tv_usec / 1000000.0);
319                         if (elapsed < 0.5) {
320                                 return;
321                         }
322                 }
323                 _last_progress_update = now;
324         }
325
326         set_progress_common (p);
327 }
328
329 void
330 Job::set_progress_common (optional<float> p)
331 {
332         {
333                 boost::mutex::scoped_lock lm (_progress_mutex);
334                 _progress = p;
335         }
336
337         emit (boost::bind (boost::ref (Progress)));
338 }
339
340 /** @return fractional progress of the current sub-job, if known */
341 optional<float>
342 Job::progress () const
343 {
344         boost::mutex::scoped_lock lm (_progress_mutex);
345         return _progress;
346 }
347
348 void
349 Job::sub (string n)
350 {
351         {
352                 boost::mutex::scoped_lock lm (_progress_mutex);
353                 LOG_GENERAL ("Sub-job %1 starting", n);
354                 _sub_name = n;
355         }
356
357         set_progress (0, true);
358         _sub_start_time = time (0);
359 }
360
361 string
362 Job::error_details () const
363 {
364         boost::mutex::scoped_lock lm (_state_mutex);
365         return _error_details;
366 }
367
368 /** @return A summary of any error that the job has generated */
369 string
370 Job::error_summary () const
371 {
372         boost::mutex::scoped_lock lm (_state_mutex);
373         return _error_summary;
374 }
375
376 /** Set the current error string.
377  *  @param e New error string.
378  */
379 void
380 Job::set_error (string s, string d)
381 {
382         if (_film) {
383                 LOG_ERROR_NC (s);
384                 LOG_ERROR_NC (d);
385                 _film->log()->log (String::compose ("Error in job: %1 (%2)", s, d), LogEntry::TYPE_ERROR);
386         }
387
388         boost::mutex::scoped_lock lm (_state_mutex);
389         _error_summary = s;
390         _error_details = d;
391 }
392
393 /** Say that this job's progress will be unknown until further notice */
394 void
395 Job::set_progress_unknown ()
396 {
397         check_for_interruption_or_pause ();
398         set_progress_common (optional<float> ());
399 }
400
401 /** @return Human-readable status of this job */
402 string
403 Job::status () const
404 {
405         optional<float> p = progress ();
406         int const t = elapsed_sub_time ();
407         int const r = remaining_time ();
408
409         string s;
410         if (!finished () && p) {
411                 int pc = lrintf (p.get() * 100);
412                 if (pc == 100) {
413                         /* 100% makes it sound like we've finished when we haven't */
414                         pc = 99;
415                 }
416
417                 char buffer[64];
418                 snprintf (buffer, sizeof(buffer), "%d%%", pc);
419                 s += buffer;
420
421                 if (t > 10 && r > 0) {
422                         boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
423                         boost::posix_time::ptime finish = now + boost::posix_time::seconds(r);
424                         char finish_string[6];
425                         snprintf (finish_string, sizeof(finish_string), "%02d:%02d", finish.time_of_day().hours(), finish.time_of_day().minutes());
426                         string day;
427                         if (now.date() != finish.date()) {
428                                 /// TRANSLATORS: the %1 in this string will be filled in with a day of the week
429                                 /// to say what day a job will finish.
430                                 day = String::compose (_(" on %1"), finish.date().day_of_week().as_long_string());
431                         }
432                         /// TRANSLATORS: "remaining; finishing at" here follows an amount of time that is remaining
433                         /// on an operation; after it is an estimated wall-clock completion time.
434                         s += String::compose(
435                                 _("; %1 remaining; finishing at %2%3"),
436                                 seconds_to_approximate_hms(r), finish_string, day
437                                 );
438                 }
439         } else if (finished_ok ()) {
440                 s = String::compose (_("OK (ran for %1)"), seconds_to_hms (_ran_for));
441         } else if (finished_in_error ()) {
442                 s = String::compose (_("Error: %1"), error_summary ());
443         } else if (finished_cancelled ()) {
444                 s = _("Cancelled");
445         }
446
447         return s;
448 }
449
450 string
451 Job::json_status () const
452 {
453         boost::mutex::scoped_lock lm (_state_mutex);
454
455         switch (_state) {
456         case NEW:
457                 return N_("new");
458         case RUNNING:
459                 return N_("running");
460         case PAUSED_BY_USER:
461         case PAUSED_BY_PRIORITY:
462                 return N_("paused");
463         case FINISHED_OK:
464                 return N_("finished_ok");
465         case FINISHED_ERROR:
466                 return N_("finished_error");
467         case FINISHED_CANCELLED:
468                 return N_("finished_cancelled");
469         }
470
471         return "";
472 }
473
474 /** @return An estimate of the remaining time for this sub-job, in seconds */
475 int
476 Job::remaining_time () const
477 {
478         if (progress().get_value_or(0) == 0) {
479                 return elapsed_sub_time ();
480         }
481
482         return elapsed_sub_time() / progress().get() - elapsed_sub_time();
483 }
484
485 void
486 Job::cancel ()
487 {
488         if (!_thread) {
489                 return;
490         }
491
492         if (paused_by_user() || paused_by_priority()) {
493                 resume ();
494         }
495
496         _thread->interrupt ();
497         DCPOMATIC_ASSERT (_thread->joinable ());
498         _thread->join ();
499         delete _thread;
500         _thread = 0;
501 }
502
503 void
504 Job::pause_by_user ()
505 {
506         if (running ()) {
507                 set_state (PAUSED_BY_USER);
508                 _pause_changed.notify_all ();
509         }
510 }
511
512 void
513 Job::pause_by_priority ()
514 {
515         if (running ()) {
516                 set_state (PAUSED_BY_PRIORITY);
517                 _pause_changed.notify_all ();
518         }
519 }
520
521 void
522 Job::resume ()
523 {
524         if (paused_by_user() || paused_by_priority()) {
525                 set_state (RUNNING);
526                 _pause_changed.notify_all ();
527         }
528 }
529
530 void
531 Job::when_finished (boost::signals2::connection& connection, function<void()> finished)
532 {
533         boost::mutex::scoped_lock lm (_state_mutex);
534         if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
535                 finished ();
536         } else {
537                 connection = Finished.connect (finished);
538         }
539 }