1 /*
2  * Miscellaneous useful functions.
3  *
4  * ***** BEGIN LICENSE BLOCK *****
5  * Version: MPL 1.1
6  *
7  * The contents of this file are subject to the Mozilla Public License Version
8  * 1.1 (the "License"); you may not use this file except in compliance with
9  * the License. You may obtain a copy of the License at
10  * http://www.mozilla.org/MPL/
11  *
12  * Software distributed under the License is distributed on an "AS IS" basis,
13  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14  * for the specific language governing rights and limitations under the
15  * License.
16  *
17  * The Original Code is the MPEG TS, PS and ES tools.
18  *
19  * The Initial Developer of the Original Code is Amino Communications Ltd.
20  * Portions created by the Initial Developer are Copyright (C) 2008
21  * the Initial Developer. All Rights Reserved.
22  *
23  * Contributor(s):
24  *   Amino Communications Ltd, Swavesey, Cambridge UK
25  *
26  * ***** END LICENSE BLOCK *****
27  */
28 #ifndef _misc_fns
29 #define _misc_fns
30 
31 #include "misc_defns.h"
32 #include "es_defns.h"
33 #ifndef _WIN32
34 #include <stdint.h>
35 #endif
36 
37 #ifdef _WIN32
38 #include "compat.h"
39 #include <winsock2.h>
40 #endif // _WIN32
41 
42 #define CRC32_POLY 0x04c11db7L
43 
44 /*
45  * Compute CRC32 over a block of data, by table method.
46  *
47  * Returns a working value, suitable for re-input for further blocks
48  *
49  * Notes: Input value should be 0xffffffff for the first block,
50  *        else return value from previous call (not sure if that
51  *        needs complementing before being passed back in).
52  */
53 extern uint32_t crc32_block(uint32_t crc, byte *pData, int blk_len);
54 
55 /*
56  * Print out the bottom N bits from a byte on the given stream
57  */
58 extern void print_bits(FILE   *stream,
59                        int     num_bits,
60                        byte    value);
61 
62 /*
63  * Print out (the first `max`) bytes of a byte array.
64  *
65  * - `stream` is the stream to print on.
66  * - `name` is identifying text to start the report with.
67  * - `data` is the byte data to print. This may be NULL.
68  * - `length` is its length
69  * - `max` is the maximum number of bytes to print
70  *
71  * Prints out::
72  *
73  *    <name> (<length>): b1 b2 b3 b4 ...
74  *
75  * where no more than `max` bytes are to be printed (and "..." is printed
76  * if not all bytes were shown).
77  */
78 extern void print_data(FILE *stream,
79                        char *name,
80                        byte  data[],
81                        int   length,
82                        int   max);
83 /*
84  * Print out (the last `max`) bytes of a byte array.
85  *
86  * - `stream` is the stream to print on.
87  * - `name` is identifying text to start the report with.
88  * - `data` is the byte data to print. This may be NULL.
89  * - `length` is its length
90  * - `max` is the maximum number of bytes to print
91  *
92  * Prints out::
93  *
94  *    <name> (<length>): ... b1 b2 b3 b4
95  *
96  * where no more than `max` bytes are to be printed (and "..." is printed
97  * if not all bytes were shown).
98  */
99 extern void print_end_of_data(FILE *stream,
100                               char *name,
101                               byte  data[],
102                               int   length,
103                               int   max);
104 /*
105  * Calculate log2 of `x` - for some reason this is missing from <math.h>
106  */
107 extern double log2(double x);
108 
109 
110 // ============================================================
111 // Simple file I/O utilities
112 // ============================================================
113 /*
114  * Read a given number of bytes from a file.
115  *
116  * This is a jacket for `read`, allowing for the future possibility of
117  * buffered input, and simplifying error handling.
118  *
119  * - `input` is the file descriptor for the file
120  * - `num_bytes` is how many bytes to read
121  * - `data` is the buffer to read the bytes into
122  *
123  * Returns 0 if all goes well, EOF if end of file was read, or 1 if some
124  * other error occurred (in which case it will already have output a message
125  * on stderr about the problem).
126  */
127 extern int read_bytes(int    input,
128                       int    num_bytes,
129                       byte  *data);
130 /*
131  * Utility function to seek within a file
132  *
133  * - `filedes` is the file to seek within
134  * - `posn` is the position to which to seek
135  *
136  * This is a jacket for::
137  *
138  *    new_posn = lseek(filedes,posn,SEEK_SET);
139  *
140  * Returns 0 if all went well, 1 if the seek failed (either because
141  * it returned -1, or because the position reached was not the position
142  * requested). If an error occurs, then an explanatory message will
143  * already have been written to stderr.
144  */
145 extern int seek_file(int       filedes,
146                      offset_t  posn);
147 /*
148  * Utility function to report the current location within a file
149  *
150  * - `filedes` is the file to seek within
151  *
152  * This is a jacket for::
153  *
154  *    posn = lseek(filedes,0,SEEK_CUR);
155  *
156  * Returns the current position in the file if all went well, otherwise
157  * -1 (in which case an error message will already have been written
158  * on stderr)
159  */
160 extern offset_t tell_file(int    filedes);
161 /*
162  * Utility function to open a file (descriptor), and report any errors
163  *
164  * This is intended only for very simple usage, and is not mean to be
165  * a general purpose "open" replacement.
166  *
167  * - `filename` is the name of the file to open
168  * - `for_write` should be TRUE if the file is to be written to,
169  *   in which case it will be opened with flags O_WRONLY|O_CREAT|O_TRUNC,
170  *   or FALSE if the file is to be read, in which case it will be
171  *   opened with flag O_RDONLY. In both cases, on Windows the flag
172  *   O_BINARY will also be set.
173  *
174  * Returns the file descriptor for the file, or -1 if it failed to open
175  * the file.
176  */
177 extern int open_binary_file(char  *filename,
178                             int    for_write);
179 /*
180  * Utility function to close a file (descriptor), and report any errors
181  *
182  * Returns 0 if all went well, 1 if an error occurred.
183  */
184 extern int close_file(int  filedes);
185 
186 // ============================================================
187 // More complex file I/O utilities
188 // ============================================================
189 /*
190  * Open an input file appropriately for reading as ES.
191  *
192  * - `name` is the name of the file, or NULL if standard input
193  *   is to be read from (which is not allowed if `use_pes` is
194  *   TRUE).
195  *
196  * - If `use_pes` is true then the input file is PS or TS and should
197  *   be read via a PES reader.
198  *
199  * - If `quiet` is true then information about the file being read will
200  *   not be written out. Otherwise, its name and what is decided about
201  *   its content will be printed.
202  *
203  * - If `force_stream_type` is true, then the caller asserts that
204  *   the input shall be read according to `want_data`, and not whatever
205  *   might be deduced from looking at the file itself.
206  *
207  * - If `force_stream_type` is true, then `want_data` should be one of
208  *   VIDEO_H262, VIDEO_H264 or VIDEO_AVS. `is_data` will then be
209  *   returned with the same value.
210  *
211  * - If `force_stream_type` is false, then the function will attempt
212  *   to determine what type of data it has, and `is_data` will be set
213  *   to whatever is determined (presumably one of VIDEO_H262, VIDEO_H264
214  *   or VIDEO_AVS).
215  *
216  * - If input is from standard input, and `force_stream_type` is FALSE,
217  *   `is_data` will always be set to VIDEO_H262, which may be incorrect.
218  *
219  * - `es` is the new ES reader context.
220  *
221  * Returns 0 if all goes well, 1 if something goes wrong. In the latter case,
222  * suitable messages will have been written out to standard error.
223  */
224 extern int open_input_as_ES(char   *name,
225                             int     use_pes,
226                             int     quiet,
227                             int     force_stream_type,
228                             int     want_data,
229                             int    *is_data,
230                             ES_p   *es);
231 /*
232  * Close an input ES stream opened with `open_input_as_ES`.
233  *
234  * Specifically, this will close the ES stream and also any underlying PES
235  * reader and file (unless the input was standard input).
236  *
237  * - `name` is the name of the file, used for error reporting.
238  * - `es` is the ES stream to close. This will be set to NULL.
239  *
240  * Returns 0 if all goes well, 1 if something goes wrong. In the latter case,
241  * suitable messages will have been written out to standard error.
242  */
243 extern int close_input_as_ES(char   *name,
244                              ES_p   *es);
245 
246 
247 // ============================================================
248 // Command line "helpers"
249 // ============================================================
250 /*
251  * Read in an unsigned integer value, checking for extraneous characters.
252  *
253  * - `prefix` is an optional prefix for error messages, typically the
254  *   name of the program. It may be NULL.
255  * - `cmd` is the command switch we're reading for (typically ``argv[ii]``),
256  *   which is used in error messages.
257  * - `str` is the string to read (typically ``argv[ii+1]``).
258  * - `base` is the base to read to. If it is 0, then the user can use
259  *   C-style expressions like "0x68" to specify the base on the command line.
260  * - `value` is the value read.
261  *
262  * Returns 0 if all went well, 1 otherwise (in which case a message
263  * explaining will have been written to stderr).
264  */
265 extern int unsigned_value(char      *prefix,
266                           char      *cmd,
267                           char      *arg,
268                           int        base,
269                           uint32_t  *value);
270 /*
271  * Read in an integer value, checking for extraneous characters.
272  *
273  * - `prefix` is an optional prefix for error messages, typically the
274  *   name of the program. It may be NULL.
275  * - `cmd` is the command switch we're reading for (typically ``argv[ii]``),
276  *   which is used in error messages.
277  * - `str` is the string to read (typically ``argv[ii+1]``).
278  * - if `positive` is true, then the number read must be positive (0 or more).
279  * - `base` is the base to read to. If it is 0, then the user can use
280  *   C-style expressions like "0x68" to specify the base on the command line.
281  * - `value` is the value read.
282  *
283  * Returns 0 if all went well, 1 otherwise (in which case a message
284  * explaining will have been written to stderr).
285  */
286 extern int int_value(char *prefix,
287                      char *cmd,
288                      char *str,
289                      int   positive,
290                      int   base,
291                      int  *value);
292 /*
293  * Read in an integer value, checking for extraneous characters and a range.
294  *
295  * - `prefix` is an optional prefix for error messages, typically the
296  *   name of the program. It may be NULL.
297  * - `cmd` is the command switch we're reading for (typically ``argv[ii]``),
298  *   which is used in error messages.
299  * - `str` is the string to read (typically ``argv[ii+1]``).
300  * - `minimum` is the minimum value allowed.
301  * - `maximum` is the maximum value allowed.
302  * - `base` is the base to read to. If it is 0, then the user can use
303  *   C-style expressions like "0x68" to specify the base on the command line.
304  * - `value` is the value read.
305  *
306  * Returns 0 if all went well, 1 otherwise (in which case a message
307  * explaining will have been written to stderr).
308  */
309 extern int int_value_in_range(char *prefix,
310                               char *cmd,
311                               char *arg,
312                               int   minimum,
313                               int   maximum,
314                               int   base,
315                               int  *value);
316 /*
317  * Read in a double value, checking for extraneous characters.
318  *
319  * - `prefix` is an optional prefix for error messages, typically the
320  *   name of the program. It may be NULL.
321  * - `cmd` is the command switch we're reading for (typically ``argv[ii]``),
322  *   which is used in error messages.
323  * - `str` is the string to read (typically ``argv[ii+1]``).
324  * - if `positive` is true, then the number read must be positive (0 or more).
325  * - `value` is the value read.
326  *
327  * Returns 0 if all went well, 1 otherwise (in which case a message
328  * explaining will have been written to stderr).
329  */
330 extern int double_value(char   *prefix,
331                            char   *cmd,
332                            char   *arg,
333                            int     positive,
334                            double *value);
335 /*
336  * Read in a hostname and (optional) port
337  *
338  * - `prefix` is an optional prefix for error messages, typically the
339  *   name of the program. It may be NULL.
340  * - `cmd` is the command switch we're reading for (typically ``argv[ii]``),
341  *   which is used in error messages.
342  * - `arg` is the string to read (typically ``argv[ii+1]``).
343  * - `hostname` is the host name read
344  * - `port` is the port read (note that this is not touched if there is
345  *   no port number, so it may be set to a default before calling this
346  *   function)
347  *
348  * Note that this works by pointing `hostname` to the start of the `arg`
349  * string, and then if there is a ':' in `arg`, changing that colon to
350  * a '\0' delimiter, and interpreting the string thereafter as the port
351  * number. If *that* fails, it resets the '\0' as a ':'.
352  *
353  * Returns 0 if all went well, 1 otherwise (in which case a message
354  * explaining will have been written to stderr).
355  */
356 extern int host_value(char  *prefix,
357                       char  *cmd,
358                       char  *arg,
359                       char **hostname,
360                       int   *port);
361 
362 
363 
364 
365 // ============================================================
366 // Sockets
367 // ============================================================
368 #ifdef _WIN32
369 /*
370  * Start up WINSOCK so we can use sockets.
371  *
372  * Note that each successful call of this *must* be matched by a call
373  * of winsock_cleanup().
374  *
375  * Returns 0 if it works, 1 if it fails.
376  */
377 extern int winsock_startup();
378 /*
379  * Convert a WinSock error number into a string and print it out on stderr
380  */
381 extern void print_winsock_err(int err);
382 #endif // _WIN32
383 /*
384  * Connect to a socket, to allow us to write to it, using TCP/IP.
385  *
386  * - `hostname` is the name of the host to connect to
387  * - `port` is the port to use
388  * - if `use_tcpip`, then a TCP/IP connection will be made, otherwise UDP.
389  *   For UDP, multicast TTL will be enabled.
390  * - If the destination address (`hostname`) is multicast and `multicast_ifaddr`
391  *   is supplied, it is used to select (by IP address) the network interface
392  *   on which to send the multicasts.  It may be NULL to use the default,
393  *   or for non-multicast cases.
394  *
395  * A socket connected to via this function must be disconnected from with
396  * disconnect_socket().
397  *
398  * Returns a positive integer (the file descriptor for the socket) if it
399  * succeeds, or -1 if it fails, in which case it will have complained on
400  * stderr.
401  */
402 extern int connect_socket(char *hostname,
403                           int   port,
404                           int   use_tcpip,
405                           char *multicast_ifaddr);
406 
407 /*
408  * Disconnect from a socket (close it).
409  *
410  * Returns 0 if all goes well, 1 otherwise.
411  */
412 #ifdef _WIN32
413 extern int disconnect_socket(SOCKET  socket);
414 #else  // _WIN32
415 extern int disconnect_socket(int  socket);
416 #endif // _WIN32
417 
418 /*! Decode a host byte order address to a static buffer. */
419 const char *ipv4_addr_to_string(const uint32_t addr);
420 
421 /*! Decode a string to a host byte order address */
422 int ipv4_string_to_addr(uint32_t *dest, const char *addr);
423 
424 
425 // ============================================================
426 // Byte order handling
427 // ============================================================
428 
429 
uint_32_be(const uint8_t * const p)430 static inline uint32_t uint_32_be(const uint8_t *const p)
431 {
432   return (((int)p[0]&0xff) << 24) |
433     (((int)p[1]&0xff) << 16) |
434     (((int)p[2]&0xff) << 8) |
435     (((int)p[3]&0xff));
436 }
437 
438 
uint_32_le(const uint8_t * const p)439 static inline uint32_t uint_32_le(const uint8_t *const p)
440 {
441   return (((int)p[0]&0xff) |
442 	  (((int)p[1]&0xff) << 8) |
443 	  (((int)p[2]&0xff) << 16) |
444 	  (((int)p[3]&0xff) << 24));
445 }
446 
447 
uint_16_be(const uint8_t * const p)448 static inline uint16_t uint_16_be(const uint8_t *const p)
449 {
450   return ((((int)p[0])&0xff)<<8) |
451     ((((int)p[1])&0xff));
452 }
453 
uint_16_le(const uint8_t * const p)454 static inline uint16_t uint_16_le(const uint8_t *const p)
455 {
456   return (((int)p[0]&0xff) |
457 	  ((int)p[1]&0xff)<<8);
458 }
459 
460 
461 #endif // _misc_fns
462 
463 // Local Variables:
464 // tab-width: 8
465 // indent-tabs-mode: nil
466 // c-basic-offset: 2
467 // End:
468 // vim: set tabstop=8 shiftwidth=2 expandtab:
469