2 Copyright (C) 2012-2021 Carl Hetherington <cth@carlh.net>
4 This file is part of DCP-o-matic.
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.
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.
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/>.
22 * @brief A parent class to represent long-running tasks which are run in their own thread.
28 #include "exceptions.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/date_time/posix_time/posix_time.hpp>
45 using std::shared_ptr;
46 using boost::optional;
48 using namespace dcpomatic;
50 /** @param film Associated film, or 0 */
51 Job::Job (shared_ptr<const Film> film)
64 #ifdef DCPOMATIC_DEBUG
65 /* Any subclass should have called stop_thread in its destructor */
66 assert (!_thread.joinable());
73 boost::this_thread::disable_interruption dis;
81 /** Start the job in a separate thread, returning immediately */
86 _start_time = time (0);
87 _sub_start_time = time (0);
88 _thread = boost::thread (boost::bind(&Job::run_wrapper, this));
89 #ifdef DCPOMATIC_LINUX
90 pthread_setname_np (_thread.native_handle(), "job-wrapper");
94 /** A wrapper for the ::run() method to catch exceptions */
98 start_of_thread (String::compose("Job-%1", json_name()));
104 } catch (dcp::FileError& e) {
106 string m = String::compose (_("An error occurred whilst handling the file %1."), boost::filesystem::path (e.filename()).leaf());
109 auto const s = boost::filesystem::space (e.filename());
110 if (s.available < pow (1024, 3)) {
112 m += _("The drive that the film is stored on is low in disc space. Free some more space and try again.");
118 set_error (e.what(), m);
120 set_state (FINISHED_ERROR);
122 } catch (dcp::StartCompressionError& e) {
126 #ifdef DCPOMATIC_WINDOWS
127 #if (__GNUC__ && !__x86_64__)
130 _("Failed to encode the DCP."),
131 _("This error has probably occurred because you are running the 32-bit version of DCP-o-matic and "
132 "trying to use too many encoding threads. Please reduce the 'number of threads DCP-o-matic should "
133 "use' in the General tab of Preferences and try again.")
138 if (running_32_on_64()) {
140 _("Failed to encode the DCP."),
141 _("This error has probably occurred because you are running the 32-bit version of DCP-o-matic. Please re-install DCP-o-matic with the 64-bit installer and try again.")
151 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
156 set_state (FINISHED_ERROR);
158 } catch (OpenFileError& e) {
161 String::compose (_("Could not open %1"), e.file().string()),
163 _("DCP-o-matic could not open the file %1 (%2). Perhaps it does not exist or is in an unexpected format."),
164 boost::filesystem::absolute (e.file()).string(),
170 set_state (FINISHED_ERROR);
172 } catch (boost::filesystem::filesystem_error& e) {
174 if (e.code() == boost::system::errc::no_such_file_or_directory) {
176 String::compose (_("Could not open %1"), e.path1().string ()),
178 _("DCP-o-matic could not open the file %1 (%2). Perhaps it does not exist or is in an unexpected format."),
179 boost::filesystem::absolute (e.path1()).string(),
186 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
191 set_state (FINISHED_ERROR);
193 } catch (boost::thread_interrupted &) {
195 set_state (FINISHED_CANCELLED);
197 } catch (sub::SubripError& e) {
199 string extra = "Error is near:\n";
200 for (auto i: e.context()) {
204 set_error (e.what (), extra);
206 set_state (FINISHED_ERROR);
208 } catch (std::bad_alloc& e) {
210 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."));
212 set_state (FINISHED_ERROR);
214 } catch (dcp::ReadError& e) {
216 set_error (e.message(), e.detail().get_value_or(""));
218 set_state (FINISHED_ERROR);
220 } catch (KDMError& e) {
222 set_error (e.summary(), e.detail());
224 set_state (FINISHED_ERROR);
226 } catch (FileError& e) {
228 set_error (e.what(), e.what());
230 set_state (FINISHED_ERROR);
232 } catch (std::exception& e) {
236 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
240 set_state (FINISHED_ERROR);
246 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
250 set_state (FINISHED_ERROR);
254 /** @return true if this job is new (ie has not started running) */
258 boost::mutex::scoped_lock lm (_state_mutex);
259 return _state == NEW;
262 /** @return true if the job is running */
264 Job::running () const
266 boost::mutex::scoped_lock lm (_state_mutex);
267 return _state == RUNNING;
270 /** @return true if the job has finished (either successfully or unsuccessfully) */
272 Job::finished () const
274 boost::mutex::scoped_lock lm (_state_mutex);
275 return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
278 /** @return true if the job has finished successfully */
280 Job::finished_ok () const
282 boost::mutex::scoped_lock lm (_state_mutex);
283 return _state == FINISHED_OK;
286 /** @return true if the job has finished unsuccessfully */
288 Job::finished_in_error () const
290 boost::mutex::scoped_lock lm (_state_mutex);
291 return _state == FINISHED_ERROR;
295 Job::finished_cancelled () const
297 boost::mutex::scoped_lock lm (_state_mutex);
298 return _state == FINISHED_CANCELLED;
302 Job::paused_by_user () const
304 boost::mutex::scoped_lock lm (_state_mutex);
305 return _state == PAUSED_BY_USER;
309 Job::paused_by_priority () const
311 boost::mutex::scoped_lock lm (_state_mutex);
312 return _state == PAUSED_BY_PRIORITY;
315 /** Set the state of this job.
316 * @param s New state.
319 Job::set_state (State s)
321 bool finished = false;
324 boost::mutex::scoped_lock lm (_state_mutex);
327 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
328 _ran_for = time(0) - _start_time;
335 emit (boost::bind (boost::ref (Finished)));
336 FinishedImmediate ();
340 /** @return DCPTime (in seconds) that this sub-job has been running */
342 Job::elapsed_sub_time () const
344 if (_sub_start_time == 0) {
348 return time (0) - _sub_start_time;
351 /** Check to see if this job has been interrupted or paused */
353 Job::check_for_interruption_or_pause ()
355 boost::this_thread::interruption_point ();
357 boost::mutex::scoped_lock lm (_state_mutex);
358 while (_state == PAUSED_BY_USER || _state == PAUSED_BY_PRIORITY) {
359 emit (boost::bind (boost::ref (Progress)));
360 _pause_changed.wait (lm);
364 /** Set the progress of the current part of the job.
365 * @param p Progress (from 0 to 1)
366 * @param force Do not ignore this update, even if it hasn't been long since the last one.
369 Job::set_progress (float p, bool force)
371 check_for_interruption_or_pause ();
374 /* Check for excessively frequent progress reporting */
375 boost::mutex::scoped_lock lm (_progress_mutex);
377 gettimeofday (&now, 0);
378 if (_last_progress_update && _last_progress_update->tv_sec > 0) {
379 double const elapsed = (now.tv_sec + now.tv_usec / 1000000.0)
380 - (_last_progress_update->tv_sec + _last_progress_update->tv_usec / 1000000.0);
385 _last_progress_update = now;
388 set_progress_common (p);
392 Job::set_progress_common (optional<float> p)
395 boost::mutex::scoped_lock lm (_progress_mutex);
399 emit (boost::bind (boost::ref (Progress)));
402 /** @return fractional progress of the current sub-job, if known */
404 Job::progress () const
406 boost::mutex::scoped_lock lm (_progress_mutex);
414 boost::mutex::scoped_lock lm (_progress_mutex);
415 LOG_GENERAL ("Sub-job %1 starting", n);
419 set_progress (0, true);
420 _sub_start_time = time (0);
424 Job::error_details () const
426 boost::mutex::scoped_lock lm (_state_mutex);
427 return _error_details;
430 /** @return A summary of any error that the job has generated */
432 Job::error_summary () const
434 boost::mutex::scoped_lock lm (_state_mutex);
435 return _error_summary;
438 /** Set the current error string.
439 * @param s New error string.
440 * @param d New error detail string.
443 Job::set_error (string s, string d)
446 _film->log()->log (String::compose ("Error in job: %1 (%2)", s, d), LogEntry::TYPE_ERROR);
449 boost::mutex::scoped_lock lm (_state_mutex);
454 /** Say that this job's progress will be unknown until further notice */
456 Job::set_progress_unknown ()
458 check_for_interruption_or_pause ();
459 set_progress_common (optional<float> ());
462 /** @return Human-readable status of this job */
466 optional<float> p = progress ();
467 int const t = elapsed_sub_time ();
468 int const r = remaining_time ();
471 if (!finished () && p) {
472 int pc = lrintf (p.get() * 100);
474 /* 100% makes it sound like we've finished when we haven't */
479 snprintf (buffer, sizeof(buffer), "%d%%", pc);
482 if (t > 10 && r > 0) {
483 auto now = boost::posix_time::second_clock::local_time();
484 auto finish = now + boost::posix_time::seconds(r);
485 char finish_string[16];
486 snprintf (finish_string, sizeof(finish_string), "%02d:%02d", int(finish.time_of_day().hours()), int(finish.time_of_day().minutes()));
488 if (now.date() != finish.date()) {
489 /// TRANSLATORS: the %1 in this string will be filled in with a day of the week
490 /// to say what day a job will finish.
491 day = String::compose (_(" on %1"), day_of_week_to_string(finish.date().day_of_week()));
493 /// TRANSLATORS: "remaining; finishing at" here follows an amount of time that is remaining
494 /// on an operation; after it is an estimated wall-clock completion time.
495 s += String::compose(
496 _("; %1 remaining; finishing at %2%3"),
497 seconds_to_approximate_hms(r), finish_string, day
500 } else if (finished_ok ()) {
501 s = String::compose (_("OK (ran for %1)"), seconds_to_hms (_ran_for));
502 } else if (finished_in_error ()) {
503 s = String::compose (_("Error: %1"), error_summary ());
504 } else if (finished_cancelled ()) {
512 Job::json_status () const
514 boost::mutex::scoped_lock lm (_state_mutex);
520 return N_("running");
522 case PAUSED_BY_PRIORITY:
525 return N_("finished_ok");
527 return N_("finished_error");
528 case FINISHED_CANCELLED:
529 return N_("finished_cancelled");
535 /** @return An estimate of the remaining time for this sub-job, in seconds */
537 Job::remaining_time () const
539 if (progress().get_value_or(0) == 0) {
540 return elapsed_sub_time ();
543 return elapsed_sub_time() / progress().get() - elapsed_sub_time();
549 if (!_thread.joinable()) {
553 if (paused_by_user() || paused_by_priority()) {
557 _thread.interrupt ();
561 /** @return true if the job was paused, false if it was not running */
563 Job::pause_by_user ()
567 boost::mutex::scoped_lock lm (_state_mutex);
568 /* We can set _state here directly because we have a lock and we aren't
569 setting the job to FINISHED_*
571 if (_state == RUNNING) {
573 _state = PAUSED_BY_USER;
578 _pause_changed.notify_all ();
585 Job::pause_by_priority ()
588 set_state (PAUSED_BY_PRIORITY);
589 _pause_changed.notify_all ();
596 if (paused_by_user() || paused_by_priority()) {
598 _pause_changed.notify_all ();
603 Job::when_finished (boost::signals2::connection& connection, function<void()> finished)
605 boost::mutex::scoped_lock lm (_state_mutex);
606 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
609 connection = Finished.connect (finished);
614 Job::message () const
616 boost::mutex::scoped_lock lm (_state_mutex);
621 Job::set_message (string m)
623 boost::mutex::scoped_lock lm (_state_mutex);