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/>.
23 * @brief A parent class to represent long-running tasks which are run in their own thread.
27 #include "compose.hpp"
28 #include "constants.h"
30 #include "dcpomatic_log.h"
31 #include "exceptions.h"
36 #include <dcp/exceptions.h>
37 #include <sub/exceptions.h>
38 #include <boost/date_time/posix_time/posix_time.hpp>
39 #include <boost/filesystem.hpp>
40 #include <boost/thread.hpp>
50 using std::shared_ptr;
52 using boost::optional;
53 using namespace dcpomatic;
56 /** @param film Associated film, or 0 */
57 Job::Job (shared_ptr<const Film> film)
62 , _rate_limit_progress(true)
70 #ifdef DCPOMATIC_DEBUG
71 /* Any subclass should have called stop_thread in its destructor */
72 assert (!_thread.joinable());
80 boost::this_thread::disable_interruption dis;
89 /** Start the job in a separate thread, returning immediately */
94 _start_time = time (0);
95 _sub_start_time = time (0);
96 _thread = boost::thread (boost::bind(&Job::run_wrapper, this));
97 #ifdef DCPOMATIC_LINUX
98 pthread_setname_np (_thread.native_handle(), "job-wrapper");
103 /** A wrapper for the ::run() method to catch exceptions */
107 start_of_thread (String::compose("Job-%1", json_name()));
113 } catch (dcp::FileError& e) {
115 string m = String::compose(_("An error occurred whilst handling the file %1."), e.filename().filename());
118 auto const s = dcp::filesystem::space(e.filename());
119 if (s.available < pow (1024, 3)) {
121 m += _("The drive that the film is stored on is low in disc space. Free some more space and try again.");
127 set_error (e.what(), m);
129 set_state (FINISHED_ERROR);
131 } catch (dcp::StartCompressionError& e) {
135 #ifdef DCPOMATIC_WINDOWS
136 #if (__GNUC__ && !__x86_64__)
139 _("Failed to encode the DCP."),
140 _("This error has probably occurred because you are running the 32-bit version of DCP-o-matic and "
141 "trying to use too many encoding threads. Please reduce the 'number of threads DCP-o-matic should "
142 "use' in the General tab of Preferences and try again.")
147 if (running_32_on_64()) {
149 _("Failed to encode the DCP."),
150 _("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.")
160 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
165 set_state (FINISHED_ERROR);
167 } catch (OpenFileError& e) {
170 String::compose (_("Could not open %1"), e.file().string()),
172 _("DCP-o-matic could not open the file %1 (%2). Perhaps it does not exist or is in an unexpected format."),
173 dcp::filesystem::absolute(e.file()).string(),
179 set_state (FINISHED_ERROR);
181 } catch (boost::filesystem::filesystem_error& e) {
183 if (e.code() == boost::system::errc::no_such_file_or_directory) {
185 String::compose (_("Could not open %1"), e.path1().string ()),
187 _("DCP-o-matic could not open the file %1 (%2). Perhaps it does not exist or is in an unexpected format."),
188 dcp::filesystem::absolute(e.path1()).string(),
195 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
200 set_state (FINISHED_ERROR);
202 } catch (boost::thread_interrupted &) {
203 /* The job was cancelled; there's nothing else we need to do here */
204 } catch (sub::SubripError& e) {
206 string extra = "Error is near:\n";
207 for (auto i: e.context()) {
211 set_error (e.what (), extra);
213 set_state (FINISHED_ERROR);
215 } catch (std::bad_alloc& e) {
217 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."));
219 set_state (FINISHED_ERROR);
221 } catch (dcp::ReadError& e) {
223 set_error (e.message(), e.detail().get_value_or(""));
225 set_state (FINISHED_ERROR);
227 } catch (KDMError& e) {
229 set_error (e.summary(), e.detail());
231 set_state (FINISHED_ERROR);
233 } catch (FileError& e) {
235 set_error (e.what(), e.what());
237 set_state (FINISHED_ERROR);
239 } catch (CPLNotFoundError& e) {
243 set_state(FINISHED_ERROR);
245 } catch (std::exception& e) {
249 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
253 set_state (FINISHED_ERROR);
259 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
263 set_state (FINISHED_ERROR);
268 /** @return true if this job is new (ie has not started running) */
272 boost::mutex::scoped_lock lm (_state_mutex);
273 return _state == NEW;
277 /** @return true if the job is running */
279 Job::running () const
281 boost::mutex::scoped_lock lm (_state_mutex);
282 return _state == RUNNING;
286 /** @return true if the job has finished (either successfully or unsuccessfully) */
288 Job::finished () const
290 boost::mutex::scoped_lock lm (_state_mutex);
291 return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
295 /** @return true if the job has finished successfully */
297 Job::finished_ok () const
299 boost::mutex::scoped_lock lm (_state_mutex);
300 return _state == FINISHED_OK;
304 /** @return true if the job has finished unsuccessfully */
306 Job::finished_in_error () const
308 boost::mutex::scoped_lock lm (_state_mutex);
309 return _state == FINISHED_ERROR;
314 Job::finished_cancelled () const
316 boost::mutex::scoped_lock lm (_state_mutex);
317 return _state == FINISHED_CANCELLED;
322 Job::paused_by_user () const
324 boost::mutex::scoped_lock lm (_state_mutex);
325 return _state == PAUSED_BY_USER;
330 Job::paused_by_priority () const
332 boost::mutex::scoped_lock lm (_state_mutex);
333 return _state == PAUSED_BY_PRIORITY;
337 /** Set the state of this job.
338 * @param s New state.
341 Job::set_state (State s)
343 bool finished = false;
346 boost::mutex::scoped_lock lm (_state_mutex);
353 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
354 _finish_time = time(nullptr);
361 auto const result = state_to_result(s);
362 emit(boost::bind(boost::ref(Finished), result));
363 FinishedImmediate(result);
369 Job::state_to_result(State state) const
373 return Result::RESULT_OK;
375 return Result::RESULT_ERROR;
376 case FINISHED_CANCELLED:
377 return Result::RESULT_CANCELLED;
379 DCPOMATIC_ASSERT(false);
382 DCPOMATIC_ASSERT(false);
386 /** @return DCPTime (in seconds) that this sub-job has been running */
388 Job::elapsed_sub_time () const
390 if (_sub_start_time == 0) {
394 return time (0) - _sub_start_time;
398 /** Check to see if this job has been interrupted or paused */
400 Job::check_for_interruption_or_pause ()
402 boost::this_thread::interruption_point ();
404 boost::mutex::scoped_lock lm (_state_mutex);
405 while (_state == PAUSED_BY_USER || _state == PAUSED_BY_PRIORITY) {
406 emit (boost::bind (boost::ref (Progress)));
407 _pause_changed.wait (lm);
413 Job::seconds_since_last_progress_update () const
415 boost::mutex::scoped_lock lm (_progress_mutex);
416 if (!_last_progress_update) {
421 gettimeofday (&now, 0);
423 return seconds(now) - seconds(*_last_progress_update);
427 /** Set the progress of the current part of the job.
428 * @param p Progress (from 0 to 1)
429 * @param force Do not ignore this update, even if it hasn't been long since the last one.
432 Job::set_progress (float p, bool force)
434 check_for_interruption_or_pause ();
436 if (!force && _rate_limit_progress) {
437 /* Check for excessively frequent progress reporting */
438 boost::mutex::scoped_lock lm (_progress_mutex);
440 gettimeofday (&now, 0);
441 if (_last_progress_update && _last_progress_update->tv_sec > 0) {
442 double const elapsed = seconds(now) - seconds(*_last_progress_update);
447 _last_progress_update = now;
450 set_progress_common (p);
455 Job::set_progress_common (optional<float> p)
458 boost::mutex::scoped_lock lm (_progress_mutex);
462 emit (boost::bind (boost::ref (Progress)));
466 /** @return fractional progress of the current sub-job, if known */
468 Job::progress () const
470 boost::mutex::scoped_lock lm (_progress_mutex);
479 boost::mutex::scoped_lock lm (_progress_mutex);
480 LOG_GENERAL ("Sub-job %1 starting", n);
484 set_progress (0, true);
485 _sub_start_time = time (0);
490 Job::error_details () const
492 boost::mutex::scoped_lock lm (_state_mutex);
493 return _error_details;
497 /** @return A summary of any error that the job has generated */
499 Job::error_summary () const
501 boost::mutex::scoped_lock lm (_state_mutex);
502 return _error_summary;
506 /** Set the current error string.
507 * @param s New error string.
508 * @param d New error detail string.
511 Job::set_error (string s, string d)
514 _film->log()->log (String::compose ("Error in job: %1 (%2)", s, d), LogEntry::TYPE_ERROR);
517 boost::mutex::scoped_lock lm (_state_mutex);
523 /** Say that this job's progress will be unknown until further notice */
525 Job::set_progress_unknown ()
527 check_for_interruption_or_pause ();
528 set_progress_common (optional<float> ());
532 /** @return Human-readable status of this job */
536 optional<float> p = progress ();
537 int const t = elapsed_sub_time ();
538 int const r = remaining_time ();
540 auto day_of_week_to_string = [](boost::gregorian::greg_weekday d) -> std::string {
541 switch (d.as_enum()) {
542 case boost::date_time::Sunday:
544 case boost::date_time::Monday:
546 case boost::date_time::Tuesday:
548 case boost::date_time::Wednesday:
549 return _("Wednesday");
550 case boost::date_time::Thursday:
551 return _("Thursday");
552 case boost::date_time::Friday:
554 case boost::date_time::Saturday:
555 return _("Saturday");
558 return d.as_long_string();
562 if (!finished () && p) {
563 int pc = lrintf (p.get() * 100);
565 /* 100% makes it sound like we've finished when we haven't */
570 snprintf (buffer, sizeof(buffer), "%d%%", pc);
573 if (t > 10 && r > 0) {
574 auto now = boost::posix_time::second_clock::local_time();
575 auto finish = now + boost::posix_time::seconds(r);
576 char finish_string[16];
577 snprintf (finish_string, sizeof(finish_string), "%02d:%02d", int(finish.time_of_day().hours()), int(finish.time_of_day().minutes()));
579 if (now.date() != finish.date()) {
580 /// TRANSLATORS: the %1 in this string will be filled in with a day of the week
581 /// to say what day a job will finish.
582 day = String::compose (_(" on %1"), day_of_week_to_string(finish.date().day_of_week()));
584 /// TRANSLATORS: "remaining; finishing at" here follows an amount of time that is remaining
585 /// on an operation; after it is an estimated wall-clock completion time.
586 s += String::compose(
587 _("; %1 remaining; finishing at %2%3"),
588 seconds_to_approximate_hms(r), finish_string, day
591 } else if (finished_ok ()) {
592 auto time_string = [](time_t time) {
593 auto tm = localtime(&time);
595 snprintf(buffer, sizeof(buffer), "%02d:%02d", tm->tm_hour, tm->tm_min);
596 return string(buffer);
598 auto const duration = _finish_time - _start_time;
600 /* It took less than 10 seconds; it doesn't seem worth saying how long it took */
602 } else if (duration < 600) {
603 /* It took less than 10 minutes; it doesn't seem worth saying when it started and finished */
604 s = String::compose(_("OK (ran for %1)"), seconds_to_hms(duration));
606 s = String::compose(_("OK (ran for %1 from %2 to %3)"), seconds_to_hms(duration), time_string(_start_time), time_string(_finish_time));
608 } else if (finished_in_error ()) {
609 s = String::compose (_("Error: %1"), error_summary ());
610 } else if (finished_cancelled ()) {
619 Job::json_status () const
621 boost::mutex::scoped_lock lm (_state_mutex);
627 return N_("running");
629 case PAUSED_BY_PRIORITY:
632 return N_("finished_ok");
634 return N_("finished_error");
635 case FINISHED_CANCELLED:
636 return N_("finished_cancelled");
643 /** @return An estimate of the remaining time for this sub-job, in seconds */
645 Job::remaining_time () const
647 if (progress().get_value_or(0) == 0) {
648 return elapsed_sub_time ();
651 return elapsed_sub_time() / progress().get() - elapsed_sub_time();
658 if (_thread.joinable()) {
661 _thread.interrupt ();
665 set_state (FINISHED_CANCELLED);
669 /** @return true if the job was paused, false if it was not running */
671 Job::pause_by_user ()
675 boost::mutex::scoped_lock lm (_state_mutex);
676 /* We can set _state here directly because we have a lock and we aren't
677 setting the job to FINISHED_*
679 if (_state == RUNNING) {
681 _state = PAUSED_BY_USER;
686 _pause_changed.notify_all ();
694 Job::pause_by_priority ()
697 set_state (PAUSED_BY_PRIORITY);
698 _pause_changed.notify_all ();
706 if (paused_by_user() || paused_by_priority()) {
708 _pause_changed.notify_all ();
714 Job::when_finished(boost::signals2::connection& connection, function<void(Result)> finished)
716 boost::mutex::scoped_lock lm (_state_mutex);
717 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
718 finished(state_to_result(_state));
720 connection = Finished.connect (finished);
726 Job::message () const
728 boost::mutex::scoped_lock lm (_state_mutex);
734 Job::set_message (string m)
736 boost::mutex::scoped_lock lm (_state_mutex);
742 Job::set_rate_limit_progress(bool rate_limit)
744 _rate_limit_progress = rate_limit;