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