Try to fix deadlock.
[dcpomatic.git] / src / lib / job.cc
1 /*
2     Copyright (C) 2012 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 <boost/thread.hpp>
25 #include <boost/filesystem.hpp>
26 #include <libdcp/exceptions.h>
27 #include "job.h"
28 #include "util.h"
29 #include "cross.h"
30 #include "ui_signaller.h"
31 #include "exceptions.h"
32
33 #include "i18n.h"
34
35 using std::string;
36 using std::list;
37 using std::stringstream;
38 using boost::shared_ptr;
39
40 Job::Job (shared_ptr<const Film> f)
41         : _film (f)
42         , _thread (0)
43         , _state (NEW)
44         , _start_time (0)
45         , _progress_unknown (false)
46         , _ran_for (0)
47 {
48         descend (1);
49 }
50
51 /** Start the job in a separate thread, returning immediately */
52 void
53 Job::start ()
54 {
55         set_state (RUNNING);
56         _start_time = time (0);
57         _thread = new boost::thread (boost::bind (&Job::run_wrapper, this));
58 }
59
60 /** A wrapper for the ::run() method to catch exceptions */
61 void
62 Job::run_wrapper ()
63 {
64         try {
65
66                 run ();
67
68         } catch (libdcp::FileError& e) {
69                 
70                 set_progress (1);
71                 set_state (FINISHED_ERROR);
72                 
73                 string m = String::compose (_("An error occurred whilst handling the file %1."), boost::filesystem::path (e.filename()).leaf());
74
75                 try {
76                         boost::filesystem::space_info const s = boost::filesystem::space (e.filename());
77                         if (s.available < pow (1024, 3)) {
78                                 m += N_("\n\n");
79                                 m += _("The drive that the film is stored on is low in disc space.  Free some more space and try again.");
80                         }
81                 } catch (...) {
82
83                 }
84
85                 set_error (e.what(), m);
86
87         } catch (OpenFileError& e) {
88
89                 set_progress (1);
90                 set_state (FINISHED_ERROR);
91
92                 set_error (
93                         String::compose (_("Could not open %1"), e.file().string()),
94                         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())
95                         );
96
97         } catch (boost::thread_interrupted &) {
98
99                 set_state (FINISHED_CANCELLED);
100                 
101         } catch (std::exception& e) {
102
103                 set_progress (1);
104                 set_state (FINISHED_ERROR);
105                 set_error (
106                         e.what (),
107                         _("It is not known what caused this error.  The best idea is to report the problem to the DCP-o-matic mailing list (dcpomatic@carlh.net)")
108                         );
109
110         } catch (...) {
111
112                 set_progress (1);
113                 set_state (FINISHED_ERROR);
114                 set_error (
115                         _("Unknown error"),
116                         _("It is not known what caused this error.  The best idea is to report the problem to the DCP-o-matic mailing list (dcpomatic@carlh.net)")
117                         );
118
119         }
120 }
121
122 /** @return true if this job is new (ie has not started running) */
123 bool
124 Job::is_new () const
125 {
126         boost::mutex::scoped_lock lm (_state_mutex);
127         return _state == NEW;
128 }
129
130 /** @return true if the job is running */
131 bool
132 Job::running () const
133 {
134         boost::mutex::scoped_lock lm (_state_mutex);
135         return _state == RUNNING;
136 }
137
138 /** @return true if the job has finished (either successfully or unsuccessfully) */
139 bool
140 Job::finished () const
141 {
142         boost::mutex::scoped_lock lm (_state_mutex);
143         return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
144 }
145
146 /** @return true if the job has finished successfully */
147 bool
148 Job::finished_ok () const
149 {
150         boost::mutex::scoped_lock lm (_state_mutex);
151         return _state == FINISHED_OK;
152 }
153
154 /** @return true if the job has finished unsuccessfully */
155 bool
156 Job::finished_in_error () const
157 {
158         boost::mutex::scoped_lock lm (_state_mutex);
159         return _state == FINISHED_ERROR;
160 }
161
162 bool
163 Job::finished_cancelled () const
164 {
165         boost::mutex::scoped_lock lm (_state_mutex);
166         return _state == FINISHED_CANCELLED;
167 }
168
169 bool
170 Job::paused () const
171 {
172         boost::mutex::scoped_lock lm (_state_mutex);
173         return _state == PAUSED;
174 }
175         
176 /** Set the state of this job.
177  *  @param s New state.
178  */
179 void
180 Job::set_state (State s)
181 {
182         bool finished = false;
183         
184         {
185                 boost::mutex::scoped_lock lm (_state_mutex);
186                 _state = s;
187
188                 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
189                         _ran_for = elapsed_time ();
190                         finished = true;
191                 }
192         }
193
194         if (finished && ui_signaller) {
195                 ui_signaller->emit (boost::bind (boost::ref (Finished)));
196         }
197 }
198
199 /** @return Time (in seconds) that this job has been running */
200 int
201 Job::elapsed_time () const
202 {
203         if (_start_time == 0) {
204                 return 0;
205         }
206         
207         return time (0) - _start_time;
208 }
209
210 /** Set the progress of the current part of the job.
211  *  @param p Progress (from 0 to 1)
212  */
213 void
214 Job::set_progress (float p)
215 {
216         boost::mutex::scoped_lock lm (_progress_mutex);
217         _progress_unknown = false;
218         _stack.back().normalised = p;
219         boost::this_thread::interruption_point ();
220
221         if (paused ()) {
222                 dcpomatic_sleep (1);
223         }
224
225         if (ui_signaller) {
226                 ui_signaller->emit (boost::bind (boost::ref (Progress)));
227         }
228 }
229
230 /** @return fractional overall progress, or -1 if not known */
231 float
232 Job::overall_progress () const
233 {
234         boost::mutex::scoped_lock lm (_progress_mutex);
235         if (_progress_unknown) {
236                 return -1;
237         }
238
239         float overall = 0;
240         float factor = 1;
241         for (list<Level>::const_iterator i = _stack.begin(); i != _stack.end(); ++i) {
242                 factor *= i->allocation;
243                 overall += i->normalised * factor;
244         }
245
246         if (overall > 1) {
247                 overall = 1;
248         }
249         
250         return overall;
251 }
252
253 /** Ascend up one level in terms of progress reporting; see descend() */
254 void
255 Job::ascend ()
256 {
257         boost::mutex::scoped_lock lm (_progress_mutex);
258         
259         assert (!_stack.empty ());
260         float const a = _stack.back().allocation;
261         _stack.pop_back ();
262         _stack.back().normalised += a;
263 }
264
265 /** Descend down one level in terms of progress reporting; e.g. if
266  *  there is a task which is split up into N subtasks, each of which
267  *  report their progress from 0 to 100%, call descend() before executing
268  *  each subtask, and ascend() afterwards to ensure that overall progress
269  *  is reported correctly.
270  *
271  *  @param a Fraction (from 0 to 1) of the current task to allocate to the subtask.
272  */
273 void
274 Job::descend (float a)
275 {
276         boost::mutex::scoped_lock lm (_progress_mutex);
277         _stack.push_back (Level (a));
278 }
279
280 string
281 Job::error_details () const
282 {
283         boost::mutex::scoped_lock lm (_state_mutex);
284         return _error_details;
285 }
286
287 /** @return A summary of any error that the job has generated */
288 string
289 Job::error_summary () const
290 {
291         boost::mutex::scoped_lock lm (_state_mutex);
292         return _error_summary;
293 }
294
295 /** Set the current error string.
296  *  @param e New error string.
297  */
298 void
299 Job::set_error (string s, string d)
300 {
301         boost::mutex::scoped_lock lm (_state_mutex);
302         _error_summary = s;
303         _error_details = d;
304 }
305
306 /** Say that this job's progress will be unknown until further notice */
307 void
308 Job::set_progress_unknown ()
309 {
310         boost::mutex::scoped_lock lm (_progress_mutex);
311         _progress_unknown = true;
312 }
313
314 /** @return Human-readable status of this job */
315 string
316 Job::status () const
317 {
318         float const p = overall_progress ();
319         int const t = elapsed_time ();
320         int const r = remaining_time ();
321
322         int pc = rint (p * 100);
323         if (pc == 100) {
324                 /* 100% makes it sound like we've finished when we haven't */
325                 pc = 99;
326         }
327
328         stringstream s;
329         if (!finished ()) {
330                 s << pc << N_("%");
331                 if (p >= 0 && t > 10 && r > 0) {
332                         /// TRANSLATORS: remaining here follows an amount of time that is remaining
333                         /// on an operation.
334                         s << "; " << seconds_to_approximate_hms (r) << " " << _("remaining");
335                 }
336         } else if (finished_ok ()) {
337                 s << String::compose (_("OK (ran for %1)"), seconds_to_hms (_ran_for));
338         } else if (finished_in_error ()) {
339                 s << String::compose (_("Error (%1)"), error_summary());
340         } else if (finished_cancelled ()) {
341                 s << _("Cancelled");
342         }
343
344         return s.str ();
345 }
346
347 /** @return An estimate of the remaining time for this job, in seconds */
348 int
349 Job::remaining_time () const
350 {
351         return elapsed_time() / overall_progress() - elapsed_time();
352 }
353
354 void
355 Job::cancel ()
356 {
357         if (!_thread) {
358                 return;
359         }
360
361         _thread->interrupt ();
362         _thread->join ();
363 }
364
365 void
366 Job::pause ()
367 {
368         if (running ()) {
369                 set_state (PAUSED);
370         }
371 }
372
373 void
374 Job::resume ()
375 {
376         if (paused ()) {
377                 set_state (RUNNING);
378         }
379 }