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