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