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

188
#if defined (__ELF__) || defined (__MACH__)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
189 190 191 192 193 194 195 196 197 198 199
# 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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
#define vlc_assert_unreachable() (vlc_assert(!"unreachable"), unreachable())

/**
 * Run-time assertion
 *
 * This macro performs a run-time assertion if C assertions are enabled
 * and the following preprocessor symbol is defined:
 * @verbatim __LIBVLC__ @endverbatim
 * That restriction ensures that assertions in public header files are not
 * unwittingly <i>leaked</i> to externally-compiled plug-ins
 * including those header files.
 *
 * Within the LibVLC code base, this is exactly the same as assert(), which can
 * and probably should be used directly instead.
 */
#ifdef __LIBVLC__
# define vlc_assert(pred) assert(pred)
#else
# define vlc_assert(pred) ((void)0)
#endif
269

270 271
/* Linkage */
#ifdef __cplusplus
272
# define VLC_EXTERN extern "C"
273
#else
274
# define VLC_EXTERN
275 276
#endif

277
#if defined (_WIN32) && defined (DLL_EXPORT)
278
# define VLC_EXPORT __declspec(dllexport)
279
#elif defined (__GNUC__)
280
# define VLC_EXPORT __attribute__((visibility("default")))
281
#else
282
# define VLC_EXPORT
283 284
#endif

285 286 287 288 289 290
/**
 * 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.
 */
291
#define VLC_API VLC_EXTERN VLC_EXPORT
292

293
/** @} */
294

Sam Hocevar's avatar
 
Sam Hocevar committed
295 296 297
/*****************************************************************************
 * Basic types definitions
 *****************************************************************************/
Sigmund Augdal Helberg's avatar
Sigmund Augdal Helberg committed
298
/**
299
 * The vlc_fourcc_t type.
Sigmund Augdal Helberg's avatar
Sigmund Augdal Helberg committed
300
 *
301
 * See http://www.webartz.com/fourcc/ for a very detailed list.
Sigmund Augdal Helberg's avatar
Sigmund Augdal Helberg committed
302
 */
303
typedef uint32_t vlc_fourcc_t;
304

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
#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

321 322 323 324 325 326 327
/**
 * 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
 */
328
static inline void vlc_fourcc_to_char( vlc_fourcc_t fcc, char *psz_fourcc )
329
{
330
    memcpy( psz_fourcc, &fcc, 4 );
331 332
}

Sam Hocevar's avatar
 
Sam Hocevar committed
333 334 335 336
/*****************************************************************************
 * Classes declaration
 *****************************************************************************/

337
/* Internal types */
338
typedef struct vlc_object_t vlc_object_t;
339
typedef struct libvlc_int_t libvlc_int_t;
340
typedef struct date_t date_t;
341

Gildas Bazin's avatar
 
Gildas Bazin committed
342
/* Playlist */
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
343

344 345
typedef struct playlist_t playlist_t;
typedef struct playlist_item_t playlist_item_t;
346
typedef struct services_discovery_t services_discovery_t;
Thomas Guillem's avatar
Thomas Guillem committed
347 348
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
349

350
/* Modules */
351 352
typedef struct module_t module_t;
typedef struct module_config_t module_config_t;
Sam Hocevar's avatar
 
Sam Hocevar committed
353

354 355
typedef struct config_category_t config_category_t;

Sam Hocevar's avatar
 
Sam Hocevar committed
356
/* Input */
357
typedef struct input_item_t input_item_t;
358
typedef struct input_item_node_t input_item_node_t;
359
typedef struct stream_t     stream_t;
360
typedef struct stream_t demux_t;
361 362
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
363
typedef struct seekpoint_t seekpoint_t;
364 365
typedef struct info_t info_t;
typedef struct info_category_t info_category_t;
366
typedef struct input_attachment_t input_attachment_t;
Sam Hocevar's avatar
 
Sam Hocevar committed
367

368 369 370 371
/* 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
372 373
typedef struct es_format_t es_format_t;
typedef struct video_palette_t video_palette_t;
374
typedef struct vlc_es_id_t vlc_es_id_t;
375

Sam Hocevar's avatar
 
Sam Hocevar committed
376
/* Audio */
377
typedef struct audio_output audio_output_t;
Gildas Bazin's avatar
 
Gildas Bazin committed
378
typedef audio_format_t audio_sample_format_t;
Sam Hocevar's avatar
 
Sam Hocevar committed
379 380

/* Video */
381
typedef struct vout_thread_t vout_thread_t;
382
typedef struct vlc_viewpoint_t vlc_viewpoint_t;
383

Gildas Bazin's avatar
 
Gildas Bazin committed
384
typedef video_format_t video_frame_format_t;
385
typedef struct picture_t picture_t;
386

387
/* Subpictures */
388
typedef struct spu_t spu_t;
389
typedef struct subpicture_t subpicture_t;
390
typedef struct subpicture_region_t subpicture_region_t;
Sam Hocevar's avatar
 
Sam Hocevar committed
391

392 393
typedef struct image_handler_t image_handler_t;

394 395
/* Stream output */
typedef struct sout_instance_t sout_instance_t;
396

397
typedef struct sout_input_t sout_input_t;
398
typedef struct sout_packetizer_input_t sout_packetizer_input_t;
399

400
typedef struct sout_access_out_t sout_access_out_t;
401

402
typedef struct sout_mux_t sout_mux_t;
403

404
typedef struct sout_stream_t    sout_stream_t;
405

406
typedef struct config_chain_t       config_chain_t;
407
typedef struct session_descriptor_t session_descriptor_t;
408

Sam Hocevar's avatar
 
Sam Hocevar committed
409
/* Decoders */
Laurent Aimar's avatar
Laurent Aimar committed
410 411
typedef struct decoder_t         decoder_t;
typedef struct decoder_synchro_t decoder_synchro_t;
Sam Hocevar's avatar
 
Sam Hocevar committed
412

Gildas Bazin's avatar
 
Gildas Bazin committed
413 414 415
/* Encoders */
typedef struct encoder_t      encoder_t;

416 417 418
/* Filters */
typedef struct filter_t filter_t;

419
/* Network */
420
typedef struct vlc_url_t vlc_url_t;
421

422 423 424
/* Misc */
typedef struct iso639_lang_t iso639_lang_t;

425 426 427 428
/* block */
typedef struct block_t      block_t;
typedef struct block_fifo_t block_fifo_t;

429 430 431
/* Hashing */
typedef struct md5_s md5_t;

Gildas Bazin's avatar
Gildas Bazin committed
432 433 434 435
/* XML */
typedef struct xml_t xml_t;
typedef struct xml_reader_t xml_reader_t;

436 437
/* vod server */
typedef struct vod_t     vod_t;
438
typedef struct vod_media_t vod_media_t;
439

440
/* VLM */
441 442
typedef struct vlm_t         vlm_t;
typedef struct vlm_message_t vlm_message_t;
443

444
/* misc */
445
typedef struct vlc_meta_t    vlc_meta_t;
Clément Stenac's avatar
Clément Stenac committed
446
typedef struct input_stats_t input_stats_t;
447
typedef struct addon_entry_t addon_entry_t;
448

449 450
/* Update */
typedef struct update_t update_t;
451

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

} vlc_value_t;

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

488
/*****************************************************************************
489
 * Variable callbacks: called when the value is modified
490 491 492 493 494 495 496
 *****************************************************************************/
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 */

497 498 499 500 501 502 503 504 505
/*****************************************************************************
 * 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 */

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

517 518 519 520 521
#ifdef __APPLE__
#include <sys/syslimits.h>
#include <AvailabilityMacros.h>
#endif

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

530
#include "vlc_tick.h"
531 532
#include "vlc_threads.h"

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

548 549 550
/* clip v in [min, max] */
#define VLC_CLIP(v, min, max)    __MIN(__MAX((v), (min)), (max))

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

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

572 573 574 575
/**
 * \defgroup bitops Bit operations
 * @{
 */
576

577 578 579 580
#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)
581

582 583 584 585 586
#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); \
587 588
}

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

595 596 597 598 599 600
    while (x)
    {
        x >>= 1;
        i--;
    }
    return i;
601 602
}

603
VLC_USED static inline int vlc_clzl(unsigned long x)
604
{
605
    return vlc_clzll(x) - ((sizeof (long long) - sizeof (long)) * 8);
606 607
}

608
VLC_USED static inline int vlc_clz(unsigned x)
609
{
610
    return vlc_clzll(x) - ((sizeof (long long) - sizeof (int)) * 8);
611 612
}

613
VLC_USED static inline int vlc_ctz_generic(unsigned long long x)
614
{
615
    unsigned i = sizeof (x) * 8;
616

617 618 619 620 621 622
    while (x)
    {
        x <<= 1;
        i--;
    }
    return i;
623
}
624

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

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

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

650 651 652
VLC_INT_FUNC(ctz)
VLC_INT_FUNC(parity)
VLC_INT_FUNC(popcount)
653

654 655 656 657 658 659 660 661 662 663 664 665 666
#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))
667

668 669 670 671 672 673 674 675 676 677 678
/**
 * 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.
 */
679
# define clz(x) \
680
    _Generic((x), \
681 682
        unsigned char: (vlc_clz(x) - (sizeof (unsigned) - 1) * 8), \
        unsigned short: (vlc_clz(x) \
683
        - (sizeof (unsigned) - sizeof (unsigned short)) * 8), \
684 685 686
        unsigned: vlc_clz(x), \
        unsigned long: vlc_clzl(x), \
        unsigned long long: vlc_clzll(x))
687

688 689 690 691 692 693 694 695 696 697
/**
 * 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.
 */
698
# define ctz(x) VLC_INT_GENERIC(vlc_ctz, x)
699

700 701 702 703 704 705 706 707
/**
 * 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)
708

709 710 711 712 713 714 715
/**
 * Bit weight / population count
 *
 * This function counts the number of non-zero bits in an integer.
 *
 * \return The count of non-zero bits.
 */
716
# define vlc_popcount(x) \
717
    _Generic((x), \
718 719 720 721 722 723 724 725
        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);
}
726

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

732 733 734 735 736 737 738 739 740 741
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
742

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

/** Byte swap (32 bits) */
VLC_USED
752
static inline uint32_t vlc_bswap32(uint32_t x)
753
{
754
#if defined (__GNUC__) || defined(__clang__)
755 756 757 758 759 760 761 762 763 764 765
    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
766
static inline uint64_t vlc_bswap64(uint64_t x)
767
{
768
#if defined (__GNUC__) || defined(__clang__)
769
    return __builtin_bswap64 (x);
770
#elif !defined (__cplusplus)
771 772 773 774 775 776 777 778
    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);
779
#else
780 781 782 783 784 785 786 787
    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);
788 789
#endif
}
790
/** @} */
791

792 793 794 795
/**
 * \defgroup overflow Overflowing arithmetic
 * @{
 */
796 797
static inline bool uadd_overflow(unsigned a, unsigned b, unsigned *res)
{
798
#if VLC_GCC_VERSION(5,0) || defined(__clang__)
799 800 801 802 803 804 805 806 807 808
     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)
{
809
#if VLC_GCC_VERSION(5,0) || defined(__clang__)
810 811 812 813 814 815 816 817 818 819
     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)
{
820
#if VLC_GCC_VERSION(5,0) || defined(__clang__)
821 822 823 824 825 826 827 828
     return __builtin_uaddll_overflow(a, b, res);
#else
     *res = a + b;
     return (a + b) < a;
#endif
}

#ifndef __cplusplus
829 830 831 832 833 834 835 836 837 838 839 840 841
/**
 * 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.
 */
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
# 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

866 867 868 869
#if !(VLC_GCC_VERSION(5,0) || defined(__clang__))
# include <limits.h>
#endif

870 871
static inline bool umul_overflow(unsigned a, unsigned b, unsigned *res)
{
872
#if VLC_GCC_VERSION(5,0) || defined(__clang__)
873 874 875 876 877 878 879 880 881 882
     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)
{
883
#if VLC_GCC_VERSION(5,0) || defined(__clang__)
884 885 886 887 888 889 890 891 892 893
     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)
{
894
#if VLC_GCC_VERSION(5,0) || defined(__clang__)
895 896 897 898 899 900 901 902
     return __builtin_umulll_overflow(a, b, res);
#else
     *res = a * b;
     return b > 0 && a > (ULLONG_MAX / b);
#endif
}

#ifndef __cplusplus
903 904 905 906 907 908 909 910 911 912 913 914 915
/**
 * 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.
 */
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
#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
939 940
/** @} */
/** @} */
941

942
/* Free and set set the variable to NULL */
943
#define FREENULL(a) do { free( a ); a = NULL; } while(0)
944

945 946
#define EMPTY_STR(str) (!str || !*str)

947
#include <vlc_arrays.h>
948

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

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

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

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

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

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

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

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

995 996 997 998 999
#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 */
1000
VLC_USED
1001
static inline uint16_t GetWLE (const void *p)
1002
{
1003 1004 1005 1006
    uint16_t x;

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

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

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

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

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

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

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

/** Writes 64 bits in network byte order */
1053
static inline void SetQWBE (void *p, uint64_t qw)
1054
{
1055 1056
    qw = hton64 (qw);
    memcpy (p, &qw, sizeof (qw));
1057 1058
}

1059
/** Writes 16 bits in little endian order */
1060
static inline void SetWLE (void *p, uint16_t w)
1061
{
1062
#ifdef WORDS_BIGENDIAN
1063
    w = vlc_bswap16 (w);
1064 1065
#endif
    memcpy (p, &w, sizeof (w));
1066
}
1067 1068

/** Writes 32 bits in little endian order */
1069
static inline void SetDWLE (void *p, uint32_t dw)
1070
{
1071
#ifdef WORDS_BIGENDIAN
1072
    dw = vlc_bswap32 (dw);
1073 1074
#endif
    memcpy (p, &dw, sizeof (dw));
1075
}
1076

1077
/** Writes 64 bits in little endian order */
1078
static inline void SetQWLE (void *p, uint64_t qw)
1079
{
1080
#ifdef WORDS_BIGENDIAN
1081
    qw = vlc_bswap64 (qw);
1082 1083
#endif
    memcpy (p, &qw, sizeof (qw));
1084
}
Sam Hocevar's avatar
 
Sam Hocevar committed
1085

1086 1087 1088
/* */
#define VLC_UNUSED(x) (void)(x)

1089
/* Stuff defined in src/extras/libc.c */
1090

1091
#if defined(_WIN32)
Sam Hocevar's avatar
 
Sam Hocevar committed
1092 1093 1094
/* several type definitions */
#   if defined( __MINGW32__ )
#       if !defined( _OFF_T_ )
1095 1096
            typedef long long _off_t;
            typedef _off_t off_t;
Sam Hocevar's avatar
 
Sam Hocevar committed
1097 1098
#           define _OFF_T_
#       else
Gildas Bazin's avatar
 
Gildas Bazin committed
1099 1100 1101
#           ifdef off_t
#               undef off_t
#           endif
Sam Hocevar's avatar
 
Sam Hocevar committed
1102 1103 1104 1105
#           define off_t long long
#       endif
#   endif

Gildas Bazin's avatar
 
Gildas Bazin committed
1106 1107
#   ifndef O_NONBLOCK
#       define O_NONBLOCK 0
Gildas Bazin's avatar
 
Gildas Bazin committed
1108
#   endif
1109 1110 1111 1112 1113

/* the mingw32 swab() and win32 _swab() prototypes expect a char* instead of a
   const void* */
#  define swab(a,b,c)  swab((char*) (a), (char*) (b), (c))

1114
#endif /* _WIN32 */
Sam Hocevar's avatar
 
Sam Hocevar committed
1115

1116 1117 1118 1119
typedef struct {
    unsigned num, den;
} vlc_rational_t;

1120
VLC_API bool vlc_ureduce( unsigned *, unsigned *, uint64_t, uint64_t, uint64_t );
1121

1122 1123 1124
#define container_of(ptr, type, member) \
    ((type *)(((char *)(ptr)) - offsetof(type, member)))

1125 1126 1127
VLC_USED VLC_MALLOC
static inline void *vlc_alloc(size_t count, size_t size)
{
1128
    return mul_overflow(count, size, &size) ? NULL : malloc(size);
1129 1130
}

1131 1132 1133 1134 1135 1136
VLC_USED
static inline void *vlc_reallocarray(void *ptr, size_t count, size_t size)
{
    return mul_overflow(count, size, &size) ? NULL : realloc(ptr, size);
}

Sam Hocevar's avatar
 
Sam Hocevar committed
1137 1138 1139
/*****************************************************************************
 * I18n stuff
 *****************************************************************************/
1140 1141 1142
VLC_API const char *vlc_gettext(const char *msgid) VLC_FORMAT_ARG(1);
VLC_API const char *vlc_ngettext(const char *s, const char *p, unsigned long n)
VLC_FORMAT_ARG(1) VLC_FORMAT_ARG(2);
1143

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1144 1145 1146
#define vlc_pgettext( ctx, id ) \
        vlc_pgettext_aux( ctx "\004" id, id )

1147
VLC_FORMAT_ARG(2)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1148
static inline const char *vlc_pgettext_aux( const char *ctx, const char *id )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1149
{
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1150
    const char *tr = vlc_gettext( ctx );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1151 1152 1153
    return (tr == ctx) ? id : tr;
}

1154 1155 1156
/*****************************************************************************
 * Loosy memory allocation functions. Do not use in new code.
 *****************************************************************************/
1157
static inline void *xmalloc(size_t len)
1158
{
1159 1160 1161
    void *ptr = malloc(len);
    if (unlikely(ptr == NULL && len > 0))
        abort();
1162 1163 1164
    return ptr;
}