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