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