Don't crash with bad content (#135).
[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         boost::mutex::scoped_lock lm (_state_mutex);
183         _state = s;
184
185         if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
186                 _ran_for = elapsed_time ();
187                 if (ui_signaller) {
188                         ui_signaller->emit (boost::bind (boost::ref (Finished)));
189                 }
190         }
191 }
192
193 /** @return Time (in seconds) that this job has been running */
194 int
195 Job::elapsed_time () const
196 {
197         if (_start_time == 0) {
198                 return 0;
199         }
200         
201         return time (0) - _start_time;
202 }
203
204 /** Set the progress of the current part of the job.
205  *  @param p Progress (from 0 to 1)
206  */
207 void
208 Job::set_progress (float p)
209 {
210         boost::mutex::scoped_lock lm (_progress_mutex);
211         _progress_unknown = false;
212         _stack.back().normalised = p;
213         boost::this_thread::interruption_point ();
214
215         if (paused ()) {
216                 dcpomatic_sleep (1);
217         }
218 }
219
220 /** @return fractional overall progress, or -1 if not known */
221 float
222 Job::overall_progress () const
223 {
224         boost::mutex::scoped_lock lm (_progress_mutex);
225         if (_progress_unknown) {
226                 return -1;
227         }
228
229         float overall = 0;
230         float factor = 1;
231         for (list<Level>::const_iterator i = _stack.begin(); i != _stack.end(); ++i) {
232                 factor *= i->allocation;
233                 overall += i->normalised * factor;
234         }
235
236         if (overall > 1) {
237                 overall = 1;
238         }
239         
240         return overall;
241 }
242
243 /** Ascend up one level in terms of progress reporting; see descend() */
244 void
245 Job::ascend ()
246 {
247         boost::mutex::scoped_lock lm (_progress_mutex);
248         
249         assert (!_stack.empty ());
250         float const a = _stack.back().allocation;
251         _stack.pop_back ();
252         _stack.back().normalised += a;
253 }
254
255 /** Descend down one level in terms of progress reporting; e.g. if
256  *  there is a task which is split up into N subtasks, each of which
257  *  report their progress from 0 to 100%, call descend() before executing
258  *  each subtask, and ascend() afterwards to ensure that overall progress
259  *  is reported correctly.
260  *
261  *  @param a Fraction (from 0 to 1) of the current task to allocate to the subtask.
262  */
263 void
264 Job::descend (float a)
265 {
266         boost::mutex::scoped_lock lm (_progress_mutex);
267         _stack.push_back (Level (a));
268 }
269
270 string
271 Job::error_details () const
272 {
273         boost::mutex::scoped_lock lm (_state_mutex);
274         return _error_details;
275 }
276
277 /** @return A summary of any error that the job has generated */
278 string
279 Job::error_summary () const
280 {
281         boost::mutex::scoped_lock lm (_state_mutex);
282         return _error_summary;
283 }
284
285 /** Set the current error string.
286  *  @param e New error string.
287  */
288 void
289 Job::set_error (string s, string d)
290 {
291         boost::mutex::scoped_lock lm (_state_mutex);
292         _error_summary = s;
293         _error_details = d;
294 }
295
296 /** Say that this job's progress will be unknown until further notice */
297 void
298 Job::set_progress_unknown ()
299 {
300         boost::mutex::scoped_lock lm (_progress_mutex);
301         _progress_unknown = true;
302 }
303
304 /** @return Human-readable status of this job */
305 string
306 Job::status () const
307 {
308         float const p = overall_progress ();
309         int const t = elapsed_time ();
310         int const r = remaining_time ();
311
312         int pc = rint (p * 100);
313         if (pc == 100) {
314                 /* 100% makes it sound like we've finished when we haven't */
315                 pc = 99;
316         }
317
318         stringstream s;
319         if (!finished ()) {
320                 s << pc << N_("%");
321                 if (p >= 0 && t > 10 && r > 0) {
322                         /// TRANSLATORS: remaining here follows an amount of time that is remaining
323                         /// on an operation.
324                         s << "; " << seconds_to_approximate_hms (r) << " " << _("remaining");
325                 }
326         } else if (finished_ok ()) {
327                 s << String::compose (_("OK (ran for %1)"), seconds_to_hms (_ran_for));
328         } else if (finished_in_error ()) {
329                 s << String::compose (_("Error (%1)"), error_summary());
330         } else if (finished_cancelled ()) {
331                 s << _("Cancelled");
332         }
333
334         return s.str ();
335 }
336
337 /** @return An estimate of the remaining time for this job, in seconds */
338 int
339 Job::remaining_time () const
340 {
341         return elapsed_time() / overall_progress() - elapsed_time();
342 }
343
344 void
345 Job::cancel ()
346 {
347         if (!_thread) {
348                 return;
349         }
350
351         _thread->interrupt ();
352         _thread->join ();
353 }
354
355 void
356 Job::pause ()
357 {
358         if (running ()) {
359                 set_state (PAUSED);
360         }
361 }
362
363 void
364 Job::resume ()
365 {
366         if (paused ()) {
367                 set_state (RUNNING);
368         }
369 }