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