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