Don't use --target-macos-arm64 any more, since it's not supported.
[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
22 /** @file  src/job.cc
23  *  @brief A parent class to represent long-running tasks which are run in their own thread.
24  */
25
26
27 #include "compose.hpp"
28 #include "constants.h"
29 #include "cross.h"
30 #include "dcpomatic_log.h"
31 #include "exceptions.h"
32 #include "film.h"
33 #include "job.h"
34 #include "log.h"
35 #include "util.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>
41 #include <time.h>
42 #include <iostream>
43
44 #include "i18n.h"
45
46
47 using std::cout;
48 using std::function;
49 using std::list;
50 using std::shared_ptr;
51 using std::string;
52 using boost::optional;
53 using namespace dcpomatic;
54
55
56 /** @param film Associated film, or 0 */
57 Job::Job (shared_ptr<const Film> film)
58         : _film (film)
59         , _state (NEW)
60         , _sub_start_time (0)
61         , _progress (0)
62         , _rate_limit_progress(true)
63 {
64
65 }
66
67
68 Job::~Job ()
69 {
70 #ifdef DCPOMATIC_DEBUG
71         /* Any subclass should have called stop_thread in its destructor */
72         assert (!_thread.joinable());
73 #endif
74 }
75
76
77 void
78 Job::stop_thread ()
79 {
80         boost::this_thread::disable_interruption dis;
81
82         _thread.interrupt ();
83         try {
84                 _thread.join ();
85         } catch (...) {}
86 }
87
88
89 /** Start the job in a separate thread, returning immediately */
90 void
91 Job::start ()
92 {
93         set_state (RUNNING);
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");
99 #endif
100 }
101
102
103 /** A wrapper for the ::run() method to catch exceptions */
104 void
105 Job::run_wrapper ()
106 {
107         start_of_thread (String::compose("Job-%1", json_name()));
108
109         try {
110
111                 run ();
112
113         } catch (dcp::FileError& e) {
114
115                 string m = String::compose(_("An error occurred whilst handling the file %1."), e.filename().filename());
116
117                 try {
118                         auto const s = dcp::filesystem::space(e.filename());
119                         if (s.available < pow (1024, 3)) {
120                                 m += N_("\n\n");
121                                 m += _("The drive that the film is stored on is low in disc space.  Free some more space and try again.");
122                         }
123                 } catch (...) {
124
125                 }
126
127                 set_error (e.what(), m);
128                 set_progress (1);
129                 set_state (FINISHED_ERROR);
130
131         } catch (dcp::StartCompressionError& e) {
132
133                 bool done = false;
134
135 #ifdef DCPOMATIC_WINDOWS
136 #if (__GNUC__ && !__x86_64__)
137                 /* 32-bit */
138                 set_error (
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.")
143                         );
144                 done = true;
145 #else
146                 /* 64-bit */
147                 if (running_32_on_64()) {
148                         set_error (
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.")
151                                 );
152                         done = true;
153                 }
154 #endif
155 #endif
156
157                 if (!done) {
158                         set_error (
159                                 e.what (),
160                                 string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
161                                 );
162                 }
163
164                 set_progress (1);
165                 set_state (FINISHED_ERROR);
166
167         } catch (OpenFileError& e) {
168
169                 set_error (
170                         String::compose (_("Could not open %1"), e.file().string()),
171                         String::compose (
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(),
174                                 e.what()
175                                 )
176                         );
177
178                 set_progress (1);
179                 set_state (FINISHED_ERROR);
180
181         } catch (boost::filesystem::filesystem_error& e) {
182
183                 if (e.code() == boost::system::errc::no_such_file_or_directory) {
184                         set_error (
185                                 String::compose (_("Could not open %1"), e.path1().string ()),
186                                 String::compose (
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(),
189                                         e.what()
190                                         )
191                                 );
192                 } else {
193                         set_error (
194                                 e.what (),
195                                 string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
196                                 );
197                 }
198
199                 set_progress (1);
200                 set_state (FINISHED_ERROR);
201
202         } catch (boost::thread_interrupted &) {
203                 /* The job was cancelled; there's nothing else we need to do here */
204         } catch (sub::SubripError& e) {
205
206                 string extra = "Error is near:\n";
207                 for (auto i: e.context()) {
208                         extra += i + "\n";
209                 }
210
211                 set_error (e.what (), extra);
212                 set_progress (1);
213                 set_state (FINISHED_ERROR);
214
215         } catch (std::bad_alloc& e) {
216
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."));
218                 set_progress (1);
219                 set_state (FINISHED_ERROR);
220
221         } catch (dcp::ReadError& e) {
222
223                 set_error (e.message(), e.detail().get_value_or(""));
224                 set_progress (1);
225                 set_state (FINISHED_ERROR);
226
227         } catch (KDMError& e) {
228
229                 set_error (e.summary(), e.detail());
230                 set_progress (1);
231                 set_state (FINISHED_ERROR);
232
233         } catch (FileError& e) {
234
235                 set_error (e.what(), e.what());
236                 set_progress (1);
237                 set_state (FINISHED_ERROR);
238
239         } catch (CPLNotFoundError& e) {
240
241                 set_error(e.what());
242                 set_progress(1);
243                 set_state(FINISHED_ERROR);
244
245         } catch (MissingConfigurationError& e) {
246
247                 set_error(e.what());
248                 set_progress(1);
249                 set_state(FINISHED_ERROR);
250
251         } catch (std::exception& e) {
252
253                 set_error (
254                         e.what (),
255                         string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
256                         );
257
258                 set_progress (1);
259                 set_state (FINISHED_ERROR);
260
261         } catch (...) {
262
263                 set_error (
264                         _("Unknown error"),
265                         string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
266                         );
267
268                 set_progress (1);
269                 set_state (FINISHED_ERROR);
270         }
271 }
272
273
274 /** @return true if this job is new (ie has not started running) */
275 bool
276 Job::is_new () const
277 {
278         boost::mutex::scoped_lock lm (_state_mutex);
279         return _state == NEW;
280 }
281
282
283 /** @return true if the job is running */
284 bool
285 Job::running () const
286 {
287         boost::mutex::scoped_lock lm (_state_mutex);
288         return _state == RUNNING;
289 }
290
291
292 /** @return true if the job has finished (either successfully or unsuccessfully) */
293 bool
294 Job::finished () const
295 {
296         boost::mutex::scoped_lock lm (_state_mutex);
297         return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
298 }
299
300
301 /** @return true if the job has finished successfully */
302 bool
303 Job::finished_ok () const
304 {
305         boost::mutex::scoped_lock lm (_state_mutex);
306         return _state == FINISHED_OK;
307 }
308
309
310 /** @return true if the job has finished unsuccessfully */
311 bool
312 Job::finished_in_error () const
313 {
314         boost::mutex::scoped_lock lm (_state_mutex);
315         return _state == FINISHED_ERROR;
316 }
317
318
319 bool
320 Job::finished_cancelled () const
321 {
322         boost::mutex::scoped_lock lm (_state_mutex);
323         return _state == FINISHED_CANCELLED;
324 }
325
326
327 bool
328 Job::paused_by_user () const
329 {
330         boost::mutex::scoped_lock lm (_state_mutex);
331         return _state == PAUSED_BY_USER;
332 }
333
334
335 bool
336 Job::paused_by_priority () const
337 {
338         boost::mutex::scoped_lock lm (_state_mutex);
339         return _state == PAUSED_BY_PRIORITY;
340 }
341
342
343 /** Set the state of this job.
344  *  @param s New state.
345  */
346 void
347 Job::set_state (State s)
348 {
349         bool finished = false;
350
351         {
352                 boost::mutex::scoped_lock lm (_state_mutex);
353                 if (_state == s) {
354                         return;
355                 }
356
357                 _state = s;
358
359                 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
360                         _finish_time = time(nullptr);
361                         finished = true;
362                         _sub_name.clear ();
363                 }
364         }
365
366         if (finished) {
367                 auto const result = state_to_result(s);
368                 emit(boost::bind(boost::ref(Finished), result));
369                 FinishedImmediate(result);
370         }
371 }
372
373
374 Job::Result
375 Job::state_to_result(State state) const
376 {
377         switch (state) {
378         case FINISHED_OK:
379                 return Result::RESULT_OK;
380         case FINISHED_ERROR:
381                 return Result::RESULT_ERROR;
382         case FINISHED_CANCELLED:
383                 return Result::RESULT_CANCELLED;
384         default:
385                 DCPOMATIC_ASSERT(false);
386         };
387
388         DCPOMATIC_ASSERT(false);
389 }
390
391
392 /** @return DCPTime (in seconds) that this sub-job has been running */
393 int
394 Job::elapsed_sub_time () const
395 {
396         if (_sub_start_time == 0) {
397                 return 0;
398         }
399
400         return time (0) - _sub_start_time;
401 }
402
403
404 /** Check to see if this job has been interrupted or paused */
405 void
406 Job::check_for_interruption_or_pause ()
407 {
408         boost::this_thread::interruption_point ();
409
410         boost::mutex::scoped_lock lm (_state_mutex);
411         while (_state == PAUSED_BY_USER || _state == PAUSED_BY_PRIORITY) {
412                 emit (boost::bind (boost::ref (Progress)));
413                 _pause_changed.wait (lm);
414         }
415 }
416
417
418 optional<float>
419 Job::seconds_since_last_progress_update () const
420 {
421         boost::mutex::scoped_lock lm (_progress_mutex);
422         if (!_last_progress_update) {
423                 return {};
424         }
425
426         struct timeval now;
427         gettimeofday (&now, 0);
428
429         return seconds(now) - seconds(*_last_progress_update);
430 }
431
432
433 /** Set the progress of the current part of the job.
434  *  @param p Progress (from 0 to 1)
435  *  @param force Do not ignore this update, even if it hasn't been long since the last one.
436  */
437 void
438 Job::set_progress (float p, bool force)
439 {
440         check_for_interruption_or_pause ();
441
442         if (!force && _rate_limit_progress) {
443                 /* Check for excessively frequent progress reporting */
444                 boost::mutex::scoped_lock lm (_progress_mutex);
445                 struct timeval now;
446                 gettimeofday (&now, 0);
447                 if (_last_progress_update && _last_progress_update->tv_sec > 0) {
448                         double const elapsed = seconds(now) - seconds(*_last_progress_update);
449                         if (elapsed < 0.5) {
450                                 return;
451                         }
452                 }
453                 _last_progress_update = now;
454         }
455
456         set_progress_common (p);
457 }
458
459
460 void
461 Job::set_progress_common (optional<float> p)
462 {
463         {
464                 boost::mutex::scoped_lock lm (_progress_mutex);
465                 _progress = p;
466         }
467
468         emit (boost::bind (boost::ref (Progress)));
469 }
470
471
472 /** @return fractional progress of the current sub-job, if known */
473 optional<float>
474 Job::progress () const
475 {
476         boost::mutex::scoped_lock lm (_progress_mutex);
477         return _progress;
478 }
479
480
481 void
482 Job::sub (string n)
483 {
484         {
485                 boost::mutex::scoped_lock lm (_progress_mutex);
486                 LOG_GENERAL ("Sub-job %1 starting", n);
487                 _sub_name = n;
488         }
489
490         set_progress (0, true);
491         _sub_start_time = time (0);
492 }
493
494
495 string
496 Job::error_details () const
497 {
498         boost::mutex::scoped_lock lm (_state_mutex);
499         return _error_details;
500 }
501
502
503 /** @return A summary of any error that the job has generated */
504 string
505 Job::error_summary () const
506 {
507         boost::mutex::scoped_lock lm (_state_mutex);
508         return _error_summary;
509 }
510
511
512 /** Set the current error string.
513  *  @param s New error string.
514  *  @param d New error detail string.
515  */
516 void
517 Job::set_error (string s, string d)
518 {
519         if (_film) {
520                 _film->log()->log (String::compose ("Error in job: %1 (%2)", s, d), LogEntry::TYPE_ERROR);
521         }
522
523         boost::mutex::scoped_lock lm (_state_mutex);
524         _error_summary = s;
525         _error_details = d;
526 }
527
528
529 /** Say that this job's progress will be unknown until further notice */
530 void
531 Job::set_progress_unknown ()
532 {
533         check_for_interruption_or_pause ();
534         set_progress_common (optional<float> ());
535 }
536
537
538 /** @return Human-readable status of this job */
539 string
540 Job::status () const
541 {
542         optional<float> p = progress ();
543         int const t = elapsed_sub_time ();
544         int const r = remaining_time ();
545
546         auto day_of_week_to_string = [](boost::gregorian::greg_weekday d) -> std::string {
547                 switch (d.as_enum()) {
548                 case boost::date_time::Sunday:
549                         return _("Sunday");
550                 case boost::date_time::Monday:
551                         return _("Monday");
552                 case boost::date_time::Tuesday:
553                         return _("Tuesday");
554                 case boost::date_time::Wednesday:
555                         return _("Wednesday");
556                 case boost::date_time::Thursday:
557                         return _("Thursday");
558                 case boost::date_time::Friday:
559                         return _("Friday");
560                 case boost::date_time::Saturday:
561                         return _("Saturday");
562                 }
563
564                 return d.as_long_string();
565         };
566
567         string s;
568         if (!finished () && p) {
569                 int pc = lrintf (p.get() * 100);
570                 if (pc == 100) {
571                         /* 100% makes it sound like we've finished when we haven't */
572                         pc = 99;
573                 }
574
575                 char buffer[64];
576                 snprintf (buffer, sizeof(buffer), "%d%%", pc);
577                 s += buffer;
578
579                 if (t > 10 && r > 0) {
580                         auto now = boost::posix_time::second_clock::local_time();
581                         auto finish = now + boost::posix_time::seconds(r);
582                         char finish_string[16];
583                         snprintf (finish_string, sizeof(finish_string), "%02d:%02d", int(finish.time_of_day().hours()), int(finish.time_of_day().minutes()));
584                         string day;
585                         if (now.date() != finish.date()) {
586                                 /// TRANSLATORS: the %1 in this string will be filled in with a day of the week
587                                 /// to say what day a job will finish.
588                                 day = String::compose (_(" on %1"), day_of_week_to_string(finish.date().day_of_week()));
589                         }
590                         /// TRANSLATORS: "remaining; finishing at" here follows an amount of time that is remaining
591                         /// on an operation; after it is an estimated wall-clock completion time.
592                         s += String::compose(
593                                 _("; %1 remaining; finishing at %2%3"),
594                                 seconds_to_approximate_hms(r), finish_string, day
595                                 );
596                 }
597         } else if (finished_ok ()) {
598                 auto time_string = [](time_t time) {
599                         auto tm = localtime(&time);
600                         char buffer[8];
601                         snprintf(buffer, sizeof(buffer), "%02d:%02d", tm->tm_hour, tm->tm_min);
602                         return string(buffer);
603                 };
604                 auto const duration = _finish_time - _start_time;
605                 if (duration < 10) {
606                         /* It took less than 10 seconds; it doesn't seem worth saying how long it took */
607                         s = _("OK");
608                 } else if (duration < 600) {
609                         /* It took less than 10 minutes; it doesn't seem worth saying when it started and finished */
610                         s = String::compose(_("OK (ran for %1)"), seconds_to_hms(duration));
611                 } else {
612                         s = String::compose(_("OK (ran for %1 from %2 to %3)"),  seconds_to_hms(duration), time_string(_start_time), time_string(_finish_time));
613                 }
614         } else if (finished_in_error ()) {
615                 s = String::compose (_("Error: %1"), error_summary ());
616         } else if (finished_cancelled ()) {
617                 s = _("Cancelled");
618         }
619
620         return s;
621 }
622
623
624 string
625 Job::json_status () const
626 {
627         boost::mutex::scoped_lock lm (_state_mutex);
628
629         switch (_state) {
630         case NEW:
631                 return N_("new");
632         case RUNNING:
633                 return N_("running");
634         case PAUSED_BY_USER:
635         case PAUSED_BY_PRIORITY:
636                 return N_("paused");
637         case FINISHED_OK:
638                 return N_("finished_ok");
639         case FINISHED_ERROR:
640                 return N_("finished_error");
641         case FINISHED_CANCELLED:
642                 return N_("finished_cancelled");
643         }
644
645         return "";
646 }
647
648
649 /** @return An estimate of the remaining time for this sub-job, in seconds */
650 int
651 Job::remaining_time () const
652 {
653         if (progress().get_value_or(0) == 0) {
654                 return elapsed_sub_time ();
655         }
656
657         return elapsed_sub_time() / progress().get() - elapsed_sub_time();
658 }
659
660
661 void
662 Job::cancel ()
663 {
664         if (_thread.joinable()) {
665                 resume();
666
667                 _thread.interrupt ();
668                 _thread.join ();
669         }
670
671         set_state (FINISHED_CANCELLED);
672 }
673
674
675 /** @return true if the job was paused, false if it was not running */
676 bool
677 Job::pause_by_user ()
678 {
679         bool paused = false;
680         {
681                 boost::mutex::scoped_lock lm (_state_mutex);
682                 /* We can set _state here directly because we have a lock and we aren't
683                    setting the job to FINISHED_*
684                 */
685                 if (_state == RUNNING) {
686                         paused = true;
687                         _state = PAUSED_BY_USER;
688                 }
689         }
690
691         if (paused) {
692                 _pause_changed.notify_all ();
693         }
694
695         return paused;
696 }
697
698
699 void
700 Job::pause_by_priority ()
701 {
702         if (running ()) {
703                 set_state (PAUSED_BY_PRIORITY);
704                 _pause_changed.notify_all ();
705         }
706 }
707
708
709 void
710 Job::resume ()
711 {
712         if (paused_by_user() || paused_by_priority()) {
713                 set_state (RUNNING);
714                 _pause_changed.notify_all ();
715         }
716 }
717
718
719 void
720 Job::when_finished(boost::signals2::connection& connection, function<void(Result)> finished)
721 {
722         boost::mutex::scoped_lock lm (_state_mutex);
723         if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
724                 finished(state_to_result(_state));
725         } else {
726                 connection = Finished.connect (finished);
727         }
728 }
729
730
731 optional<string>
732 Job::message () const
733 {
734         boost::mutex::scoped_lock lm (_state_mutex);
735         return _message;
736 }
737
738
739 void
740 Job::set_message (string m)
741 {
742         boost::mutex::scoped_lock lm (_state_mutex);
743         _message = m;
744 }
745
746
747 void
748 Job::set_rate_limit_progress(bool rate_limit)
749 {
750         _rate_limit_progress = rate_limit;
751 }
752