Move things round a bit.
[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 #include <execinfo.h>
29 #include <cxxabi.h>
30 #include <signal.h>
31 #include <sys/types.h> 
32 #include <sys/socket.h>
33 #include <boost/algorithm/string.hpp>
34 #include <openjpeg.h>
35 #include <magick/MagickCore.h>
36 #include <magick/version.h>
37 #include <libssh/libssh.h>
38 extern "C" {
39 #include <libavcodec/avcodec.h>
40 #include <libavformat/avformat.h>
41 #include <libswscale/swscale.h>
42 #include <libswresample/swresample.h>
43 #include <libavfilter/avfiltergraph.h>
44 #include <libavfilter/avcodec.h>
45 #include <libavfilter/buffersink.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 /** @param l Mangled C++ identifier.
128  *  @return Demangled version.
129  */
130 static string
131 demangle (string l)
132 {
133         string::size_type const b = l.find_first_of ("(");
134         if (b == string::npos) {
135                 return l;
136         }
137
138         string::size_type const p = l.find_last_of ("+");
139         if (p == string::npos) {
140                 return l;
141         }
142
143         if ((p - b) <= 1) {
144                 return l;
145         }
146         
147         string const fn = l.substr (b + 1, p - b - 1);
148
149         int status;
150         try {
151                 
152                 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
153                 string d (realname);
154                 free (realname);
155                 return d;
156                 
157         } catch (std::exception) {
158                 
159         }
160         
161         return l;
162 }
163
164 /** Write a stacktrace to an ostream.
165  *  @param out Stream to write to.
166  *  @param levels Number of levels to go up the call stack.
167  */
168 void
169 stacktrace (ostream& out, int levels)
170 {
171         void *array[200];
172         size_t size;
173         char **strings;
174         size_t i;
175      
176         size = backtrace (array, 200);
177         strings = backtrace_symbols (array, size);
178      
179         if (strings) {
180                 for (i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
181                         out << "  " << demangle (strings[i]) << endl;
182                 }
183                 
184                 free (strings);
185         }
186 }
187
188 /** @param s Sample format.
189  *  @return String representation.
190  */
191 string
192 audio_sample_format_to_string (AVSampleFormat s)
193 {
194         /* Our sample format handling is not exactly complete */
195         
196         switch (s) {
197         case AV_SAMPLE_FMT_S16:
198                 return "S16";
199         default:
200                 break;
201         }
202
203         return "Unknown";
204 }
205
206 /** @param s String representation of a sample format, as returned from audio_sample_format_to_string().
207  *  @return Sample format.
208  */
209 AVSampleFormat
210 audio_sample_format_from_string (string s)
211 {
212         if (s == "S16") {
213                 return AV_SAMPLE_FMT_S16;
214         }
215
216         return AV_SAMPLE_FMT_NONE;
217 }
218
219 /** @return Version of OpenDCP that is on the path (and hence that we will use) */
220 static string
221 opendcp_version ()
222 {
223         FILE* f = popen ("opendcp_xml", "r");
224         if (f == 0) {
225                 throw EncodeError ("could not run opendcp_xml to check version");
226         }
227
228         string version = "unknown";
229         
230         while (!feof (f)) {
231                 char* buf = 0;
232                 size_t n = 0;
233                 ssize_t const r = getline (&buf, &n, f);
234                 if (r > 0) {
235                         string s (buf);
236                         vector<string> b;
237                         split (b, s, is_any_of (" "));
238                         if (b.size() >= 3 && b[0] == "OpenDCP" && b[1] == "version") {
239                                 version = b[2];
240                         }
241                         free (buf);
242                 }
243         }
244
245         pclose (f);
246
247         return version;
248 }
249
250 /** @return Version of vobcopy that is on the path (and hence that we will use) */
251 static string
252 vobcopy_version ()
253 {
254         FILE* f = popen ("vobcopy -V 2>&1", "r");
255         if (f == 0) {
256                 throw EncodeError ("could not run vobcopy to check version");
257         }
258
259         string version = "unknown";
260         
261         while (!feof (f)) {
262                 char* buf = 0;
263                 size_t n = 0;
264                 ssize_t const r = getline (&buf, &n, f);
265                 if (r > 0) {
266                         string s (buf);
267                         vector<string> b;
268                         split (b, s, is_any_of (" "));
269                         if (b.size() >= 2 && b[0] == "Vobcopy") {
270                                 version = b[1];
271                         }
272                         free (buf);
273                 }
274         }
275
276         pclose (f);
277
278         return version;
279 }
280
281 /** @param v Version as used by FFmpeg.
282  *  @return A string representation of v.
283  */
284 static string
285 ffmpeg_version_to_string (int v)
286 {
287         stringstream s;
288         s << ((v & 0xff0000) >> 16) << "." << ((v & 0xff00) >> 8) << "." << (v & 0xff);
289         return s.str ();
290 }
291
292 /** Return a user-readable string summarising the versions of our dependencies */
293 string
294 dependency_version_summary ()
295 {
296         stringstream s;
297         s << "libopenjpeg " << opj_version () << ", "
298           << "opendcp " << opendcp_version () << ", "
299           << "vobcopy " << vobcopy_version() << ", "
300           << "libswresample " << ffmpeg_version_to_string (swresample_version()) << ", "
301           << "libavcodec " << ffmpeg_version_to_string (avcodec_version()) << ", "
302           << "libavfilter " << ffmpeg_version_to_string (avfilter_version()) << ", "
303           << "libavformat " << ffmpeg_version_to_string (avformat_version()) << ", "
304           << "libavutil " << ffmpeg_version_to_string (avutil_version()) << ", "
305           << "libpostproc " << ffmpeg_version_to_string (postproc_version()) << ", "
306           << "libswscale " << ffmpeg_version_to_string (swscale_version()) << ", "
307           << MagickVersion << ", "
308           << "libssh " << ssh_version (0);
309
310         return s.str ();
311 }
312
313 /** Write some data to a socket.
314  *  @param fd Socket file descriptor.
315  *  @param data Data.
316  *  @param size Amount to write, in bytes.
317  */
318 void
319 socket_write (int fd, uint8_t const * data, int size)
320 {
321         uint8_t const * p = data;
322         while (size) {
323                 int const n = send (fd, p, size, MSG_NOSIGNAL);
324                 if (n < 0) {
325                         stringstream s;
326                         s << "could not write (" << strerror (errno) << ")";
327                         throw NetworkError (s.str ());
328                 }
329
330                 size -= n;
331                 p += n;
332         }
333 }
334
335 double
336 seconds (struct timeval t)
337 {
338         return t.tv_sec + (double (t.tv_usec) / 1e6);
339 }
340
341 /** @param fd File descriptor to read from */
342 SocketReader::SocketReader (int fd)
343         : _fd (fd)
344         , _buffer_data (0)
345 {
346
347 }
348
349 /** Mark some data as being `consumed', so that it will not be returned
350  *  as data again.
351  *  @param size Amount of data to consume, in bytes.
352  */
353 void
354 SocketReader::consume (int size)
355 {
356         assert (_buffer_data >= size);
357         
358         _buffer_data -= size;
359         if (_buffer_data > 0) {
360                 /* Shift still-valid data to the start of the buffer */
361                 memmove (_buffer, _buffer + size, _buffer_data);
362         }
363 }
364
365 /** Read a definite amount of data from our socket, and mark
366  *  it as consumed.
367  *  @param data Where to put the data.
368  *  @param size Number of bytes to read.
369  */
370 void
371 SocketReader::read_definite_and_consume (uint8_t* data, int size)
372 {
373         int const from_buffer = min (_buffer_data, size);
374         if (from_buffer > 0) {
375                 /* Get data from our buffer */
376                 memcpy (data, _buffer, from_buffer);
377                 consume (from_buffer);
378                 /* Update our output state */
379                 data += from_buffer;
380                 size -= from_buffer;
381         }
382
383         /* read() the rest */
384         while (size > 0) {
385                 int const n = ::read (_fd, data, size);
386                 if (n <= 0) {
387                         throw NetworkError ("could not read");
388                 }
389
390                 data += n;
391                 size -= n;
392         }
393 }
394
395 /** Read as much data as is available, up to some limit.
396  *  @param data Where to put the data.
397  *  @param size Maximum amount of data to read.
398  */
399 void
400 SocketReader::read_indefinite (uint8_t* data, int size)
401 {
402         assert (size < int (sizeof (_buffer)));
403
404         /* Amount of extra data we need to read () */
405         int to_read = size - _buffer_data;
406         while (to_read > 0) {
407                 /* read as much of it as we can (into our buffer) */
408                 int const n = ::read (_fd, _buffer + _buffer_data, to_read);
409                 if (n <= 0) {
410                         throw NetworkError ("could not read");
411                 }
412
413                 to_read -= n;
414                 _buffer_data += n;
415         }
416
417         assert (_buffer_data >= size);
418
419         /* copy data into the output buffer */
420         assert (size >= _buffer_data);
421         memcpy (data, _buffer, size);
422 }
423
424 void
425 sigchld_handler (int, siginfo_t* info, void *)
426 {
427         PlayerManager::instance()->child_exited (info->si_pid);
428 }
429
430 /** Call the required functions to set up DVD-o-matic's static arrays, etc. */
431 void
432 dvdomatic_setup ()
433 {
434         Format::setup_formats ();
435         DCPContentType::setup_dcp_content_types ();
436         Scaler::setup_scalers ();
437         Filter::setup_filters ();
438
439         struct sigaction sa;
440         sa.sa_flags = SA_SIGINFO;
441         sigemptyset (&sa.sa_mask);
442         sa.sa_sigaction = sigchld_handler;
443         sigaction (SIGCHLD, &sa, 0);
444 }
445
446 string
447 crop_string (Position start, Size size)
448 {
449         stringstream s;
450         s << "crop=" << size.width << ":" << size.height << ":" << start.x << ":" << start.y;
451         return s.str ();
452 }
453
454 vector<string>
455 split_at_spaces_considering_quotes (string s)
456 {
457         vector<string> out;
458         bool in_quotes = false;
459         string c;
460         for (string::size_type i = 0; i < s.length(); ++i) {
461                 if (s[i] == ' ' && !in_quotes) {
462                         out.push_back (c);
463                         c = "";
464                 } else if (s[i] == '"') {
465                         in_quotes = !in_quotes;
466                 } else {
467                         c += s[i];
468                 }
469         }
470
471         out.push_back (c);
472         return out;
473 }
474
475 #ifdef DEBUG_HASH
476 void
477 md5_data (string title, void const * data, int size)
478 {
479         MHASH ht = mhash_init (MHASH_MD5);
480         if (ht == MHASH_FAILED) {
481                 throw EncodeError ("could not create hash thread");
482         }
483
484         mhash (ht, data, size);
485         
486         uint8_t hash[16];
487         mhash_deinit (ht, hash);
488         
489         printf ("%s [%d]: ", title.c_str (), size);
490         for (int i = 0; i < int (mhash_get_block_size (MHASH_MD5)); ++i) {
491                 printf ("%.2x", hash[i]);
492         }
493         printf ("\n");
494 }
495 #endif
496