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;
47 using boost::function;
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 */
102 } catch (dcp::FileError& e) {
104 string m = String::compose (_("An error occurred whilst handling the file %1."), boost::filesystem::path (e.filename()).leaf());
107 auto const s = boost::filesystem::space (e.filename());
108 if (s.available < pow (1024, 3)) {
110 m += _("The drive that the film is stored on is low in disc space. Free some more space and try again.");
116 set_error (e.what(), m);
118 set_state (FINISHED_ERROR);
120 } catch (dcp::StartCompressionError& e) {
124 #ifdef DCPOMATIC_WINDOWS
125 #if (__GNUC__ && !__x86_64__)
128 _("Failed to encode the DCP."),
129 _("This error has probably occurred because you are running the 32-bit version of DCP-o-matic and "
130 "trying to use too many encoding threads. Please reduce the 'number of threads DCP-o-matic should "
131 "use' in the General tab of Preferences and try again.")
136 if (running_32_on_64()) {
138 _("Failed to encode the DCP."),
139 _("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.")
149 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
154 set_state (FINISHED_ERROR);
156 } catch (OpenFileError& e) {
159 String::compose (_("Could not open %1"), e.file().string()),
161 _("DCP-o-matic could not open the file %1 (%2). Perhaps it does not exist or is in an unexpected format."),
162 boost::filesystem::absolute (e.file()).string(),
168 set_state (FINISHED_ERROR);
170 } catch (boost::filesystem::filesystem_error& e) {
172 if (e.code() == boost::system::errc::no_such_file_or_directory) {
174 String::compose (_("Could not open %1"), e.path1().string ()),
176 _("DCP-o-matic could not open the file %1 (%2). Perhaps it does not exist or is in an unexpected format."),
177 boost::filesystem::absolute (e.path1()).string(),
184 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
189 set_state (FINISHED_ERROR);
191 } catch (boost::thread_interrupted &) {
193 set_state (FINISHED_CANCELLED);
195 } catch (sub::SubripError& e) {
197 string extra = "Error is near:\n";
198 for (auto i: e.context()) {
202 set_error (e.what (), extra);
204 set_state (FINISHED_ERROR);
206 } catch (std::bad_alloc& e) {
208 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."));
210 set_state (FINISHED_ERROR);
212 } catch (dcp::ReadError& e) {
214 set_error (e.message(), e.detail().get_value_or(""));
216 set_state (FINISHED_ERROR);
218 } catch (KDMError& e) {
220 set_error (e.summary(), e.detail());
222 set_state (FINISHED_ERROR);
224 } catch (FileError& e) {
226 set_error (e.what(), e.what());
228 set_state (FINISHED_ERROR);
230 } catch (std::exception& e) {
234 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
238 set_state (FINISHED_ERROR);
244 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
248 set_state (FINISHED_ERROR);
252 /** @return true if this job is new (ie has not started running) */
256 boost::mutex::scoped_lock lm (_state_mutex);
257 return _state == NEW;
260 /** @return true if the job is running */
262 Job::running () const
264 boost::mutex::scoped_lock lm (_state_mutex);
265 return _state == RUNNING;
268 /** @return true if the job has finished (either successfully or unsuccessfully) */
270 Job::finished () const
272 boost::mutex::scoped_lock lm (_state_mutex);
273 return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
276 /** @return true if the job has finished successfully */
278 Job::finished_ok () const
280 boost::mutex::scoped_lock lm (_state_mutex);
281 return _state == FINISHED_OK;
284 /** @return true if the job has finished unsuccessfully */
286 Job::finished_in_error () const
288 boost::mutex::scoped_lock lm (_state_mutex);
289 return _state == FINISHED_ERROR;
293 Job::finished_cancelled () const
295 boost::mutex::scoped_lock lm (_state_mutex);
296 return _state == FINISHED_CANCELLED;
300 Job::paused_by_user () const
302 boost::mutex::scoped_lock lm (_state_mutex);
303 return _state == PAUSED_BY_USER;
307 Job::paused_by_priority () const
309 boost::mutex::scoped_lock lm (_state_mutex);
310 return _state == PAUSED_BY_PRIORITY;
313 /** Set the state of this job.
314 * @param s New state.
317 Job::set_state (State s)
319 bool finished = false;
322 boost::mutex::scoped_lock lm (_state_mutex);
325 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
326 _ran_for = time(0) - _start_time;
333 emit (boost::bind (boost::ref (Finished)));
334 FinishedImmediate ();
338 /** @return DCPTime (in seconds) that this sub-job has been running */
340 Job::elapsed_sub_time () const
342 if (_sub_start_time == 0) {
346 return time (0) - _sub_start_time;
349 /** Check to see if this job has been interrupted or paused */
351 Job::check_for_interruption_or_pause ()
353 boost::this_thread::interruption_point ();
355 boost::mutex::scoped_lock lm (_state_mutex);
356 while (_state == PAUSED_BY_USER || _state == PAUSED_BY_PRIORITY) {
357 emit (boost::bind (boost::ref (Progress)));
358 _pause_changed.wait (lm);
362 /** Set the progress of the current part of the job.
363 * @param p Progress (from 0 to 1)
364 * @param force Do not ignore this update, even if it hasn't been long since the last one.
367 Job::set_progress (float p, bool force)
369 check_for_interruption_or_pause ();
372 /* Check for excessively frequent progress reporting */
373 boost::mutex::scoped_lock lm (_progress_mutex);
375 gettimeofday (&now, 0);
376 if (_last_progress_update && _last_progress_update->tv_sec > 0) {
377 double const elapsed = (now.tv_sec + now.tv_usec / 1000000.0)
378 - (_last_progress_update->tv_sec + _last_progress_update->tv_usec / 1000000.0);
383 _last_progress_update = now;
386 set_progress_common (p);
390 Job::set_progress_common (optional<float> p)
393 boost::mutex::scoped_lock lm (_progress_mutex);
397 emit (boost::bind (boost::ref (Progress)));
400 /** @return fractional progress of the current sub-job, if known */
402 Job::progress () const
404 boost::mutex::scoped_lock lm (_progress_mutex);
412 boost::mutex::scoped_lock lm (_progress_mutex);
413 LOG_GENERAL ("Sub-job %1 starting", n);
417 set_progress (0, true);
418 _sub_start_time = time (0);
422 Job::error_details () const
424 boost::mutex::scoped_lock lm (_state_mutex);
425 return _error_details;
428 /** @return A summary of any error that the job has generated */
430 Job::error_summary () const
432 boost::mutex::scoped_lock lm (_state_mutex);
433 return _error_summary;
436 /** Set the current error string.
437 * @param s New error string.
438 * @param d New error detail string.
441 Job::set_error (string s, string d)
444 _film->log()->log (String::compose ("Error in job: %1 (%2)", s, d), LogEntry::TYPE_ERROR);
447 boost::mutex::scoped_lock lm (_state_mutex);
452 /** Say that this job's progress will be unknown until further notice */
454 Job::set_progress_unknown ()
456 check_for_interruption_or_pause ();
457 set_progress_common (optional<float> ());
460 /** @return Human-readable status of this job */
464 optional<float> p = progress ();
465 int const t = elapsed_sub_time ();
466 int const r = remaining_time ();
469 if (!finished () && p) {
470 int pc = lrintf (p.get() * 100);
472 /* 100% makes it sound like we've finished when we haven't */
477 snprintf (buffer, sizeof(buffer), "%d%%", pc);
480 if (t > 10 && r > 0) {
481 auto now = boost::posix_time::second_clock::local_time();
482 auto finish = now + boost::posix_time::seconds(r);
483 char finish_string[16];
484 snprintf (finish_string, sizeof(finish_string), "%02d:%02d", int(finish.time_of_day().hours()), int(finish.time_of_day().minutes()));
486 if (now.date() != finish.date()) {
487 /// TRANSLATORS: the %1 in this string will be filled in with a day of the week
488 /// to say what day a job will finish.
489 day = String::compose (_(" on %1"), day_of_week_to_string(finish.date().day_of_week()));
491 /// TRANSLATORS: "remaining; finishing at" here follows an amount of time that is remaining
492 /// on an operation; after it is an estimated wall-clock completion time.
493 s += String::compose(
494 _("; %1 remaining; finishing at %2%3"),
495 seconds_to_approximate_hms(r), finish_string, day
498 } else if (finished_ok ()) {
499 s = String::compose (_("OK (ran for %1)"), seconds_to_hms (_ran_for));
500 } else if (finished_in_error ()) {
501 s = String::compose (_("Error: %1"), error_summary ());
502 } else if (finished_cancelled ()) {
510 Job::json_status () const
512 boost::mutex::scoped_lock lm (_state_mutex);
518 return N_("running");
520 case PAUSED_BY_PRIORITY:
523 return N_("finished_ok");
525 return N_("finished_error");
526 case FINISHED_CANCELLED:
527 return N_("finished_cancelled");
533 /** @return An estimate of the remaining time for this sub-job, in seconds */
535 Job::remaining_time () const
537 if (progress().get_value_or(0) == 0) {
538 return elapsed_sub_time ();
541 return elapsed_sub_time() / progress().get() - elapsed_sub_time();
547 if (!_thread.joinable()) {
551 if (paused_by_user() || paused_by_priority()) {
555 _thread.interrupt ();
559 /** @return true if the job was paused, false if it was not running */
561 Job::pause_by_user ()
565 boost::mutex::scoped_lock lm (_state_mutex);
566 /* We can set _state here directly because we have a lock and we aren't
567 setting the job to FINISHED_*
569 if (_state == RUNNING) {
571 _state = PAUSED_BY_USER;
576 _pause_changed.notify_all ();
583 Job::pause_by_priority ()
586 set_state (PAUSED_BY_PRIORITY);
587 _pause_changed.notify_all ();
594 if (paused_by_user() || paused_by_priority()) {
596 _pause_changed.notify_all ();
601 Job::when_finished (boost::signals2::connection& connection, function<void()> finished)
603 boost::mutex::scoped_lock lm (_state_mutex);
604 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
607 connection = Finished.connect (finished);
612 Job::message () const
614 boost::mutex::scoped_lock lm (_state_mutex);
619 Job::set_message (string m)
621 boost::mutex::scoped_lock lm (_state_mutex);