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