vlc_common.h 32.8 KB
Newer Older
Sam Hocevar's avatar
 
Sam Hocevar committed
1
/*****************************************************************************
Pere Orga's avatar
Pere Orga committed
2
 * vlc_common.h: common definitions
Sam Hocevar's avatar
 
Sam Hocevar committed
3 4
 * Collection of useful common types and macros definitions
 *****************************************************************************
5
 * Copyright (C) 1998-2011 VLC authors and VideoLAN
Sam Hocevar's avatar
 
Sam Hocevar committed
6 7 8
 *
 * Authors: Samuel Hocevar <sam@via.ecp.fr>
 *          Vincent Seguin <seguin@via.ecp.fr>
9
 *          Gildas Bazin <gbazin@videolan.org>
10
 *          Rémi Denis-Courmont
Sam Hocevar's avatar
 
Sam Hocevar committed
11
 *
12 13 14
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
Sam Hocevar's avatar
 
Sam Hocevar committed
15
 * (at your option) any later version.
16
 *
Sam Hocevar's avatar
 
Sam Hocevar committed
17 18
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
Sam Hocevar's avatar
 
Sam Hocevar committed
21
 *
22 23 24
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
Sam Hocevar's avatar
 
Sam Hocevar committed
25 26
 *****************************************************************************/

27 28 29
#ifndef VLC_COMMON_H
# define VLC_COMMON_H 1

Clément Stenac's avatar
Clément Stenac committed
30
/**
31
 * \defgroup vlc VLC plug-in programming interface
Sam Hocevar's avatar
Sam Hocevar committed
32
 * \file
33
 * \ingroup vlc
Clément Stenac's avatar
Clément Stenac committed
34 35 36
 * This file is a collection of common definitions and types
 */

37
/*****************************************************************************
38
 * Required vlc headers
39
 *****************************************************************************/
40 41
#include "vlc_config.h"

Sam Hocevar's avatar
 
Sam Hocevar committed
42 43 44
/*****************************************************************************
 * Required system headers
 *****************************************************************************/
Gildas Bazin's avatar
 
Gildas Bazin committed
45
#include <stdlib.h>
46 47
#include <stdarg.h>

48
#include <string.h>
49
#include <stdio.h>
50
#include <inttypes.h>
51
#include <stddef.h>
Sam Hocevar's avatar
 
Sam Hocevar committed
52

53 54 55 56
#ifndef __cplusplus
# include <stdbool.h>
#endif

57 58
/**
 * \defgroup cext C programming language extensions
59
 * \ingroup vlc
60 61 62 63 64 65
 *
 * This section defines a number of macros and inline functions extending the
 * C language. Most extensions are implemented by GCC and LLVM/Clang, and have
 * unoptimized fallbacks for other C11/C++11 conforming compilers.
 * @{
 */
66 67 68 69
#ifdef __GNUC__
# define VLC_GCC_VERSION(maj,min) \
    ((__GNUC__ > (maj)) || (__GNUC__ == (maj) && __GNUC_MINOR__ >= (min)))
#else
70
/** GCC version check */
71 72 73
# define VLC_GCC_VERSION(maj,min) (0)
#endif

74 75 76 77 78 79 80 81 82 83 84 85
/* Try to fix format strings for all versions of mingw and mingw64 */
#if defined( _WIN32 ) && defined( __USE_MINGW_ANSI_STDIO )
 #undef PRId64
 #define PRId64 "lld"
 #undef PRIi64
 #define PRIi64 "lli"
 #undef PRIu64
 #define PRIu64 "llu"
 #undef PRIo64
 #define PRIo64 "llo"
 #undef PRIx64
 #define PRIx64 "llx"
86 87
 #define snprintf __mingw_snprintf
 #define vsnprintf __mingw_vsnprintf
88
 #define swprintf _snwprintf
89 90
#endif

91
/* Function attributes for compiler warnings */
92
#ifdef __GNUC__
93
# define VLC_DEPRECATED __attribute__((deprecated))
94 95 96 97 98
# if VLC_GCC_VERSION(6,0)
#  define VLC_DEPRECATED_ENUM __attribute__((deprecated))
# else
#  define VLC_DEPRECATED_ENUM
# endif
99

100
# if defined( _WIN32 ) && !defined( __clang__ )
101 102 103 104 105 106
#  define VLC_FORMAT(x,y) __attribute__ ((format(gnu_printf,x,y)))
# else
#  define VLC_FORMAT(x,y) __attribute__ ((format(printf,x,y)))
# endif
# define VLC_FORMAT_ARG(x) __attribute__ ((format_arg(x)))
# define VLC_MALLOC __attribute__ ((malloc))
107
# define VLC_USED __attribute__ ((warn_unused_result))
108

109
#else
110 111 112 113 114 115 116 117 118
/**
 * Deprecated functions or compound members annotation
 *
 * Use this macro in front of a function declaration or compound member
 * within a compound type declaration.
 * The compiler may emit a warning every time the function or member is used.
 *
 * Use \ref VLC_DEPRECATED_ENUM instead for enumeration members.
 */
119
# define VLC_DEPRECATED
120 121 122 123 124 125 126 127 128

/**
 * Deprecated enum member annotation
 *
 * Use this macro after an enumerated type member declaration.
 * The compiler may emit a warning every time the enumeration member is used.
 *
 * See also \ref VLC_DEPRECATED.
 */
129
# define VLC_DEPRECATED_ENUM
130 131 132 133 134 135 136 137 138 139 140

/**
 * String format function annotation
 *
 * Use this macro after a function prototype/declaration if the function
 * expects a standard C format string. This helps compiler diagnostics.
 *
 * @param x the position (starting from 1) of the format string argument
 * @param y the first position (also starting from 1) of the variable arguments
 *          following the format string (usually but not always \p x+1).
 */
141
# define VLC_FORMAT(x,y)
142 143 144 145 146 147 148 149 150 151

/**
 * Format string translation function annotation
 *
 * Use this macro after a function prototype/declaration if the function
 * expects a format string as input and returns another format string as output
 * to another function.
 *
 * This is primarily intended for localization functions such as gettext().
 */
152
# define VLC_FORMAT_ARG(x)
153 154 155 156 157 158 159 160 161 162 163 164 165 166

/**
 * Heap allocated result function annotation
 *
 * Use this macro to annotate a function that returns a pointer to memory that
 * cannot alias any other valid pointer.
 *
 * This is primarily used for functions that return a pointer to heap-allocated
 * memory, but it can be used for other applicable purposes.
 *
 * \warning Do not use this annotation if the returned pointer can in any way
 * alias a valid pointer at the time the function exits. This could lead to
 * very weird memory corruption bugs.
 */
167
# define VLC_MALLOC
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184

/**
 * Used result function annotation
 *
 * Use this macro to annotate a function whose result must be used.
 *
 * There are several cases where this is useful:
 * - If a function has no side effects (or no useful side effects), such that
 *   the only useful purpose of calling said function is to obtain its
 *   return value.
 * - If ignoring the function return value would lead to a resource leak
 *   (including but not limited to a memory leak).
 * - If a function cannot be used correctly without checking its return value.
 *   For instance, if the function can fail at any time.
 *
 * The compiler may warn if the return value of a function call is ignored.
 */
185
# define VLC_USED
186 187
#endif

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
188 189 190 191 192 193 194 195 196 197 198 199
#ifdef __ELF__
# define VLC_WEAK __attribute__((weak))
#else
/**
 * Weak symbol annotation
 *
 * Use this macro before an external identifier \b definition to mark it as a
 * weak symbol. A weak symbol can be overriden by another symbol of the same
 * name at the link time.
 */
# define VLC_WEAK
#endif
200

201
/* Branch prediction */
202
#if defined (__GNUC__) || defined (__clang__)
203 204 205
# define likely(p)     __builtin_expect(!!(p), 1)
# define unlikely(p)   __builtin_expect(!!(p), 0)
# define unreachable() __builtin_unreachable()
206
#else
207 208 209 210 211 212 213
/**
 * Predicted true condition
 *
 * This macro indicates that the condition is expected most often true.
 * The compiler may optimize the code assuming that this condition is usually
 * met.
 */
214
# define likely(p)     (!!(p))
215 216 217 218 219 220 221 222

/**
 * Predicted false condition
 *
 * This macro indicates that the condition is expected most often false.
 * The compiler may optimize the code assuming that this condition is rarely
 * met.
 */
223
# define unlikely(p)   (!!(p))
224 225 226 227 228 229 230 231 232 233 234

/**
 * Impossible branch
 *
 * This macro indicates that the branch cannot be reached at run-time, and
 * represents undefined behaviour.
 * The compiler may optimize the code assuming that the call flow will never
 * logically reach the point where this macro is expanded.
 *
 * See also \ref vlc_assert_unreachable.
 */
235
# define unreachable() ((void)0)
236 237
#endif

238 239 240 241 242 243 244 245 246 247 248
/**
 * Impossible branch assertion
 *
 * This macro asserts that the branch cannot be reached at run-time.
 *
 * If the branch is reached in a debug build, it will trigger an assertion
 * failure and abnormal program termination.
 *
 * If the branch is reached in a non-debug build, this macro is equivalent to
 * \ref unreachable and the behaviour is undefined.
 */
249 250
#define vlc_assert_unreachable() (assert(!"unreachable"), unreachable())

251 252
/* Linkage */
#ifdef __cplusplus
253
# define VLC_EXTERN extern "C"
254
#else
255
# define VLC_EXTERN
256 257
#endif

258
#if defined (_WIN32) && defined (DLL_EXPORT)
259
# define VLC_EXPORT __declspec(dllexport)
260
#elif defined (__GNUC__)
261
# define VLC_EXPORT __attribute__((visibility("default")))
262
#else
263
# define VLC_EXPORT
264 265
#endif

266 267 268 269 270 271
/**
 * Exported API call annotation
 *
 * This macro is placed before a function declaration to indicate that the
 * function is an API call of the LibVLC plugin API.
 */
272
#define VLC_API VLC_EXTERN VLC_EXPORT
273

274
/** @} */
275

Sam Hocevar's avatar
 
Sam Hocevar committed
276 277 278
/*****************************************************************************
 * Basic types definitions
 *****************************************************************************/
Sigmund Augdal Helberg's avatar
Sigmund Augdal Helberg committed
279 280 281
/**
 * High precision date or time interval
 *
282 283
 * Store a high precision date or time interval. The maximum precision is the
 * microsecond, and a 64 bits integer is used to avoid overflows (maximum
Sam Hocevar's avatar
 
Sam Hocevar committed
284
 * time interval is then 292271 years, which should be long enough for any
285 286
 * video). Dates are stored as microseconds since a common date (usually the
 * epoch). Note that date and time intervals can be manipulated using regular
Sam Hocevar's avatar
 
Sam Hocevar committed
287
 * arithmetic operators, and that no special functions are required.
Sigmund Augdal Helberg's avatar
Sigmund Augdal Helberg committed
288
 */
289
typedef int64_t mtime_t;
Sam Hocevar's avatar
 
Sam Hocevar committed
290

Sigmund Augdal Helberg's avatar
Sigmund Augdal Helberg committed
291
/**
292
 * The vlc_fourcc_t type.
Sigmund Augdal Helberg's avatar
Sigmund Augdal Helberg committed
293
 *
294
 * See http://www.webartz.com/fourcc/ for a very detailed list.
Sigmund Augdal Helberg's avatar
Sigmund Augdal Helberg committed
295
 */
296
typedef uint32_t vlc_fourcc_t;
297

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
#ifdef WORDS_BIGENDIAN
#   define VLC_FOURCC( a, b, c, d ) \
        ( ((uint32_t)d) | ( ((uint32_t)c) << 8 ) \
           | ( ((uint32_t)b) << 16 ) | ( ((uint32_t)a) << 24 ) )
#   define VLC_TWOCC( a, b ) \
        ( (uint16_t)(b) | ( (uint16_t)(a) << 8 ) )

#else
#   define VLC_FOURCC( a, b, c, d ) \
        ( ((uint32_t)a) | ( ((uint32_t)b) << 8 ) \
           | ( ((uint32_t)c) << 16 ) | ( ((uint32_t)d) << 24 ) )
#   define VLC_TWOCC( a, b ) \
        ( (uint16_t)(a) | ( (uint16_t)(b) << 8 ) )

#endif

314 315 316 317 318 319 320
/**
 * Translate a vlc_fourcc into its string representation. This function
 * assumes there is enough room in psz_fourcc to store 4 characters in.
 *
 * \param fcc a vlc_fourcc_t
 * \param psz_fourcc string to store string representation of vlc_fourcc in
 */
321
static inline void vlc_fourcc_to_char( vlc_fourcc_t fcc, char *psz_fourcc )
322
{
323
    memcpy( psz_fourcc, &fcc, 4 );
324 325
}

Sam Hocevar's avatar
 
Sam Hocevar committed
326 327 328 329
/*****************************************************************************
 * Classes declaration
 *****************************************************************************/

330
/* Internal types */
331 332
typedef struct vlc_list_t vlc_list_t;
typedef struct vlc_object_t vlc_object_t;
333
typedef struct libvlc_int_t libvlc_int_t;
334
typedef struct date_t date_t;
335

Gildas Bazin's avatar
 
Gildas Bazin committed
336
/* Playlist */
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
337

338 339
typedef struct playlist_t playlist_t;
typedef struct playlist_item_t playlist_item_t;
340
typedef struct services_discovery_t services_discovery_t;
Thomas Guillem's avatar
Thomas Guillem committed
341 342
typedef struct vlc_renderer_discovery_t vlc_renderer_discovery_t;
typedef struct vlc_renderer_item_t vlc_renderer_item_t;
Sam Hocevar's avatar
 
Sam Hocevar committed
343

344
/* Modules */
345 346
typedef struct module_t module_t;
typedef struct module_config_t module_config_t;
Sam Hocevar's avatar
 
Sam Hocevar committed
347

Clément Stenac's avatar
Clément Stenac committed
348 349
typedef struct config_category_t config_category_t;

Sam Hocevar's avatar
 
Sam Hocevar committed
350
/* Input */
351
typedef struct input_thread_t input_thread_t;
352
typedef struct input_item_t input_item_t;
353
typedef struct input_item_node_t input_item_node_t;
354
typedef struct stream_t     stream_t;
355
typedef struct stream_t demux_t;
356 357
typedef struct es_out_t     es_out_t;
typedef struct es_out_id_t  es_out_id_t;
Gildas Bazin's avatar
Gildas Bazin committed
358
typedef struct seekpoint_t seekpoint_t;
359 360
typedef struct info_t info_t;
typedef struct info_category_t info_category_t;
361
typedef struct input_attachment_t input_attachment_t;
Sam Hocevar's avatar
 
Sam Hocevar committed
362

363 364 365 366
/* Format */
typedef struct audio_format_t audio_format_t;
typedef struct video_format_t video_format_t;
typedef struct subs_format_t subs_format_t;
Gildas Bazin's avatar
 
Gildas Bazin committed
367 368
typedef struct es_format_t es_format_t;
typedef struct video_palette_t video_palette_t;
369

Sam Hocevar's avatar
 
Sam Hocevar committed
370
/* Audio */
371
typedef struct audio_output audio_output_t;
Gildas Bazin's avatar
 
Gildas Bazin committed
372
typedef audio_format_t audio_sample_format_t;
Sam Hocevar's avatar
 
Sam Hocevar committed
373 374

/* Video */
375
typedef struct vout_thread_t vout_thread_t;
376
typedef struct vlc_viewpoint_t vlc_viewpoint_t;
377

Gildas Bazin's avatar
 
Gildas Bazin committed
378
typedef video_format_t video_frame_format_t;
379 380
typedef struct picture_t picture_t;
typedef struct picture_sys_t picture_sys_t;
381

382
/* Subpictures */
383
typedef struct spu_t spu_t;
384
typedef struct subpicture_t subpicture_t;
385
typedef struct subpicture_region_t subpicture_region_t;
Sam Hocevar's avatar
 
Sam Hocevar committed
386

387 388
typedef struct image_handler_t image_handler_t;

389 390
/* Stream output */
typedef struct sout_instance_t sout_instance_t;
391

392
typedef struct sout_input_t sout_input_t;
393
typedef struct sout_packetizer_input_t sout_packetizer_input_t;
394

395
typedef struct sout_access_out_t sout_access_out_t;
396

397
typedef struct sout_mux_t sout_mux_t;
398

399
typedef struct sout_stream_t    sout_stream_t;
400

401
typedef struct config_chain_t       config_chain_t;
402
typedef struct session_descriptor_t session_descriptor_t;
403

Sam Hocevar's avatar
 
Sam Hocevar committed
404
/* Decoders */
Laurent Aimar's avatar
Laurent Aimar committed
405 406
typedef struct decoder_t         decoder_t;
typedef struct decoder_synchro_t decoder_synchro_t;
Sam Hocevar's avatar
 
Sam Hocevar committed
407

Gildas Bazin's avatar
 
Gildas Bazin committed
408 409 410
/* Encoders */
typedef struct encoder_t      encoder_t;

411 412 413
/* Filters */
typedef struct filter_t filter_t;

414
/* Network */
415
typedef struct vlc_url_t vlc_url_t;
416

417 418 419
/* Misc */
typedef struct iso639_lang_t iso639_lang_t;

420 421 422 423
/* block */
typedef struct block_t      block_t;
typedef struct block_fifo_t block_fifo_t;

424 425 426
/* Hashing */
typedef struct md5_s md5_t;

Gildas Bazin's avatar
Gildas Bazin committed
427 428 429 430
/* XML */
typedef struct xml_t xml_t;
typedef struct xml_reader_t xml_reader_t;

431 432
/* vod server */
typedef struct vod_t     vod_t;
433
typedef struct vod_media_t vod_media_t;
434

435
/* VLM */
436 437
typedef struct vlm_t         vlm_t;
typedef struct vlm_message_t vlm_message_t;
438

439
/* misc */
440
typedef struct vlc_meta_t    vlc_meta_t;
Clément Stenac's avatar
Clément Stenac committed
441
typedef struct input_stats_t input_stats_t;
442
typedef struct addon_entry_t addon_entry_t;
443

444 445
/* Update */
typedef struct update_t update_t;
446

447 448 449 450 451
/**
 * VLC value structure
 */
typedef union
{
452
    int64_t         i_int;
453
    bool            b_bool;
454 455 456 457
    float           f_float;
    char *          psz_string;
    void *          p_address;
    vlc_list_t *    p_list;
458
    struct { int32_t x; int32_t y; } coords;
459 460 461 462 463 464 465 466

} vlc_value_t;

/**
 * VLC list structure
 */
struct vlc_list_t
{
467 468 469
    int          i_type;
    int          i_count;
    vlc_value_t *p_values;
470 471 472 473 474
};

/*****************************************************************************
 * Error values (shouldn't be exposed)
 *****************************************************************************/
475 476 477 478 479 480 481 482 483
#define VLC_SUCCESS        (-0) /**< No error */
#define VLC_EGENERIC       (-1) /**< Unspecified error */
#define VLC_ENOMEM         (-2) /**< Not enough memory */
#define VLC_ETIMEOUT       (-3) /**< Timeout */
#define VLC_ENOMOD         (-4) /**< Module not found */
#define VLC_ENOOBJ         (-5) /**< Object not found */
#define VLC_ENOVAR         (-6) /**< Variable not found */
#define VLC_EBADVAR        (-7) /**< Bad variable value */
#define VLC_ENOITEM        (-8) /**< Item not found */
484

485
/*****************************************************************************
486
 * Variable callbacks: called when the value is modified
487 488 489 490 491 492 493
 *****************************************************************************/
typedef int ( * vlc_callback_t ) ( vlc_object_t *,      /* variable's object */
                                   char const *,            /* variable name */
                                   vlc_value_t,                 /* old value */
                                   vlc_value_t,                 /* new value */
                                   void * );                /* callback data */

494 495 496 497 498 499 500 501 502
/*****************************************************************************
 * List callbacks: called when elements are added/removed from the list
 *****************************************************************************/
typedef int ( * vlc_list_callback_t ) ( vlc_object_t *,      /* variable's object */
                                        char const *,            /* variable name */
                                        int,                  /* VLC_VAR_* action */
                                        vlc_value_t *,      /* new/deleted value  */
                                        void *);                 /* callback data */

503 504 505
/*****************************************************************************
 * OS-specific headers and thread types
 *****************************************************************************/
506
#if defined( _WIN32 )
507 508 509 510 511 512 513
#   include <malloc.h>
#   ifndef PATH_MAX
#       define PATH_MAX MAX_PATH
#   endif
#   include <windows.h>
#endif

514 515 516 517 518
#ifdef __APPLE__
#include <sys/syslimits.h>
#include <AvailabilityMacros.h>
#endif

519 520 521 522
#ifdef __OS2__
#   define OS2EMX_PLAIN_CHAR
#   define INCL_BASE
#   define INCL_PM
KO Myung-Hun's avatar
KO Myung-Hun committed
523
#   include <os2safe.h>
524 525 526
#   include <os2.h>
#endif

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
527
#include "vlc_mtime.h"
528 529
#include "vlc_threads.h"

530 531
/**
 * \defgroup intops Integer operations
532
 * \ingroup cext
533 534 535 536
 *
 * Common integer functions.
 * @{
 */
Sam Hocevar's avatar
 
Sam Hocevar committed
537 538 539
/* __MAX and __MIN: self explanatory */
#ifndef __MAX
#   define __MAX(a, b)   ( ((a) > (b)) ? (a) : (b) )
Sam Hocevar's avatar
 
Sam Hocevar committed
540
#endif
Sam Hocevar's avatar
 
Sam Hocevar committed
541 542
#ifndef __MIN
#   define __MIN(a, b)   ( ((a) < (b)) ? (a) : (b) )
Sam Hocevar's avatar
 
Sam Hocevar committed
543 544
#endif

545 546 547
/* clip v in [min, max] */
#define VLC_CLIP(v, min, max)    __MIN(__MAX((v), (min)), (max))

548
/** Greatest common divisor */
549
VLC_USED
550
static inline int64_t GCD ( int64_t a, int64_t b )
551
{
552 553 554 555 556 557 558
    while( b )
    {
        int64_t c = a % b;
        a = b;
        b = c;
    }
    return a;
559 560
}

561
/* function imported from libavutil/common.h */
562
VLC_USED
563 564 565 566 567 568
static inline uint8_t clip_uint8_vlc( int32_t a )
{
    if( a&(~255) ) return (-a)>>31;
    else           return a;
}

569 570 571 572
/**
 * \defgroup bitops Bit operations
 * @{
 */
573

574 575 576 577
#define VLC_INT_FUNC(basename) \
        VLC_INT_FUNC_TYPE(basename, unsigned, ) \
        VLC_INT_FUNC_TYPE(basename, unsigned long, l) \
        VLC_INT_FUNC_TYPE(basename, unsigned long long, ll)
578

579 580 581 582 583
#if defined (__GNUC__) || defined (__clang__)
# define VLC_INT_FUNC_TYPE(basename,type,suffix) \
VLC_USED static inline int vlc_##basename##suffix(type x) \
{ \
    return __builtin_##basename##suffix(x); \
584 585
}

586 587 588
VLC_INT_FUNC(clz)
#else
VLC_USED static inline int vlc_clzll(unsigned long long x)
589
{
590
    int i = sizeof (x) * 8;
591

592 593 594 595 596 597
    while (x)
    {
        x >>= 1;
        i--;
    }
    return i;
598 599
}

600
VLC_USED static inline int vlc_clzl(unsigned long x)
601
{
602
    return vlc_clzll(x) - ((sizeof (long long) - sizeof (long)) * 8);
603 604
}

605
VLC_USED static inline int vlc_clz(unsigned x)
606
{
607
    return vlc_clzll(x) - ((sizeof (long long) - sizeof (int)) * 8);
608 609
}

610
VLC_USED static inline int vlc_ctz_generic(unsigned long long x)
611
{
612
    unsigned i = sizeof (x) * 8;
613

614 615 616 617 618 619
    while (x)
    {
        x <<= 1;
        i--;
    }
    return i;
620
}
621

622
VLC_USED static inline int vlc_parity_generic(unsigned long long x)
623
{
624 625 626
    for (unsigned i = 4 * sizeof (x); i > 0; i /= 2)
        x ^= x >> i;
    return x & 1;
627 628
}

629
VLC_USED static inline int vlc_popcount_generic(unsigned long long x)
630
{
631 632 633 634 635 636 637
    int count = 0;
    while (x)
    {
        count += x & 1;
        x = x >> 1;
    }
    return count;
638 639
}

640 641 642 643
# define VLC_INT_FUNC_TYPE(basename,type,suffix) \
VLC_USED static inline int vlc_##basename##suffix(type x) \
{ \
    return vlc_##basename##_generic(x); \
644
}
645
#endif
646

647 648 649
VLC_INT_FUNC(ctz)
VLC_INT_FUNC(parity)
VLC_INT_FUNC(popcount)
650

651 652 653 654 655 656 657 658 659 660 661 662 663
#ifndef __cplusplus
# define VLC_INT_GENERIC(func,x) \
    _Generic((x), \
        unsigned char:      func(x), \
          signed char:      func(x), \
        unsigned short:     func(x), \
          signed short:     func(x), \
        unsigned int:       func(x), \
          signed int:       func(x), \
        unsigned long:      func##l(x), \
          signed long:      func##l(x), \
        unsigned long long: func##ll(x), \
          signed long long: func##ll(x))
664

665 666 667 668 669 670 671 672 673 674 675
/**
 * Count leading zeroes
 *
 * This function counts the number of consecutive zero (clear) bits
 * down from the highest order bit in an unsigned integer.
 *
 * \param x a non-zero integer
 * \note This macro assumes that CHAR_BIT equals 8.
 * \warning By definition, the result depends on the (width of the) type of x.
 * \return The number of leading zero bits in x.
 */
676
# define clz(x) \
677
    _Generic((x), \
678 679 680 681 682 683
        unsigned char: (vlc_clz(x) - (sizeof (unsigned) - 1) * 8), \
        unsigned short: (vlc_clz(x) \
		- (sizeof (unsigned) - sizeof (unsigned short)) * 8), \
        unsigned: vlc_clz(x), \
        unsigned long: vlc_clzl(x), \
        unsigned long long: vlc_clzll(x))
684

685 686 687 688 689 690 691 692 693 694
/**
 * Count trailing zeroes
 *
 * This function counts the number of consecutive zero bits
 * up from the lowest order bit in an unsigned integer.
 *
 * \param x a non-zero integer
 * \note This function assumes that CHAR_BIT equals 8.
 * \return The number of trailing zero bits in x.
 */
695
# define ctz(x) VLC_INT_GENERIC(vlc_ctz, x)
696

697 698 699 700 701 702 703 704
/**
 * Parity
 *
 * This function determines the parity of an integer.
 * \retval 0 if x has an even number of set bits.
 * \retval 1 if x has an odd number of set bits.
 */
# define parity(x) VLC_INT_GENERIC(vlc_parity, x)
705

706 707 708 709 710 711 712
/**
 * Bit weight / population count
 *
 * This function counts the number of non-zero bits in an integer.
 *
 * \return The count of non-zero bits.
 */
713
# define vlc_popcount(x) \
714
    _Generic((x), \
715 716 717 718 719 720 721 722
        signed char:  vlc_popcount((unsigned char)(x)), \
        signed short: vlc_popcount((unsigned short)(x)), \
        default: VLC_INT_GENERIC(vlc_popcount ,x))
#else
VLC_USED static inline int vlc_popcount(unsigned char x)
{
    return vlc_popcount((unsigned)x);
}
723

724
VLC_USED static inline int vlc_popcount(unsigned short x)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
725
{
726
    return vlc_popcount((unsigned)x);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
727 728
}

729 730 731 732 733 734 735 736 737 738
VLC_USED static inline int vlc_popcount(unsigned long x)
{
    return vlc_popcountl(x);
}

VLC_USED static inline int vlc_popcount(unsigned long long x)
{
    return vlc_popcountll(x);
}
#endif
739

740 741
/** Byte swap (16 bits) */
VLC_USED
742
static inline uint16_t vlc_bswap16(uint16_t x)
743 744 745 746 747 748
{
    return (x << 8) | (x >> 8);
}

/** Byte swap (32 bits) */
VLC_USED
749
static inline uint32_t vlc_bswap32(uint32_t x)
750
{
751
#if defined (__GNUC__) || defined(__clang__)
752 753 754 755 756 757 758 759 760 761 762
    return __builtin_bswap32 (x);
#else
    return ((x & 0x000000FF) << 24)
         | ((x & 0x0000FF00) <<  8)
         | ((x & 0x00FF0000) >>  8)
         | ((x & 0xFF000000) >> 24);
#endif
}

/** Byte swap (64 bits) */
VLC_USED
763
static inline uint64_t vlc_bswap64(uint64_t x)
764
{
765
#if defined (__GNUC__) || defined(__clang__)
766
    return __builtin_bswap64 (x);
767
#elif !defined (__cplusplus)
768 769 770 771 772 773 774 775
    return ((x & 0x00000000000000FF) << 56)
         | ((x & 0x000000000000FF00) << 40)
         | ((x & 0x0000000000FF0000) << 24)
         | ((x & 0x00000000FF000000) <<  8)
         | ((x & 0x000000FF00000000) >>  8)
         | ((x & 0x0000FF0000000000) >> 24)
         | ((x & 0x00FF000000000000) >> 40)
         | ((x & 0xFF00000000000000) >> 56);
776
#else
777 778 779 780 781 782 783 784
    return ((x & 0x00000000000000FFULL) << 56)
         | ((x & 0x000000000000FF00ULL) << 40)
         | ((x & 0x0000000000FF0000ULL) << 24)
         | ((x & 0x00000000FF000000ULL) <<  8)
         | ((x & 0x000000FF00000000ULL) >>  8)
         | ((x & 0x0000FF0000000000ULL) >> 24)
         | ((x & 0x00FF000000000000ULL) >> 40)
         | ((x & 0xFF00000000000000ULL) >> 56);
785 786
#endif
}
787
/** @} */
788

789 790 791 792
/**
 * \defgroup overflow Overflowing arithmetic
 * @{
 */
793 794
static inline bool uadd_overflow(unsigned a, unsigned b, unsigned *res)
{
795
#if VLC_GCC_VERSION(5,0) || defined(__clang__)
796 797 798 799 800 801 802 803 804 805
     return __builtin_uadd_overflow(a, b, res);
#else
     *res = a + b;
     return (a + b) < a;
#endif
}

static inline bool uaddl_overflow(unsigned long a, unsigned long b,
                                  unsigned long *res)
{
806
#if VLC_GCC_VERSION(5,0) || defined(__clang__)
807 808 809 810 811 812 813 814 815 816
     return __builtin_uaddl_overflow(a, b, res);
#else
     *res = a + b;
     return (a + b) < a;
#endif
}

static inline bool uaddll_overflow(unsigned long long a, unsigned long long b,
                                   unsigned long long *res)
{
817
#if VLC_GCC_VERSION(5,0) || defined(__clang__)
818 819 820 821 822 823 824 825
     return __builtin_uaddll_overflow(a, b, res);
#else
     *res = a + b;
     return (a + b) < a;
#endif
}

#ifndef __cplusplus
826 827 828 829 830 831 832 833 834 835 836 837 838
/**
 * Overflowing addition
 *
 * Converts \p a and \p b to the type of \p *r.
 * Then computes the sum of both conversions while checking for overflow.
 * Finally stores the result in \p *r.
 *
 * \param a an integer
 * \param b an integer
 * \param r a pointer to an integer [OUT]
 * \retval false The sum did not overflow.
 * \retval true The sum overflowed.
 */
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
# define add_overflow(a,b,r) \
    _Generic(*(r), \
        unsigned: uadd_overflow(a, b, (unsigned *)(r)), \
        unsigned long: uaddl_overflow(a, b, (unsigned long *)(r)), \
        unsigned long long: uaddll_overflow(a, b, (unsigned long long *)(r)))
#else
static inline bool add_overflow(unsigned a, unsigned b, unsigned *res)
{
    return uadd_overflow(a, b, res);
}

static inline bool add_overflow(unsigned long a, unsigned long b,
                                unsigned long *res)
{
    return uaddl_overflow(a, b, res);
}

static inline bool add_overflow(unsigned long long a, unsigned long long b,
                                unsigned long long *res)
{
    return uaddll_overflow(a, b, res);
}
#endif

863 864 865 866
#if !(VLC_GCC_VERSION(5,0) || defined(__clang__))
# include <limits.h>
#endif

867 868
static inline bool umul_overflow(unsigned a, unsigned b, unsigned *res)
{
869
#if VLC_GCC_VERSION(5,0) || defined(__clang__)
870 871 872 873 874 875 876 877 878 879
     return __builtin_umul_overflow(a, b, res);
#else
     *res = a * b;
     return b > 0 && a > (UINT_MAX / b);
#endif
}

static inline bool umull_overflow(unsigned long a, unsigned long b,
                                  unsigned long *res)
{
880
#if VLC_GCC_VERSION(5,0) || defined(__clang__)
881 882 883 884 885 886 887 888 889 890
     return __builtin_umull_overflow(a, b, res);
#else
     *res = a * b;
     return b > 0 && a > (ULONG_MAX / b);
#endif
}

static inline bool umulll_overflow(unsigned long long a, unsigned long long b,
                                   unsigned long long *res)
{
891
#if VLC_GCC_VERSION(5,0) || defined(__clang__)
892 893 894 895 896 897 898 899
     return __builtin_umulll_overflow(a, b, res);
#else
     *res = a * b;
     return b > 0 && a > (ULLONG_MAX / b);
#endif
}

#ifndef __cplusplus
900 901 902 903 904 905 906 907 908 909 910 911 912
/**
 * Overflowing multiplication
 *
 * Converts \p a and \p b to the type of \p *r.
 * Then computes the product of both conversions while checking for overflow.
 * Finally stores the result in \p *r.
 *
 * \param a an integer
 * \param b an integer
 * \param r a pointer to an integer [OUT]
 * \retval false The product did not overflow.
 * \retval true The product overflowed.
 */
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
#define mul_overflow(a,b,r) \
    _Generic(*(r), \
        unsigned: umul_overflow(a, b, (unsigned *)(r)), \
        unsigned long: umull_overflow(a, b, (unsigned long *)(r)), \
        unsigned long long: umulll_overflow(a, b, (unsigned long long *)(r)))
#else
static inline bool mul_overflow(unsigned a, unsigned b, unsigned *res)
{
    return umul_overflow(a, b, res);
}

static inline bool mul_overflow(unsigned long a, unsigned long b,
                                unsigned long *res)
{
    return umull_overflow(a, b, res);
}

static inline bool mul_overflow(unsigned long long a, unsigned long long b,
                                unsigned long long *res)
{
    return umulll_overflow(a, b, res);
}
#endif
936 937
/** @} */
/** @} */
938

939
/* Free and set set the variable to NULL */
940
#define FREENULL(a) do { free( a ); a = NULL; } while(0)
Clément Stenac's avatar
Clément Stenac committed
941

942 943
#define EMPTY_STR(str) (!str || !*str)

944
VLC_API char const * vlc_error( int ) VLC_USED;
Clément Stenac's avatar
Clément Stenac committed
945

946
#include <vlc_arrays.h>
947

Sam Hocevar's avatar
 
Sam Hocevar committed
948
/* MSB (big endian)/LSB (little endian) conversions - network order is always
949
 * MSB, and should be used for both network communications and files. */
950 951 952 953

#ifdef WORDS_BIGENDIAN
# define hton16(i) ((uint16_t)(i))
# define hton32(i) ((uint32_t)(i))
954
# define hton64(i) ((uint64_t)(i))
955
#else
956 957 958
# define hton16(i) vlc_bswap16(i)
# define hton32(i) vlc_bswap32(i)
# define hton64(i) vlc_bswap64(i)
959 960 961 962 963 964
#endif
#define ntoh16(i) hton16(i)
#define ntoh32(i) hton32(i)
#define ntoh64(i) hton64(i)

/** Reads 16 bits in network byte order */
965
VLC_USED
966
static inline uint16_t U16_AT (const void *p)
967
{
968 969 970 971
    uint16_t x;

    memcpy (&x, p, sizeof (x));
    return ntoh16 (x);
972
}
973

974
/** Reads 32 bits in network byte order */
975
VLC_USED
976
static inline uint32_t U32_AT (const void *p)
977
{
978 979 980 981
    uint32_t x;

    memcpy (&x, p, sizeof (x));
    return ntoh32 (x);
982
}
983

984
/** Reads 64 bits in network byte order */
985
VLC_USED
986
static inline uint64_t U64_AT (const void *p)
987
{
988 989 990 991
    uint64_t x;

    memcpy (&x, p, sizeof (x));
    return ntoh64 (x);
992
}
993

994 995 996 997 998
#define GetWBE(p)  U16_AT(p)
#define GetDWBE(p) U32_AT(p)
#define GetQWBE(p) U64_AT(p)

/** Reads 16 bits in little-endian order */
999
VLC_USED
1000
static inline uint16_t GetWLE (const void *p)
1001
{
1002 1003 1004 1005
    uint16_t x;

    memcpy (&x, p, sizeof (x));
#ifdef WORDS_BIGENDIAN
1006
    x = vlc_bswap16 (x);
1007 1008
#endif
    return x;
1009
}
1010

1011
/** Reads 32 bits in little-endian order */
1012
VLC_USED
1013
static inline uint32_t GetDWLE (const void *p)
1014
{
1015 1016 1017 1018
    uint32_t x;

    memcpy (&x, p, sizeof (x));
#ifdef WORDS_BIGENDIAN
1019
    x = vlc_bswap32 (x);
1020 1021
#endif
    return x;
1022
}
1023

1024
/** Reads 64 bits in little-endian order */
1025
VLC_USED
1026
static inline uint64_t GetQWLE (const void *p)
1027
{
1028
    uint64_t x;
1029

1030 1031
    memcpy (&x, p, sizeof (x));
#ifdef WORDS_BIGENDIAN
1032
    x = vlc_bswap64 (x);
1033 1034
#endif
    return x;
Gildas Bazin's avatar
 
Gildas Bazin committed
1035 1036
}

1037
/** Writes 16 bits in network byte order */
1038
static inline void SetWBE (void *p, uint16_t w)
Gildas Bazin's avatar
 
Gildas Bazin committed
1039
{
1040 1041
    w = hton16 (w);
    memcpy (p, &w, sizeof (w));
Gildas Bazin's avatar
 
Gildas Bazin committed
1042
}
1043 1044

/** Writes 32 bits in network byte order */
1045
static inline void SetDWBE (void *p, uint32_t dw)
Gildas Bazin's avatar
 
Gildas Bazin committed
1046
{
1047 1048
    dw = hton32 (dw);
    memcpy (p, &dw, sizeof (dw));
Gildas Bazin's avatar
 
Gildas Bazin committed
1049
}
1050 1051

/** Writes 64 bits in network byte order */
1052
static inline void SetQWBE (void *p, uint64_t qw)