Fix crash on 'report a problem' in the KDM creator.
[dcpomatic.git] / src / lib / job.cc
1 /*
2     Copyright (C) 2012-2016 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 "compose.hpp"
32 #include <dcp/exceptions.h>
33 #include <sub/exceptions.h>
34 #include <boost/thread.hpp>
35 #include <boost/filesystem.hpp>
36 #include <boost/foreach.hpp>
37 #include <iostream>
38
39 #include "i18n.h"
40
41 using std::string;
42 using std::list;
43 using std::cout;
44 using boost::shared_ptr;
45 using boost::optional;
46 using boost::function;
47
48 #define LOG_ERROR_NC(...) if (_film) { _film->log()->log (__VA_ARGS__, LogEntry::TYPE_ERROR); }
49 #define LOG_GENERAL(...) if (_film) { _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_GENERAL); }
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         if (_thread) {
67                 _thread->interrupt ();
68                 /* We can't use DCPOMATIC_ASSERT here as it may throw an exception */
69                 if (_thread->joinable ()) {
70                         try {
71                                 _thread->join ();
72                         } catch (...) {
73                                 /* Too late to do anything about this */
74                         }
75                 }
76         }
77
78         delete _thread;
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 = new boost::thread (boost::bind (&Job::run_wrapper, this));
89 }
90
91 /** A wrapper for the ::run() method to catch exceptions */
92 void
93 Job::run_wrapper ()
94 {
95         try {
96
97                 run ();
98
99         } catch (dcp::FileError& e) {
100
101                 string m = String::compose (_("An error occurred whilst handling the file %1."), boost::filesystem::path (e.filename()).leaf());
102
103                 try {
104                         boost::filesystem::space_info const s = boost::filesystem::space (e.filename());
105                         if (s.available < pow (1024, 3)) {
106                                 m += N_("\n\n");
107                                 m += _("The drive that the film is stored on is low in disc space.  Free some more space and try again.");
108                         }
109                 } catch (...) {
110
111                 }
112
113                 set_error (e.what(), m);
114                 set_progress (1);
115                 set_state (FINISHED_ERROR);
116
117         } catch (OpenFileError& e) {
118
119                 set_error (
120                         String::compose (_("Could not open %1"), e.file().string()),
121                         String::compose (
122                                 _("DCP-o-matic could not open the file %1.  Perhaps it does not exist or is in an unexpected format."),
123                                 boost::filesystem::absolute (e.file()).string()
124                                 )
125                         );
126
127                 set_progress (1);
128                 set_state (FINISHED_ERROR);
129
130         } catch (boost::filesystem::filesystem_error& e) {
131
132                 if (e.code() == boost::system::errc::no_such_file_or_directory) {
133                         set_error (
134                                 String::compose (_("Could not open %1"), e.path1().string ()),
135                                 String::compose (
136                                         _("DCP-o-matic could not open the file %1.  Perhaps it does not exist or is in an unexpected format."),
137                                         boost::filesystem::absolute (e.path1()).string()
138                                         )
139                                 );
140                 } else {
141                         set_error (
142                                 e.what (),
143                                 string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
144                                 );
145                 }
146
147                 set_progress (1);
148                 set_state (FINISHED_ERROR);
149
150         } catch (boost::thread_interrupted &) {
151
152                 set_state (FINISHED_CANCELLED);
153
154         } catch (sub::SubripError& e) {
155
156                 string extra = "Error is near:\n";
157                 BOOST_FOREACH (string i, e.context()) {
158                         extra += i + "\n";
159                 }
160
161                 set_error (e.what (), extra);
162                 set_progress (1);
163                 set_state (FINISHED_ERROR);
164
165         } catch (std::bad_alloc& e) {
166
167                 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."));
168                 set_progress (1);
169                 set_state (FINISHED_ERROR);
170
171         } catch (std::exception& e) {
172
173                 set_error (
174                         e.what (),
175                         string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
176                         );
177
178                 set_progress (1);
179                 set_state (FINISHED_ERROR);
180
181         } catch (...) {
182
183                 set_error (
184                         _("Unknown error"),
185                         string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
186                         );
187
188                 set_progress (1);
189                 set_state (FINISHED_ERROR);
190         }
191 }
192
193 /** @return true if this job is new (ie has not started running) */
194 bool
195 Job::is_new () const
196 {
197         boost::mutex::scoped_lock lm (_state_mutex);
198         return _state == NEW;
199 }
200
201 /** @return true if the job is running */
202 bool
203 Job::running () const
204 {
205         boost::mutex::scoped_lock lm (_state_mutex);
206         return _state == RUNNING;
207 }
208
209 /** @return true if the job has finished (either successfully or unsuccessfully) */
210 bool
211 Job::finished () const
212 {
213         boost::mutex::scoped_lock lm (_state_mutex);
214         return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
215 }
216
217 /** @return true if the job has finished successfully */
218 bool
219 Job::finished_ok () const
220 {
221         boost::mutex::scoped_lock lm (_state_mutex);
222         return _state == FINISHED_OK;
223 }
224
225 /** @return true if the job has finished unsuccessfully */
226 bool
227 Job::finished_in_error () const
228 {
229         boost::mutex::scoped_lock lm (_state_mutex);
230         return _state == FINISHED_ERROR;
231 }
232
233 bool
234 Job::finished_cancelled () const
235 {
236         boost::mutex::scoped_lock lm (_state_mutex);
237         return _state == FINISHED_CANCELLED;
238 }
239
240 bool
241 Job::paused () const
242 {
243         boost::mutex::scoped_lock lm (_state_mutex);
244         return _state == PAUSED;
245 }
246
247 /** Set the state of this job.
248  *  @param s New state.
249  */
250 void
251 Job::set_state (State s)
252 {
253         bool finished = false;
254
255         {
256                 boost::mutex::scoped_lock lm (_state_mutex);
257                 _state = s;
258
259                 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
260                         _ran_for = time(0) - _start_time;
261                         finished = true;
262                         _sub_name.clear ();
263                 }
264         }
265
266         if (finished) {
267                 emit (boost::bind (boost::ref (Finished)));
268         }
269 }
270
271 /** @return DCPTime (in seconds) that this sub-job has been running */
272 int
273 Job::elapsed_sub_time () const
274 {
275         if (_sub_start_time == 0) {
276                 return 0;
277         }
278
279         return time (0) - _sub_start_time;
280 }
281
282 /** Set the progress of the current part of the job.
283  *  @param p Progress (from 0 to 1)
284  */
285 void
286 Job::set_progress (float p, bool force)
287 {
288         if (!force) {
289                 /* Check for excessively frequent progress reporting */
290                 boost::mutex::scoped_lock lm (_progress_mutex);
291                 struct timeval now;
292                 gettimeofday (&now, 0);
293                 if (_last_progress_update && _last_progress_update->tv_sec > 0) {
294                         double const elapsed = (now.tv_sec + now.tv_usec / 1000000.0)
295                                 - (_last_progress_update->tv_sec + _last_progress_update->tv_usec / 1000000.0);
296                         if (elapsed < 0.5) {
297                                 return;
298                         }
299                 }
300                 _last_progress_update = now;
301         }
302
303         set_progress_common (p);
304 }
305
306 void
307 Job::set_progress_common (optional<float> p)
308 {
309         boost::mutex::scoped_lock lm (_progress_mutex);
310         _progress = p;
311         boost::this_thread::interruption_point ();
312
313         boost::mutex::scoped_lock lm2 (_state_mutex);
314         while (_state == PAUSED) {
315                 _pause_changed.wait (lm2);
316         }
317
318         lm.unlock ();
319         lm2.unlock ();
320
321         emit (boost::bind (boost::ref (Progress)));
322 }
323
324 /** @return fractional progress of the current sub-job, if known */
325 optional<float>
326 Job::progress () const
327 {
328         boost::mutex::scoped_lock lm (_progress_mutex);
329         return _progress;
330 }
331
332 void
333 Job::sub (string n)
334 {
335         {
336                 boost::mutex::scoped_lock lm (_progress_mutex);
337                 LOG_GENERAL ("Sub-job %1 starting", n);
338                 _sub_name = n;
339         }
340
341         set_progress (0, true);
342         _sub_start_time = time (0);
343 }
344
345 string
346 Job::error_details () const
347 {
348         boost::mutex::scoped_lock lm (_state_mutex);
349         return _error_details;
350 }
351
352 /** @return A summary of any error that the job has generated */
353 string
354 Job::error_summary () const
355 {
356         boost::mutex::scoped_lock lm (_state_mutex);
357         return _error_summary;
358 }
359
360 /** Set the current error string.
361  *  @param e New error string.
362  */
363 void
364 Job::set_error (string s, string d)
365 {
366         if (_film) {
367                 LOG_ERROR_NC (s);
368                 LOG_ERROR_NC (d);
369                 _film->log()->log (String::compose ("Error in job: %1 (%2)", s, d), LogEntry::TYPE_ERROR);
370         }
371
372         boost::mutex::scoped_lock lm (_state_mutex);
373         _error_summary = s;
374         _error_details = d;
375 }
376
377 /** Say that this job's progress will be unknown until further notice */
378 void
379 Job::set_progress_unknown ()
380 {
381         set_progress_common (optional<float> ());
382 }
383
384 /** @return Human-readable status of this job */
385 string
386 Job::status () const
387 {
388         optional<float> p = progress ();
389         int const t = elapsed_sub_time ();
390         int const r = remaining_time ();
391
392         string s;
393         if (!finished () && p) {
394                 int pc = lrintf (p.get() * 100);
395                 if (pc == 100) {
396                         /* 100% makes it sound like we've finished when we haven't */
397                         pc = 99;
398                 }
399
400                 char buffer[64];
401                 snprintf (buffer, sizeof(buffer), "%d%%", pc);
402                 s += buffer;
403
404                 if (t > 10 && r > 0) {
405                         /// TRANSLATORS: remaining here follows an amount of time that is remaining
406                         /// on an operation.
407                         s += "; " + seconds_to_approximate_hms (r) + " " + _("remaining");
408                 }
409         } else if (finished_ok ()) {
410                 s = String::compose (_("OK (ran for %1)"), seconds_to_hms (_ran_for));
411         } else if (finished_in_error ()) {
412                 s = String::compose (_("Error: %1"), error_summary ());
413         } else if (finished_cancelled ()) {
414                 s = _("Cancelled");
415         }
416
417         return s;
418 }
419
420 string
421 Job::json_status () const
422 {
423         boost::mutex::scoped_lock lm (_state_mutex);
424
425         switch (_state) {
426         case NEW:
427                 return N_("new");
428         case RUNNING:
429                 return N_("running");
430         case PAUSED:
431                 return N_("paused");
432         case FINISHED_OK:
433                 return N_("finished_ok");
434         case FINISHED_ERROR:
435                 return N_("finished_error");
436         case FINISHED_CANCELLED:
437                 return N_("finished_cancelled");
438         }
439
440         return "";
441 }
442
443 /** @return An estimate of the remaining time for this sub-job, in seconds */
444 int
445 Job::remaining_time () const
446 {
447         if (progress().get_value_or(0) == 0) {
448                 return elapsed_sub_time ();
449         }
450
451         return elapsed_sub_time() / progress().get() - elapsed_sub_time();
452 }
453
454 void
455 Job::cancel ()
456 {
457         if (!_thread) {
458                 return;
459         }
460
461         if (paused ()) {
462                 resume ();
463         }
464
465         _thread->interrupt ();
466         DCPOMATIC_ASSERT (_thread->joinable ());
467         _thread->join ();
468         delete _thread;
469         _thread = 0;
470 }
471
472 void
473 Job::pause ()
474 {
475         if (running ()) {
476                 set_state (PAUSED);
477                 _pause_changed.notify_all ();
478         }
479 }
480
481 void
482 Job::resume ()
483 {
484         if (paused ()) {
485                 set_state (RUNNING);
486                 _pause_changed.notify_all ();
487         }
488 }
489
490 void
491 Job::when_finished (boost::signals2::connection& connection, function<void()> finished)
492 {
493         boost::mutex::scoped_lock lm (_state_mutex);
494         if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
495                 finished ();
496         } else {
497                 connection = Finished.connect (finished);
498         }
499 }