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