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