Merge.
[dcpomatic.git] / src / lib / util.cc
1 /*
2     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
3     Copyright (C) 2000-2007 Paul Davis
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 /** @file src/lib/util.cc
22  *  @brief Some utility functions and classes.
23  */
24
25 #include <sstream>
26 #include <iomanip>
27 #include <iostream>
28 #ifdef DVDOMATIC_POSIX
29 #include <execinfo.h>
30 #include <cxxabi.h>
31 #include <sys/types.h> 
32 #include <sys/socket.h>
33 #endif
34 #include <libssh/libssh.h>
35 #include <signal.h>
36 #include <boost/algorithm/string.hpp>
37 #include <openjpeg.h>
38 #include <magick/MagickCore.h>
39 #include <magick/version.h>
40 #include <libdcp/version.h>
41 extern "C" {
42 #include <libavcodec/avcodec.h>
43 #include <libavformat/avformat.h>
44 #include <libswscale/swscale.h>
45 #include <libavfilter/avfiltergraph.h>
46 #include <libpostproc/postprocess.h>
47 #include <libavutil/pixfmt.h>
48 }
49 #include "util.h"
50 #include "exceptions.h"
51 #include "scaler.h"
52 #include "format.h"
53 #include "dcp_content_type.h"
54 #include "filter.h"
55 #include "screen.h"
56 #include "film_state.h"
57 #include "player_manager.h"
58
59 #ifdef DEBUG_HASH
60 #include <mhash.h>
61 #endif
62
63 using namespace std;
64 using namespace boost;
65
66 /** Convert some number of seconds to a string representation
67  *  in hours, minutes and seconds.
68  *
69  *  @param s Seconds.
70  *  @return String of the form H:M:S (where H is hours, M
71  *  is minutes and S is seconds).
72  */
73 string
74 seconds_to_hms (int s)
75 {
76         int m = s / 60;
77         s -= (m * 60);
78         int h = m / 60;
79         m -= (h * 60);
80
81         stringstream hms;
82         hms << h << ":";
83         hms.width (2);
84         hms << setfill ('0') << m << ":";
85         hms.width (2);
86         hms << setfill ('0') << s;
87
88         return hms.str ();
89 }
90
91 /** @param s Number of seconds.
92  *  @return String containing an approximate description of s (e.g. "about 2 hours")
93  */
94 string
95 seconds_to_approximate_hms (int s)
96 {
97         int m = s / 60;
98         s -= (m * 60);
99         int h = m / 60;
100         m -= (h * 60);
101
102         stringstream ap;
103         
104         if (h > 0) {
105                 if (m > 30) {
106                         ap << (h + 1) << " hours";
107                 } else {
108                         if (h == 1) {
109                                 ap << "1 hour";
110                         } else {
111                                 ap << h << " hours";
112                         }
113                 }
114         } else if (m > 0) {
115                 if (m == 1) {
116                         ap << "1 minute";
117                 } else {
118                         ap << m << " minutes";
119                 }
120         } else {
121                 ap << s << " seconds";
122         }
123
124         return ap.str ();
125 }
126
127 #ifdef DVDOMATIC_POSIX
128 /** @param l Mangled C++ identifier.
129  *  @return Demangled version.
130  */
131 static string
132 demangle (string l)
133 {
134         string::size_type const b = l.find_first_of ("(");
135         if (b == string::npos) {
136                 return l;
137         }
138
139         string::size_type const p = l.find_last_of ("+");
140         if (p == string::npos) {
141                 return l;
142         }
143
144         if ((p - b) <= 1) {
145                 return l;
146         }
147         
148         string const fn = l.substr (b + 1, p - b - 1);
149
150         int status;
151         try {
152                 
153                 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
154                 string d (realname);
155                 free (realname);
156                 return d;
157                 
158         } catch (std::exception) {
159                 
160         }
161         
162         return l;
163 }
164
165 /** Write a stacktrace to an ostream.
166  *  @param out Stream to write to.
167  *  @param levels Number of levels to go up the call stack.
168  */
169 void
170 stacktrace (ostream& out, int levels)
171 {
172         void *array[200];
173         size_t size;
174         char **strings;
175         size_t i;
176      
177         size = backtrace (array, 200);
178         strings = backtrace_symbols (array, size);
179      
180         if (strings) {
181                 for (i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
182                         out << "  " << demangle (strings[i]) << endl;
183                 }
184                 
185                 free (strings);
186         }
187 }
188 #endif
189
190 /** @param s Sample format.
191  *  @return String representation.
192  */
193 string
194 audio_sample_format_to_string (AVSampleFormat s)
195 {
196         /* Our sample format handling is not exactly complete */
197         
198         switch (s) {
199         case AV_SAMPLE_FMT_S16:
200                 return "S16";
201         default:
202                 break;
203         }
204
205         return "Unknown";
206 }
207
208 /** @param s String representation of a sample format, as returned from audio_sample_format_to_string().
209  *  @return Sample format.
210  */
211 AVSampleFormat
212 audio_sample_format_from_string (string s)
213 {
214         if (s == "S16") {
215                 return AV_SAMPLE_FMT_S16;
216         }
217
218         return AV_SAMPLE_FMT_NONE;
219 }
220
221 /** @return Version of vobcopy that is on the path (and hence that we will use) */
222 static string
223 vobcopy_version ()
224 {
225         FILE* f = popen ("vobcopy -V 2>&1", "r");
226         if (f == 0) {
227                 throw EncodeError ("could not run vobcopy to check version");
228         }
229
230         string version = "unknown";
231         
232         while (!feof (f)) {
233                 char buf[256];
234                 if (fgets (buf, sizeof (buf), f)) {
235                         string s (buf);
236                         vector<string> b;
237                         split (b, s, is_any_of (" "));
238                         if (b.size() >= 2 && b[0] == "Vobcopy") {
239                                 version = b[1];
240                         }
241                 }
242         }
243
244         pclose (f);
245
246         return version;
247 }
248
249 /** @param v Version as used by FFmpeg.
250  *  @return A string representation of v.
251  */
252 static string
253 ffmpeg_version_to_string (int v)
254 {
255         stringstream s;
256         s << ((v & 0xff0000) >> 16) << "." << ((v & 0xff00) >> 8) << "." << (v & 0xff);
257         return s.str ();
258 }
259
260 /** Return a user-readable string summarising the versions of our dependencies */
261 string
262 dependency_version_summary ()
263 {
264         stringstream s;
265         s << "libopenjpeg " << opj_version () << ", "
266           << "vobcopy " << vobcopy_version() << ", "
267           << "libavcodec " << ffmpeg_version_to_string (avcodec_version()) << ", "
268           << "libavfilter " << ffmpeg_version_to_string (avfilter_version()) << ", "
269           << "libavformat " << ffmpeg_version_to_string (avformat_version()) << ", "
270           << "libavutil " << ffmpeg_version_to_string (avutil_version()) << ", "
271           << "libpostproc " << ffmpeg_version_to_string (postproc_version()) << ", "
272           << "libswscale " << ffmpeg_version_to_string (swscale_version()) << ", "
273           << MagickVersion << ", "
274           << "libssh " << ssh_version (0) << ", "
275           << "libdcp " << libdcp::version << " git " << libdcp::git_commit;
276
277         return s.str ();
278 }
279
280 #ifdef DVDOMATIC_POSIX
281 /** Write some data to a socket.
282  *  @param fd Socket file descriptor.
283  *  @param data Data.
284  *  @param size Amount to write, in bytes.
285  */
286 void
287 socket_write (int fd, uint8_t const * data, int size)
288 {
289         uint8_t const * p = data;
290         while (size) {
291                 int const n = send (fd, p, size, MSG_NOSIGNAL);
292                 if (n < 0) {
293                         stringstream s;
294                         s << "could not write (" << strerror (errno) << ")";
295                         throw NetworkError (s.str ());
296                 }
297
298                 size -= n;
299                 p += n;
300         }
301 }
302 #endif
303
304 double
305 seconds (struct timeval t)
306 {
307         return t.tv_sec + (double (t.tv_usec) / 1e6);
308 }
309
310 #ifdef DVDOMATIC_POSIX
311 /** @param fd File descriptor to read from */
312 SocketReader::SocketReader (int fd)
313         : _fd (fd)
314         , _buffer_data (0)
315 {
316
317 }
318
319 /** Mark some data as being `consumed', so that it will not be returned
320  *  as data again.
321  *  @param size Amount of data to consume, in bytes.
322  */
323 void
324 SocketReader::consume (int size)
325 {
326         assert (_buffer_data >= size);
327         
328         _buffer_data -= size;
329         if (_buffer_data > 0) {
330                 /* Shift still-valid data to the start of the buffer */
331                 memmove (_buffer, _buffer + size, _buffer_data);
332         }
333 }
334
335 /** Read a definite amount of data from our socket, and mark
336  *  it as consumed.
337  *  @param data Where to put the data.
338  *  @param size Number of bytes to read.
339  */
340 void
341 SocketReader::read_definite_and_consume (uint8_t* data, int size)
342 {
343         int const from_buffer = min (_buffer_data, size);
344         if (from_buffer > 0) {
345                 /* Get data from our buffer */
346                 memcpy (data, _buffer, from_buffer);
347                 consume (from_buffer);
348                 /* Update our output state */
349                 data += from_buffer;
350                 size -= from_buffer;
351         }
352
353         /* read() the rest */
354         while (size > 0) {
355                 int const n = ::read (_fd, data, size);
356                 if (n <= 0) {
357                         throw NetworkError ("could not read");
358                 }
359
360                 data += n;
361                 size -= n;
362         }
363 }
364
365 /** Read as much data as is available, up to some limit.
366  *  @param data Where to put the data.
367  *  @param size Maximum amount of data to read.
368  */
369 void
370 SocketReader::read_indefinite (uint8_t* data, int size)
371 {
372         assert (size < int (sizeof (_buffer)));
373
374         /* Amount of extra data we need to read () */
375         int to_read = size - _buffer_data;
376         while (to_read > 0) {
377                 /* read as much of it as we can (into our buffer) */
378                 int const n = ::read (_fd, _buffer + _buffer_data, to_read);
379                 if (n <= 0) {
380                         throw NetworkError ("could not read");
381                 }
382
383                 to_read -= n;
384                 _buffer_data += n;
385         }
386
387         assert (_buffer_data >= size);
388
389         /* copy data into the output buffer */
390         assert (size >= _buffer_data);
391         memcpy (data, _buffer, size);
392 }
393 #endif
394
395 #ifdef DVDOMATIC_POSIX
396 void
397 sigchld_handler (int, siginfo_t* info, void *)
398 {
399         PlayerManager::instance()->child_exited (info->si_pid);
400 }
401 #endif
402
403 /** Call the required functions to set up DVD-o-matic's static arrays, etc. */
404 void
405 dvdomatic_setup ()
406 {
407         Format::setup_formats ();
408         DCPContentType::setup_dcp_content_types ();
409         Scaler::setup_scalers ();
410         Filter::setup_filters ();
411
412 #ifdef DVDOMATIC_POSIX  
413         struct sigaction sa;
414         sa.sa_flags = SA_SIGINFO;
415         sigemptyset (&sa.sa_mask);
416         sa.sa_sigaction = sigchld_handler;
417         sigaction (SIGCHLD, &sa, 0);
418 #endif  
419 }
420
421 string
422 crop_string (Position start, Size size)
423 {
424         stringstream s;
425         s << "crop=" << size.width << ":" << size.height << ":" << start.x << ":" << start.y;
426         return s.str ();
427 }
428
429 vector<string>
430 split_at_spaces_considering_quotes (string s)
431 {
432         vector<string> out;
433         bool in_quotes = false;
434         string c;
435         for (string::size_type i = 0; i < s.length(); ++i) {
436                 if (s[i] == ' ' && !in_quotes) {
437                         out.push_back (c);
438                         c = "";
439                 } else if (s[i] == '"') {
440                         in_quotes = !in_quotes;
441                 } else {
442                         c += s[i];
443                 }
444         }
445
446         out.push_back (c);
447         return out;
448 }
449
450 #ifdef DEBUG_HASH
451 void
452 md5_data (string title, void const * data, int size)
453 {
454         MHASH ht = mhash_init (MHASH_MD5);
455         if (ht == MHASH_FAILED) {
456                 throw EncodeError ("could not create hash thread");
457         }
458
459         mhash (ht, data, size);
460         
461         uint8_t hash[16];
462         mhash_deinit (ht, hash);
463         
464         printf ("%s [%d]: ", title.c_str (), size);
465         for (int i = 0; i < int (mhash_get_block_size (MHASH_MD5)); ++i) {
466                 printf ("%.2x", hash[i]);
467         }
468         printf ("\n");
469 }
470 #endif
471