2c2e0667329c1c0ef435d036fd31c256d109000a
[dcpomatic.git] / src / lib / job.cc
1 /*
2     Copyright (C) 2012-2015 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 /** @file  src/job.cc
21  *  @brief A parent class to represent long-running tasks which are run in their own thread.
22  */
23
24 #include "job.h"
25 #include "util.h"
26 #include "cross.h"
27 #include "exceptions.h"
28 #include "film.h"
29 #include "log.h"
30 #include "compose.hpp"
31 #include <dcp/exceptions.h>
32 #include <boost/thread.hpp>
33 #include <boost/filesystem.hpp>
34 #include <iostream>
35
36 #include "i18n.h"
37
38 using std::string;
39 using std::list;
40 using std::cout;
41 using boost::shared_ptr;
42 using boost::optional;
43 using boost::function;
44
45 #define LOG_ERROR_NC(...) _film->log()->log (__VA_ARGS__, LogEntry::TYPE_ERROR);
46 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_GENERAL);
47
48 /** @param film Associated film, or 0 */
49 Job::Job (shared_ptr<const Film> film)
50         : _film (film)
51         , _thread (0)
52         , _state (NEW)
53         , _start_time (0)
54         , _progress (0)
55         , _ran_for (0)
56 {
57
58 }
59
60 Job::~Job ()
61 {
62         if (_thread) {
63                 _thread->interrupt ();
64                 DCPOMATIC_ASSERT (_thread->joinable ());
65                 _thread->join ();
66         }
67
68         delete _thread;
69 }
70
71 /** Start the job in a separate thread, returning immediately */
72 void
73 Job::start ()
74 {
75         set_state (RUNNING);
76         _start_time = time (0);
77         _thread = new boost::thread (boost::bind (&Job::run_wrapper, this));
78 }
79
80 /** A wrapper for the ::run() method to catch exceptions */
81 void
82 Job::run_wrapper ()
83 {
84         try {
85
86                 run ();
87
88         } catch (dcp::FileError& e) {
89
90                 string m = String::compose (_("An error occurred whilst handling the file %1."), boost::filesystem::path (e.filename()).leaf());
91
92                 try {
93                         boost::filesystem::space_info const s = boost::filesystem::space (e.filename());
94                         if (s.available < pow (1024, 3)) {
95                                 m += N_("\n\n");
96                                 m += _("The drive that the film is stored on is low in disc space.  Free some more space and try again.");
97                         }
98                 } catch (...) {
99
100                 }
101
102                 set_error (e.what(), m);
103                 set_progress (1);
104                 set_state (FINISHED_ERROR);
105
106         } catch (OpenFileError& e) {
107
108                 set_error (
109                         String::compose (_("Could not open %1"), e.file().string()),
110                         String::compose (
111                                 _("DCP-o-matic could not open the file %1.  Perhaps it does not exist or is in an unexpected format."),
112                                 boost::filesystem::absolute (e.file()).string()
113                                 )
114                         );
115
116                 set_progress (1);
117                 set_state (FINISHED_ERROR);
118
119         } catch (boost::filesystem::filesystem_error& e) {
120
121                 if (e.code() == boost::system::errc::no_such_file_or_directory) {
122                         set_error (
123                                 String::compose (_("Could not open %1"), e.path1().string ()),
124                                 String::compose (
125                                         _("DCP-o-matic could not open the file %1.  Perhaps it does not exist or is in an unexpected format."),
126                                         boost::filesystem::absolute (e.path1()).string()
127                                         )
128                                 );
129                 } else {
130                         set_error (
131                                 e.what (),
132                                 string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
133                                 );
134                 }
135
136                 set_progress (1);
137                 set_state (FINISHED_ERROR);
138
139         } catch (boost::thread_interrupted &) {
140
141                 set_state (FINISHED_CANCELLED);
142
143         } catch (std::bad_alloc& e) {
144
145                 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."));
146                 set_progress (1);
147                 set_state (FINISHED_ERROR);
148
149         } catch (std::exception& e) {
150
151                 set_error (
152                         e.what (),
153                         string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
154                         );
155
156                 set_progress (1);
157                 set_state (FINISHED_ERROR);
158
159         } catch (...) {
160
161                 set_error (
162                         _("Unknown error"),
163                         string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
164                         );
165
166                 set_progress (1);
167                 set_state (FINISHED_ERROR);
168         }
169 }
170
171 /** @return true if this job is new (ie has not started running) */
172 bool
173 Job::is_new () const
174 {
175         boost::mutex::scoped_lock lm (_state_mutex);
176         return _state == NEW;
177 }
178
179 /** @return true if the job is running */
180 bool
181 Job::running () const
182 {
183         boost::mutex::scoped_lock lm (_state_mutex);
184         return _state == RUNNING;
185 }
186
187 /** @return true if the job has finished (either successfully or unsuccessfully) */
188 bool
189 Job::finished () const
190 {
191         boost::mutex::scoped_lock lm (_state_mutex);
192         return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
193 }
194
195 /** @return true if the job has finished successfully */
196 bool
197 Job::finished_ok () const
198 {
199         boost::mutex::scoped_lock lm (_state_mutex);
200         return _state == FINISHED_OK;
201 }
202
203 /** @return true if the job has finished unsuccessfully */
204 bool
205 Job::finished_in_error () const
206 {
207         boost::mutex::scoped_lock lm (_state_mutex);
208         return _state == FINISHED_ERROR;
209 }
210
211 bool
212 Job::finished_cancelled () const
213 {
214         boost::mutex::scoped_lock lm (_state_mutex);
215         return _state == FINISHED_CANCELLED;
216 }
217
218 bool
219 Job::paused () const
220 {
221         boost::mutex::scoped_lock lm (_state_mutex);
222         return _state == PAUSED;
223 }
224
225 /** Set the state of this job.
226  *  @param s New state.
227  */
228 void
229 Job::set_state (State s)
230 {
231         bool finished = false;
232
233         {
234                 boost::mutex::scoped_lock lm (_state_mutex);
235                 _state = s;
236
237                 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
238                         _ran_for = elapsed_time ();
239                         finished = true;
240                         _sub_name.clear ();
241                 }
242         }
243
244         if (finished) {
245                 emit (boost::bind (boost::ref (Finished)));
246         }
247 }
248
249 /** @return DCPTime (in seconds) that this sub-job has been running */
250 int
251 Job::elapsed_time () const
252 {
253         if (_start_time == 0) {
254                 return 0;
255         }
256
257         return time (0) - _start_time;
258 }
259
260 /** Set the progress of the current part of the job.
261  *  @param p Progress (from 0 to 1)
262  */
263 void
264 Job::set_progress (float p, bool force)
265 {
266         if (!force && fabs (p - progress().get_value_or(0)) < 0.01) {
267                 /* Calm excessive progress reporting */
268                 return;
269         }
270
271         set_progress_common (p);
272 }
273
274 void
275 Job::set_progress_common (optional<float> p)
276 {
277         boost::mutex::scoped_lock lm (_progress_mutex);
278         _progress = p;
279         boost::this_thread::interruption_point ();
280
281         boost::mutex::scoped_lock lm2 (_state_mutex);
282         while (_state == PAUSED) {
283                 _pause_changed.wait (lm2);
284         }
285
286         lm.unlock ();
287         lm2.unlock ();
288
289         emit (boost::bind (boost::ref (Progress)));
290 }
291
292 /** @return fractional progress of the current sub-job, if known */
293 optional<float>
294 Job::progress () const
295 {
296         boost::mutex::scoped_lock lm (_progress_mutex);
297         return _progress;
298 }
299
300 void
301 Job::sub (string n)
302 {
303         {
304                 boost::mutex::scoped_lock lm (_progress_mutex);
305                 LOG_GENERAL ("Sub-job %1 starting", n);
306                 _sub_name = n;
307         }
308
309         set_progress (0, true);
310 }
311
312 string
313 Job::error_details () const
314 {
315         boost::mutex::scoped_lock lm (_state_mutex);
316         return _error_details;
317 }
318
319 /** @return A summary of any error that the job has generated */
320 string
321 Job::error_summary () const
322 {
323         boost::mutex::scoped_lock lm (_state_mutex);
324         return _error_summary;
325 }
326
327 /** Set the current error string.
328  *  @param e New error string.
329  */
330 void
331 Job::set_error (string s, string d)
332 {
333         if (_film) {
334                 LOG_ERROR_NC (s);
335                 LOG_ERROR_NC (d);
336                 _film->log()->log (String::compose ("Error in job: %1 (%2)", s, d), LogEntry::TYPE_ERROR);
337         }
338
339         boost::mutex::scoped_lock lm (_state_mutex);
340         _error_summary = s;
341         _error_details = d;
342 }
343
344 /** Say that this job's progress will be unknown until further notice */
345 void
346 Job::set_progress_unknown ()
347 {
348         set_progress_common (optional<float> ());
349 }
350
351 /** @return Human-readable status of this job */
352 string
353 Job::status () const
354 {
355         optional<float> p = progress ();
356         int const t = elapsed_time ();
357         int const r = remaining_time ();
358
359         SafeStringStream s;
360         if (!finished () && p) {
361                 int pc = lrintf (p.get() * 100);
362                 if (pc == 100) {
363                         /* 100% makes it sound like we've finished when we haven't */
364                         pc = 99;
365                 }
366
367                 s << pc << N_("%");
368
369                 if (t > 10 && r > 0) {
370                         /// TRANSLATORS: remaining here follows an amount of time that is remaining
371                         /// on an operation.
372                         s << "; " << seconds_to_approximate_hms (r) << " " << _("remaining");
373                 }
374         } else if (finished_ok ()) {
375                 s << String::compose (_("OK (ran for %1)"), seconds_to_hms (_ran_for));
376         } else if (finished_in_error ()) {
377                 s << String::compose (_("Error: %1"), error_summary ());
378         } else if (finished_cancelled ()) {
379                 s << _("Cancelled");
380         }
381
382         return s.str ();
383 }
384
385 string
386 Job::json_status () const
387 {
388         boost::mutex::scoped_lock lm (_state_mutex);
389
390         switch (_state) {
391         case NEW:
392                 return N_("new");
393         case RUNNING:
394                 return N_("running");
395         case PAUSED:
396                 return N_("paused");
397         case FINISHED_OK:
398                 return N_("finished_ok");
399         case FINISHED_ERROR:
400                 return N_("finished_error");
401         case FINISHED_CANCELLED:
402                 return N_("finished_cancelled");
403         }
404
405         return "";
406 }
407
408 /** @return An estimate of the remaining time for this sub-job, in seconds */
409 int
410 Job::remaining_time () const
411 {
412         if (progress().get_value_or(0) == 0) {
413                 return elapsed_time ();
414         }
415
416         return elapsed_time() / progress().get() - elapsed_time();
417 }
418
419 void
420 Job::cancel ()
421 {
422         if (!_thread) {
423                 return;
424         }
425
426         if (paused ()) {
427                 resume ();
428         }
429
430         _thread->interrupt ();
431         DCPOMATIC_ASSERT (_thread->joinable ());
432         _thread->join ();
433         delete _thread;
434         _thread = 0;
435 }
436
437 void
438 Job::pause ()
439 {
440         if (running ()) {
441                 set_state (PAUSED);
442                 _pause_changed.notify_all ();
443         }
444 }
445
446 void
447 Job::resume ()
448 {
449         if (paused ()) {
450                 set_state (RUNNING);
451                 _pause_changed.notify_all ();
452         }
453 }
454
455 void
456 Job::when_finished (boost::signals2::connection& connection, function<void()> finished)
457 {
458         boost::mutex::scoped_lock lm (_state_mutex);
459         if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
460                 finished ();
461         } else {
462                 connection = Finished.connect (finished);
463         }
464 }