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