diff --git a/CMakeLists.txt b/CMakeLists.txt index 5d8e44f2..457c03da 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -172,7 +172,7 @@ else() list(APPEND STRICT_OPTIONS_CPP "-Wno-error=unknown-warning-option" "-Qunused-arguments" "-Wno-tautological-compare" "-Wno-unused-function" "-Wno-array-bounds") endif() if(ENABLE_STRICT) - list(APPEND STRICT_OPTIONS_CPP "-Werror" "-Wextra" "-Wno-unused-parameter" "-Wno-missing-field-initializers" "-fno-strict-aliasing") + list(APPEND STRICT_OPTIONS_CPP "-Werror" "-Wextra" "-Wunused-parameter" "-Wno-missing-field-initializers" "-fno-strict-aliasing") endif() endif() if(STRICT_OPTIONS_CPP) diff --git a/build/android/ortp_AndroidConfig.h b/build/android/ortp_AndroidConfig.h index abbe98d7..a1421c82 100644 --- a/build/android/ortp_AndroidConfig.h +++ b/build/android/ortp_AndroidConfig.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify diff --git a/build/wp8/oRTP/inttypes.h b/build/wp8/oRTP/inttypes.h index 4b3828a2..da259a25 100644 --- a/build/wp8/oRTP/inttypes.h +++ b/build/wp8/oRTP/inttypes.h @@ -1,32 +1,32 @@ // ISO C9x compliant inttypes.h for Microsoft Visual Studio -// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 -// +// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 +// // Copyright (c) 2006 Alexander Chemeris -// +// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: -// +// // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. -// +// // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. -// +// // 3. The name of the author may be used to endorse or promote products // derived from this software without specific prior written permission. -// +// // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// +// /////////////////////////////////////////////////////////////////////////////// #ifndef _MSC_VER // [ @@ -45,8 +45,8 @@ // 7.8 Format conversion of integer types typedef struct { - intmax_t quot; - intmax_t rem; + intmax_t quot; + intmax_t rem; } imaxdiv_t; // 7.8.1 Macros for format specifiers @@ -54,212 +54,212 @@ typedef struct { #if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 // The fprintf macros for signed integers are: -#define PRId8 "d" -#define PRIi8 "i" -#define PRIdLEAST8 "d" -#define PRIiLEAST8 "i" -#define PRIdFAST8 "d" -#define PRIiFAST8 "i" - -#define PRId16 "hd" -#define PRIi16 "hi" -#define PRIdLEAST16 "hd" -#define PRIiLEAST16 "hi" -#define PRIdFAST16 "hd" -#define PRIiFAST16 "hi" - -#define PRId32 "I32d" -#define PRIi32 "I32i" -#define PRIdLEAST32 "I32d" -#define PRIiLEAST32 "I32i" -#define PRIdFAST32 "I32d" -#define PRIiFAST32 "I32i" - -#define PRId64 "I64d" -#define PRIi64 "I64i" -#define PRIdLEAST64 "I64d" -#define PRIiLEAST64 "I64i" -#define PRIdFAST64 "I64d" -#define PRIiFAST64 "I64i" - -#define PRIdMAX "I64d" -#define PRIiMAX "I64i" - -#define PRIdPTR "Id" -#define PRIiPTR "Ii" +#define PRId8 "d" +#define PRIi8 "i" +#define PRIdLEAST8 "d" +#define PRIiLEAST8 "i" +#define PRIdFAST8 "d" +#define PRIiFAST8 "i" + +#define PRId16 "hd" +#define PRIi16 "hi" +#define PRIdLEAST16 "hd" +#define PRIiLEAST16 "hi" +#define PRIdFAST16 "hd" +#define PRIiFAST16 "hi" + +#define PRId32 "I32d" +#define PRIi32 "I32i" +#define PRIdLEAST32 "I32d" +#define PRIiLEAST32 "I32i" +#define PRIdFAST32 "I32d" +#define PRIiFAST32 "I32i" + +#define PRId64 "I64d" +#define PRIi64 "I64i" +#define PRIdLEAST64 "I64d" +#define PRIiLEAST64 "I64i" +#define PRIdFAST64 "I64d" +#define PRIiFAST64 "I64i" + +#define PRIdMAX "I64d" +#define PRIiMAX "I64i" + +#define PRIdPTR "Id" +#define PRIiPTR "Ii" // The fprintf macros for unsigned integers are: -#define PRIo8 "o" -#define PRIu8 "u" -#define PRIx8 "x" -#define PRIX8 "X" -#define PRIoLEAST8 "o" -#define PRIuLEAST8 "u" -#define PRIxLEAST8 "x" -#define PRIXLEAST8 "X" -#define PRIoFAST8 "o" -#define PRIuFAST8 "u" -#define PRIxFAST8 "x" -#define PRIXFAST8 "X" - -#define PRIo16 "ho" -#define PRIu16 "hu" -#define PRIx16 "hx" -#define PRIX16 "hX" -#define PRIoLEAST16 "ho" -#define PRIuLEAST16 "hu" -#define PRIxLEAST16 "hx" -#define PRIXLEAST16 "hX" -#define PRIoFAST16 "ho" -#define PRIuFAST16 "hu" -#define PRIxFAST16 "hx" -#define PRIXFAST16 "hX" - -#define PRIo32 "I32o" -#define PRIu32 "I32u" -#define PRIx32 "I32x" -#define PRIX32 "I32X" -#define PRIoLEAST32 "I32o" -#define PRIuLEAST32 "I32u" -#define PRIxLEAST32 "I32x" -#define PRIXLEAST32 "I32X" -#define PRIoFAST32 "I32o" -#define PRIuFAST32 "I32u" -#define PRIxFAST32 "I32x" -#define PRIXFAST32 "I32X" - -#define PRIo64 "I64o" -#define PRIu64 "I64u" -#define PRIx64 "I64x" -#define PRIX64 "I64X" -#define PRIoLEAST64 "I64o" -#define PRIuLEAST64 "I64u" -#define PRIxLEAST64 "I64x" -#define PRIXLEAST64 "I64X" -#define PRIoFAST64 "I64o" -#define PRIuFAST64 "I64u" -#define PRIxFAST64 "I64x" -#define PRIXFAST64 "I64X" - -#define PRIoMAX "I64o" -#define PRIuMAX "I64u" -#define PRIxMAX "I64x" -#define PRIXMAX "I64X" - -#define PRIoPTR "Io" -#define PRIuPTR "Iu" -#define PRIxPTR "Ix" -#define PRIXPTR "IX" +#define PRIo8 "o" +#define PRIu8 "u" +#define PRIx8 "x" +#define PRIX8 "X" +#define PRIoLEAST8 "o" +#define PRIuLEAST8 "u" +#define PRIxLEAST8 "x" +#define PRIXLEAST8 "X" +#define PRIoFAST8 "o" +#define PRIuFAST8 "u" +#define PRIxFAST8 "x" +#define PRIXFAST8 "X" + +#define PRIo16 "ho" +#define PRIu16 "hu" +#define PRIx16 "hx" +#define PRIX16 "hX" +#define PRIoLEAST16 "ho" +#define PRIuLEAST16 "hu" +#define PRIxLEAST16 "hx" +#define PRIXLEAST16 "hX" +#define PRIoFAST16 "ho" +#define PRIuFAST16 "hu" +#define PRIxFAST16 "hx" +#define PRIXFAST16 "hX" + +#define PRIo32 "I32o" +#define PRIu32 "I32u" +#define PRIx32 "I32x" +#define PRIX32 "I32X" +#define PRIoLEAST32 "I32o" +#define PRIuLEAST32 "I32u" +#define PRIxLEAST32 "I32x" +#define PRIXLEAST32 "I32X" +#define PRIoFAST32 "I32o" +#define PRIuFAST32 "I32u" +#define PRIxFAST32 "I32x" +#define PRIXFAST32 "I32X" + +#define PRIo64 "I64o" +#define PRIu64 "I64u" +#define PRIx64 "I64x" +#define PRIX64 "I64X" +#define PRIoLEAST64 "I64o" +#define PRIuLEAST64 "I64u" +#define PRIxLEAST64 "I64x" +#define PRIXLEAST64 "I64X" +#define PRIoFAST64 "I64o" +#define PRIuFAST64 "I64u" +#define PRIxFAST64 "I64x" +#define PRIXFAST64 "I64X" + +#define PRIoMAX "I64o" +#define PRIuMAX "I64u" +#define PRIxMAX "I64x" +#define PRIXMAX "I64X" + +#define PRIoPTR "Io" +#define PRIuPTR "Iu" +#define PRIxPTR "Ix" +#define PRIXPTR "IX" // The fscanf macros for signed integers are: -#define SCNd8 "d" -#define SCNi8 "i" -#define SCNdLEAST8 "d" -#define SCNiLEAST8 "i" -#define SCNdFAST8 "d" -#define SCNiFAST8 "i" - -#define SCNd16 "hd" -#define SCNi16 "hi" -#define SCNdLEAST16 "hd" -#define SCNiLEAST16 "hi" -#define SCNdFAST16 "hd" -#define SCNiFAST16 "hi" - -#define SCNd32 "ld" -#define SCNi32 "li" -#define SCNdLEAST32 "ld" -#define SCNiLEAST32 "li" -#define SCNdFAST32 "ld" -#define SCNiFAST32 "li" - -#define SCNd64 "I64d" -#define SCNi64 "I64i" -#define SCNdLEAST64 "I64d" -#define SCNiLEAST64 "I64i" -#define SCNdFAST64 "I64d" -#define SCNiFAST64 "I64i" - -#define SCNdMAX "I64d" -#define SCNiMAX "I64i" +#define SCNd8 "d" +#define SCNi8 "i" +#define SCNdLEAST8 "d" +#define SCNiLEAST8 "i" +#define SCNdFAST8 "d" +#define SCNiFAST8 "i" + +#define SCNd16 "hd" +#define SCNi16 "hi" +#define SCNdLEAST16 "hd" +#define SCNiLEAST16 "hi" +#define SCNdFAST16 "hd" +#define SCNiFAST16 "hi" + +#define SCNd32 "ld" +#define SCNi32 "li" +#define SCNdLEAST32 "ld" +#define SCNiLEAST32 "li" +#define SCNdFAST32 "ld" +#define SCNiFAST32 "li" + +#define SCNd64 "I64d" +#define SCNi64 "I64i" +#define SCNdLEAST64 "I64d" +#define SCNiLEAST64 "I64i" +#define SCNdFAST64 "I64d" +#define SCNiFAST64 "I64i" + +#define SCNdMAX "I64d" +#define SCNiMAX "I64i" #ifdef _WIN64 // [ -# define SCNdPTR "I64d" -# define SCNiPTR "I64i" -#else // _WIN64 ][ -# define SCNdPTR "ld" -# define SCNiPTR "li" -#endif // _WIN64 ] +#define SCNdPTR "I64d" +#define SCNiPTR "I64i" +#else // _WIN64 ][ +#define SCNdPTR "ld" +#define SCNiPTR "li" +#endif // _WIN64 ] // The fscanf macros for unsigned integers are: -#define SCNo8 "o" -#define SCNu8 "u" -#define SCNx8 "x" -#define SCNX8 "X" -#define SCNoLEAST8 "o" -#define SCNuLEAST8 "u" -#define SCNxLEAST8 "x" -#define SCNXLEAST8 "X" -#define SCNoFAST8 "o" -#define SCNuFAST8 "u" -#define SCNxFAST8 "x" -#define SCNXFAST8 "X" - -#define SCNo16 "ho" -#define SCNu16 "hu" -#define SCNx16 "hx" -#define SCNX16 "hX" -#define SCNoLEAST16 "ho" -#define SCNuLEAST16 "hu" -#define SCNxLEAST16 "hx" -#define SCNXLEAST16 "hX" -#define SCNoFAST16 "ho" -#define SCNuFAST16 "hu" -#define SCNxFAST16 "hx" -#define SCNXFAST16 "hX" - -#define SCNo32 "lo" -#define SCNu32 "lu" -#define SCNx32 "lx" -#define SCNX32 "lX" -#define SCNoLEAST32 "lo" -#define SCNuLEAST32 "lu" -#define SCNxLEAST32 "lx" -#define SCNXLEAST32 "lX" -#define SCNoFAST32 "lo" -#define SCNuFAST32 "lu" -#define SCNxFAST32 "lx" -#define SCNXFAST32 "lX" - -#define SCNo64 "I64o" -#define SCNu64 "I64u" -#define SCNx64 "I64x" -#define SCNX64 "I64X" -#define SCNoLEAST64 "I64o" -#define SCNuLEAST64 "I64u" -#define SCNxLEAST64 "I64x" -#define SCNXLEAST64 "I64X" -#define SCNoFAST64 "I64o" -#define SCNuFAST64 "I64u" -#define SCNxFAST64 "I64x" -#define SCNXFAST64 "I64X" - -#define SCNoMAX "I64o" -#define SCNuMAX "I64u" -#define SCNxMAX "I64x" -#define SCNXMAX "I64X" +#define SCNo8 "o" +#define SCNu8 "u" +#define SCNx8 "x" +#define SCNX8 "X" +#define SCNoLEAST8 "o" +#define SCNuLEAST8 "u" +#define SCNxLEAST8 "x" +#define SCNXLEAST8 "X" +#define SCNoFAST8 "o" +#define SCNuFAST8 "u" +#define SCNxFAST8 "x" +#define SCNXFAST8 "X" + +#define SCNo16 "ho" +#define SCNu16 "hu" +#define SCNx16 "hx" +#define SCNX16 "hX" +#define SCNoLEAST16 "ho" +#define SCNuLEAST16 "hu" +#define SCNxLEAST16 "hx" +#define SCNXLEAST16 "hX" +#define SCNoFAST16 "ho" +#define SCNuFAST16 "hu" +#define SCNxFAST16 "hx" +#define SCNXFAST16 "hX" + +#define SCNo32 "lo" +#define SCNu32 "lu" +#define SCNx32 "lx" +#define SCNX32 "lX" +#define SCNoLEAST32 "lo" +#define SCNuLEAST32 "lu" +#define SCNxLEAST32 "lx" +#define SCNXLEAST32 "lX" +#define SCNoFAST32 "lo" +#define SCNuFAST32 "lu" +#define SCNxFAST32 "lx" +#define SCNXFAST32 "lX" + +#define SCNo64 "I64o" +#define SCNu64 "I64u" +#define SCNx64 "I64x" +#define SCNX64 "I64X" +#define SCNoLEAST64 "I64o" +#define SCNuLEAST64 "I64u" +#define SCNxLEAST64 "I64x" +#define SCNXLEAST64 "I64X" +#define SCNoFAST64 "I64o" +#define SCNuFAST64 "I64u" +#define SCNxFAST64 "I64x" +#define SCNXFAST64 "I64X" + +#define SCNoMAX "I64o" +#define SCNuMAX "I64u" +#define SCNxMAX "I64x" +#define SCNXMAX "I64X" #ifdef _WIN64 // [ -# define SCNoPTR "I64o" -# define SCNuPTR "I64u" -# define SCNxPTR "I64x" -# define SCNXPTR "I64X" -#else // _WIN64 ][ -# define SCNoPTR "lo" -# define SCNuPTR "lu" -# define SCNxPTR "lx" -# define SCNXPTR "lX" -#endif // _WIN64 ] +#define SCNoPTR "I64o" +#define SCNuPTR "I64u" +#define SCNxPTR "I64x" +#define SCNXPTR "I64X" +#else // _WIN64 ][ +#define SCNoPTR "lo" +#define SCNuPTR "lu" +#define SCNxPTR "lx" +#define SCNXPTR "lX" +#endif // _WIN64 ] #endif // __STDC_FORMAT_MACROS ] @@ -274,23 +274,22 @@ typedef struct { // in %MSVC.NET%\crt\src\div.c #ifdef STATIC_IMAXDIV // [ static -#else // STATIC_IMAXDIV ][ +#else // STATIC_IMAXDIV ][ _inline #endif // STATIC_IMAXDIV ] -imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) -{ - imaxdiv_t result; + imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) { + imaxdiv_t result; - result.quot = numer / denom; - result.rem = numer % denom; + result.quot = numer / denom; + result.rem = numer % denom; - if (numer < 0 && result.rem > 0) { - // did division wrong; must fix up - ++result.quot; - result.rem -= denom; - } + if (numer < 0 && result.rem > 0) { + // did division wrong; must fix up + ++result.quot; + result.rem -= denom; + } - return result; + return result; } // 7.8.2.3 The strtoimax and strtoumax functions @@ -301,5 +300,4 @@ imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) #define wcstoimax _wcstoi64 #define wcstoumax _wcstoui64 - #endif // _MSC_INTTYPES_H_ ] diff --git a/build/wp8/oRTP/stdint.h b/build/wp8/oRTP/stdint.h index d02608a5..285b9269 100644 --- a/build/wp8/oRTP/stdint.h +++ b/build/wp8/oRTP/stdint.h @@ -1,32 +1,32 @@ // ISO C9x compliant stdint.h for Microsoft Visual Studio -// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 -// +// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 +// // Copyright (c) 2006-2008 Alexander Chemeris -// +// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: -// +// // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. -// +// // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. -// +// // 3. The name of the author may be used to endorse or promote products // derived from this software without specific prior written permission. -// +// // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// +// /////////////////////////////////////////////////////////////////////////////// #ifndef _MSC_VER // [ @@ -49,20 +49,19 @@ #ifdef __cplusplus extern "C" { #endif -# include +#include #ifdef __cplusplus } #endif // Define _W64 macros to mark types changing their size, like intptr_t. #ifndef _W64 -# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 -# define _W64 __w64 -# else -# define _W64 -# endif +#if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 +#define _W64 __w64 +#else +#define _W64 +#endif #endif - // 7.18.1 Integer types @@ -72,176 +71,173 @@ extern "C" { // realize that, e.g. char has the same size as __int8 // so we give up on __intX for them. #if (_MSC_VER < 1300) - typedef signed char int8_t; - typedef signed short int16_t; - typedef signed int int32_t; - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned int uint32_t; +typedef signed char int8_t; +typedef signed short int16_t; +typedef signed int int32_t; +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; +typedef unsigned int uint32_t; #else - typedef signed __int8 int8_t; - typedef signed __int16 int16_t; - typedef signed __int32 int32_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; +typedef signed __int8 int8_t; +typedef signed __int16 int16_t; +typedef signed __int32 int32_t; +typedef unsigned __int8 uint8_t; +typedef unsigned __int16 uint16_t; +typedef unsigned __int32 uint32_t; #endif -typedef signed __int64 int64_t; -typedef unsigned __int64 uint64_t; - +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; // 7.18.1.2 Minimum-width integer types -typedef int8_t int_least8_t; -typedef int16_t int_least16_t; -typedef int32_t int_least32_t; -typedef int64_t int_least64_t; -typedef uint8_t uint_least8_t; -typedef uint16_t uint_least16_t; -typedef uint32_t uint_least32_t; -typedef uint64_t uint_least64_t; +typedef int8_t int_least8_t; +typedef int16_t int_least16_t; +typedef int32_t int_least32_t; +typedef int64_t int_least64_t; +typedef uint8_t uint_least8_t; +typedef uint16_t uint_least16_t; +typedef uint32_t uint_least32_t; +typedef uint64_t uint_least64_t; // 7.18.1.3 Fastest minimum-width integer types -typedef int8_t int_fast8_t; -typedef int16_t int_fast16_t; -typedef int32_t int_fast32_t; -typedef int64_t int_fast64_t; -typedef uint8_t uint_fast8_t; -typedef uint16_t uint_fast16_t; -typedef uint32_t uint_fast32_t; -typedef uint64_t uint_fast64_t; +typedef int8_t int_fast8_t; +typedef int16_t int_fast16_t; +typedef int32_t int_fast32_t; +typedef int64_t int_fast64_t; +typedef uint8_t uint_fast8_t; +typedef uint16_t uint_fast16_t; +typedef uint32_t uint_fast32_t; +typedef uint64_t uint_fast64_t; // 7.18.1.4 Integer types capable of holding object pointers #ifdef _WIN64 // [ - typedef signed __int64 intptr_t; - typedef unsigned __int64 uintptr_t; -#else // _WIN64 ][ - typedef _W64 signed int intptr_t; - typedef _W64 unsigned int uintptr_t; +typedef signed __int64 intptr_t; +typedef unsigned __int64 uintptr_t; +#else // _WIN64 ][ +typedef _W64 signed int intptr_t; +typedef _W64 unsigned int uintptr_t; #endif // _WIN64 ] // 7.18.1.5 Greatest-width integer types -typedef int64_t intmax_t; -typedef uint64_t uintmax_t; - +typedef int64_t intmax_t; +typedef uint64_t uintmax_t; // 7.18.2 Limits of specified-width integer types -#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 +#if !defined(__cplusplus) || \ + defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 // 7.18.2.1 Limits of exact-width integer types -#define INT8_MIN ((int8_t)_I8_MIN) -#define INT8_MAX _I8_MAX -#define INT16_MIN ((int16_t)_I16_MIN) -#define INT16_MAX _I16_MAX -#define INT32_MIN ((int32_t)_I32_MIN) -#define INT32_MAX _I32_MAX -#define INT64_MIN ((int64_t)_I64_MIN) -#define INT64_MAX _I64_MAX -#define UINT8_MAX _UI8_MAX -#define UINT16_MAX _UI16_MAX -#define UINT32_MAX _UI32_MAX -#define UINT64_MAX _UI64_MAX +#define INT8_MIN ((int8_t)_I8_MIN) +#define INT8_MAX _I8_MAX +#define INT16_MIN ((int16_t)_I16_MIN) +#define INT16_MAX _I16_MAX +#define INT32_MIN ((int32_t)_I32_MIN) +#define INT32_MAX _I32_MAX +#define INT64_MIN ((int64_t)_I64_MIN) +#define INT64_MAX _I64_MAX +#define UINT8_MAX _UI8_MAX +#define UINT16_MAX _UI16_MAX +#define UINT32_MAX _UI32_MAX +#define UINT64_MAX _UI64_MAX // 7.18.2.2 Limits of minimum-width integer types -#define INT_LEAST8_MIN INT8_MIN -#define INT_LEAST8_MAX INT8_MAX -#define INT_LEAST16_MIN INT16_MIN -#define INT_LEAST16_MAX INT16_MAX -#define INT_LEAST32_MIN INT32_MIN -#define INT_LEAST32_MAX INT32_MAX -#define INT_LEAST64_MIN INT64_MIN -#define INT_LEAST64_MAX INT64_MAX -#define UINT_LEAST8_MAX UINT8_MAX -#define UINT_LEAST16_MAX UINT16_MAX -#define UINT_LEAST32_MAX UINT32_MAX -#define UINT_LEAST64_MAX UINT64_MAX +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST8_MAX INT8_MAX +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST16_MAX INT16_MAX +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST32_MAX INT32_MAX +#define INT_LEAST64_MIN INT64_MIN +#define INT_LEAST64_MAX INT64_MAX +#define UINT_LEAST8_MAX UINT8_MAX +#define UINT_LEAST16_MAX UINT16_MAX +#define UINT_LEAST32_MAX UINT32_MAX +#define UINT_LEAST64_MAX UINT64_MAX // 7.18.2.3 Limits of fastest minimum-width integer types -#define INT_FAST8_MIN INT8_MIN -#define INT_FAST8_MAX INT8_MAX -#define INT_FAST16_MIN INT16_MIN -#define INT_FAST16_MAX INT16_MAX -#define INT_FAST32_MIN INT32_MIN -#define INT_FAST32_MAX INT32_MAX -#define INT_FAST64_MIN INT64_MIN -#define INT_FAST64_MAX INT64_MAX -#define UINT_FAST8_MAX UINT8_MAX -#define UINT_FAST16_MAX UINT16_MAX -#define UINT_FAST32_MAX UINT32_MAX -#define UINT_FAST64_MAX UINT64_MAX +#define INT_FAST8_MIN INT8_MIN +#define INT_FAST8_MAX INT8_MAX +#define INT_FAST16_MIN INT16_MIN +#define INT_FAST16_MAX INT16_MAX +#define INT_FAST32_MIN INT32_MIN +#define INT_FAST32_MAX INT32_MAX +#define INT_FAST64_MIN INT64_MIN +#define INT_FAST64_MAX INT64_MAX +#define UINT_FAST8_MAX UINT8_MAX +#define UINT_FAST16_MAX UINT16_MAX +#define UINT_FAST32_MAX UINT32_MAX +#define UINT_FAST64_MAX UINT64_MAX // 7.18.2.4 Limits of integer types capable of holding object pointers #ifdef _WIN64 // [ -# define INTPTR_MIN INT64_MIN -# define INTPTR_MAX INT64_MAX -# define UINTPTR_MAX UINT64_MAX +#define INTPTR_MIN INT64_MIN +#define INTPTR_MAX INT64_MAX +#define UINTPTR_MAX UINT64_MAX #else // _WIN64 ][ -# define INTPTR_MIN INT32_MIN -# define INTPTR_MAX INT32_MAX -# define UINTPTR_MAX UINT32_MAX +#define INTPTR_MIN INT32_MIN +#define INTPTR_MAX INT32_MAX +#define UINTPTR_MAX UINT32_MAX #endif // _WIN64 ] // 7.18.2.5 Limits of greatest-width integer types -#define INTMAX_MIN INT64_MIN -#define INTMAX_MAX INT64_MAX -#define UINTMAX_MAX UINT64_MAX +#define INTMAX_MIN INT64_MIN +#define INTMAX_MAX INT64_MAX +#define UINTMAX_MAX UINT64_MAX // 7.18.3 Limits of other integer types #ifdef _WIN64 // [ -# define PTRDIFF_MIN _I64_MIN -# define PTRDIFF_MAX _I64_MAX -#else // _WIN64 ][ -# define PTRDIFF_MIN _I32_MIN -# define PTRDIFF_MAX _I32_MAX -#endif // _WIN64 ] +#define PTRDIFF_MIN _I64_MIN +#define PTRDIFF_MAX _I64_MAX +#else // _WIN64 ][ +#define PTRDIFF_MIN _I32_MIN +#define PTRDIFF_MAX _I32_MAX +#endif // _WIN64 ] -#define SIG_ATOMIC_MIN INT_MIN -#define SIG_ATOMIC_MAX INT_MAX +#define SIG_ATOMIC_MIN INT_MIN +#define SIG_ATOMIC_MAX INT_MAX #ifndef SIZE_MAX // [ -# ifdef _WIN64 // [ -# define SIZE_MAX _UI64_MAX -# else // _WIN64 ][ -# define SIZE_MAX _UI32_MAX -# endif // _WIN64 ] +#ifdef _WIN64 // [ +#define SIZE_MAX _UI64_MAX +#else // _WIN64 ][ +#define SIZE_MAX _UI32_MAX +#endif // _WIN64 ] #endif // SIZE_MAX ] // WCHAR_MIN and WCHAR_MAX are also defined in #ifndef WCHAR_MIN // [ -# define WCHAR_MIN 0 -#endif // WCHAR_MIN ] +#define WCHAR_MIN 0 +#endif // WCHAR_MIN ] #ifndef WCHAR_MAX // [ -# define WCHAR_MAX _UI16_MAX -#endif // WCHAR_MAX ] +#define WCHAR_MAX _UI16_MAX +#endif // WCHAR_MAX ] -#define WINT_MIN 0 -#define WINT_MAX _UI16_MAX +#define WINT_MIN 0 +#define WINT_MAX _UI16_MAX #endif // __STDC_LIMIT_MACROS ] - // 7.18.4 Limits of other integer types #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 // 7.18.4.1 Macros for minimum-width integer constants -#define INT8_C(val) val##i8 +#define INT8_C(val) val##i8 #define INT16_C(val) val##i16 #define INT32_C(val) val##i32 #define INT64_C(val) val##i64 -#define UINT8_C(val) val##ui8 +#define UINT8_C(val) val##ui8 #define UINT16_C(val) val##ui16 #define UINT32_C(val) val##ui32 #define UINT64_C(val) val##ui64 // 7.18.4.2 Macros for greatest-width integer constants -#define INTMAX_C INT64_C -#define UINTMAX_C UINT64_C +#define INTMAX_C INT64_C +#define UINTMAX_C UINT64_C #endif // __STDC_CONSTANT_MACROS ] - #endif // _MSC_STDINT_H_ ] diff --git a/configure.ac b/configure.ac index 3f5f53c8..e4ad36bc 100644 --- a/configure.ac +++ b/configure.ac @@ -82,7 +82,7 @@ case "$target_os" in esac if test "$strictness" = "yes" ; then - STRICT_OPTIONS="$STRICT_OPTIONS -Werror -Wextra -Wno-unused-parameter -Wno-missing-field-initializers" + STRICT_OPTIONS="$STRICT_OPTIONS -Werror -Wextra -Wunused-parameter -Wno-missing-field-initializers" CFLAGS="$CFLAGS -fno-strict-aliasing" fi diff --git a/include/MSVC/inttypes.h b/include/MSVC/inttypes.h index 60e8c89c..fcbee54d 100644 --- a/include/MSVC/inttypes.h +++ b/include/MSVC/inttypes.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,34 +18,34 @@ * along with this program. If not, see . */ // ISO C9x compliant inttypes.h for Microsoft Visual Studio -// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 -// +// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 +// // Copyright (c) 2006 Alexander Chemeris -// +// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: -// +// // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. -// +// // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. -// +// // 3. The name of the author may be used to endorse or promote products // derived from this software without specific prior written permission. -// +// // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// +// /////////////////////////////////////////////////////////////////////////////// #ifndef _MSC_VER // [ @@ -64,8 +64,8 @@ // 7.8 Format conversion of integer types typedef struct { - intmax_t quot; - intmax_t rem; + intmax_t quot; + intmax_t rem; } imaxdiv_t; // 7.8.1 Macros for format specifiers @@ -73,212 +73,212 @@ typedef struct { #if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 // The fprintf macros for signed integers are: -#define PRId8 "d" -#define PRIi8 "i" -#define PRIdLEAST8 "d" -#define PRIiLEAST8 "i" -#define PRIdFAST8 "d" -#define PRIiFAST8 "i" - -#define PRId16 "hd" -#define PRIi16 "hi" -#define PRIdLEAST16 "hd" -#define PRIiLEAST16 "hi" -#define PRIdFAST16 "hd" -#define PRIiFAST16 "hi" - -#define PRId32 "I32d" -#define PRIi32 "I32i" -#define PRIdLEAST32 "I32d" -#define PRIiLEAST32 "I32i" -#define PRIdFAST32 "I32d" -#define PRIiFAST32 "I32i" - -#define PRId64 "I64d" -#define PRIi64 "I64i" -#define PRIdLEAST64 "I64d" -#define PRIiLEAST64 "I64i" -#define PRIdFAST64 "I64d" -#define PRIiFAST64 "I64i" - -#define PRIdMAX "I64d" -#define PRIiMAX "I64i" - -#define PRIdPTR "Id" -#define PRIiPTR "Ii" +#define PRId8 "d" +#define PRIi8 "i" +#define PRIdLEAST8 "d" +#define PRIiLEAST8 "i" +#define PRIdFAST8 "d" +#define PRIiFAST8 "i" + +#define PRId16 "hd" +#define PRIi16 "hi" +#define PRIdLEAST16 "hd" +#define PRIiLEAST16 "hi" +#define PRIdFAST16 "hd" +#define PRIiFAST16 "hi" + +#define PRId32 "I32d" +#define PRIi32 "I32i" +#define PRIdLEAST32 "I32d" +#define PRIiLEAST32 "I32i" +#define PRIdFAST32 "I32d" +#define PRIiFAST32 "I32i" + +#define PRId64 "I64d" +#define PRIi64 "I64i" +#define PRIdLEAST64 "I64d" +#define PRIiLEAST64 "I64i" +#define PRIdFAST64 "I64d" +#define PRIiFAST64 "I64i" + +#define PRIdMAX "I64d" +#define PRIiMAX "I64i" + +#define PRIdPTR "Id" +#define PRIiPTR "Ii" // The fprintf macros for unsigned integers are: -#define PRIo8 "o" -#define PRIu8 "u" -#define PRIx8 "x" -#define PRIX8 "X" -#define PRIoLEAST8 "o" -#define PRIuLEAST8 "u" -#define PRIxLEAST8 "x" -#define PRIXLEAST8 "X" -#define PRIoFAST8 "o" -#define PRIuFAST8 "u" -#define PRIxFAST8 "x" -#define PRIXFAST8 "X" - -#define PRIo16 "ho" -#define PRIu16 "hu" -#define PRIx16 "hx" -#define PRIX16 "hX" -#define PRIoLEAST16 "ho" -#define PRIuLEAST16 "hu" -#define PRIxLEAST16 "hx" -#define PRIXLEAST16 "hX" -#define PRIoFAST16 "ho" -#define PRIuFAST16 "hu" -#define PRIxFAST16 "hx" -#define PRIXFAST16 "hX" - -#define PRIo32 "I32o" -#define PRIu32 "I32u" -#define PRIx32 "I32x" -#define PRIX32 "I32X" -#define PRIoLEAST32 "I32o" -#define PRIuLEAST32 "I32u" -#define PRIxLEAST32 "I32x" -#define PRIXLEAST32 "I32X" -#define PRIoFAST32 "I32o" -#define PRIuFAST32 "I32u" -#define PRIxFAST32 "I32x" -#define PRIXFAST32 "I32X" - -#define PRIo64 "I64o" -#define PRIu64 "I64u" -#define PRIx64 "I64x" -#define PRIX64 "I64X" -#define PRIoLEAST64 "I64o" -#define PRIuLEAST64 "I64u" -#define PRIxLEAST64 "I64x" -#define PRIXLEAST64 "I64X" -#define PRIoFAST64 "I64o" -#define PRIuFAST64 "I64u" -#define PRIxFAST64 "I64x" -#define PRIXFAST64 "I64X" - -#define PRIoMAX "I64o" -#define PRIuMAX "I64u" -#define PRIxMAX "I64x" -#define PRIXMAX "I64X" - -#define PRIoPTR "Io" -#define PRIuPTR "Iu" -#define PRIxPTR "Ix" -#define PRIXPTR "IX" +#define PRIo8 "o" +#define PRIu8 "u" +#define PRIx8 "x" +#define PRIX8 "X" +#define PRIoLEAST8 "o" +#define PRIuLEAST8 "u" +#define PRIxLEAST8 "x" +#define PRIXLEAST8 "X" +#define PRIoFAST8 "o" +#define PRIuFAST8 "u" +#define PRIxFAST8 "x" +#define PRIXFAST8 "X" + +#define PRIo16 "ho" +#define PRIu16 "hu" +#define PRIx16 "hx" +#define PRIX16 "hX" +#define PRIoLEAST16 "ho" +#define PRIuLEAST16 "hu" +#define PRIxLEAST16 "hx" +#define PRIXLEAST16 "hX" +#define PRIoFAST16 "ho" +#define PRIuFAST16 "hu" +#define PRIxFAST16 "hx" +#define PRIXFAST16 "hX" + +#define PRIo32 "I32o" +#define PRIu32 "I32u" +#define PRIx32 "I32x" +#define PRIX32 "I32X" +#define PRIoLEAST32 "I32o" +#define PRIuLEAST32 "I32u" +#define PRIxLEAST32 "I32x" +#define PRIXLEAST32 "I32X" +#define PRIoFAST32 "I32o" +#define PRIuFAST32 "I32u" +#define PRIxFAST32 "I32x" +#define PRIXFAST32 "I32X" + +#define PRIo64 "I64o" +#define PRIu64 "I64u" +#define PRIx64 "I64x" +#define PRIX64 "I64X" +#define PRIoLEAST64 "I64o" +#define PRIuLEAST64 "I64u" +#define PRIxLEAST64 "I64x" +#define PRIXLEAST64 "I64X" +#define PRIoFAST64 "I64o" +#define PRIuFAST64 "I64u" +#define PRIxFAST64 "I64x" +#define PRIXFAST64 "I64X" + +#define PRIoMAX "I64o" +#define PRIuMAX "I64u" +#define PRIxMAX "I64x" +#define PRIXMAX "I64X" + +#define PRIoPTR "Io" +#define PRIuPTR "Iu" +#define PRIxPTR "Ix" +#define PRIXPTR "IX" // The fscanf macros for signed integers are: -#define SCNd8 "d" -#define SCNi8 "i" -#define SCNdLEAST8 "d" -#define SCNiLEAST8 "i" -#define SCNdFAST8 "d" -#define SCNiFAST8 "i" - -#define SCNd16 "hd" -#define SCNi16 "hi" -#define SCNdLEAST16 "hd" -#define SCNiLEAST16 "hi" -#define SCNdFAST16 "hd" -#define SCNiFAST16 "hi" - -#define SCNd32 "ld" -#define SCNi32 "li" -#define SCNdLEAST32 "ld" -#define SCNiLEAST32 "li" -#define SCNdFAST32 "ld" -#define SCNiFAST32 "li" - -#define SCNd64 "I64d" -#define SCNi64 "I64i" -#define SCNdLEAST64 "I64d" -#define SCNiLEAST64 "I64i" -#define SCNdFAST64 "I64d" -#define SCNiFAST64 "I64i" - -#define SCNdMAX "I64d" -#define SCNiMAX "I64i" +#define SCNd8 "d" +#define SCNi8 "i" +#define SCNdLEAST8 "d" +#define SCNiLEAST8 "i" +#define SCNdFAST8 "d" +#define SCNiFAST8 "i" + +#define SCNd16 "hd" +#define SCNi16 "hi" +#define SCNdLEAST16 "hd" +#define SCNiLEAST16 "hi" +#define SCNdFAST16 "hd" +#define SCNiFAST16 "hi" + +#define SCNd32 "ld" +#define SCNi32 "li" +#define SCNdLEAST32 "ld" +#define SCNiLEAST32 "li" +#define SCNdFAST32 "ld" +#define SCNiFAST32 "li" + +#define SCNd64 "I64d" +#define SCNi64 "I64i" +#define SCNdLEAST64 "I64d" +#define SCNiLEAST64 "I64i" +#define SCNdFAST64 "I64d" +#define SCNiFAST64 "I64i" + +#define SCNdMAX "I64d" +#define SCNiMAX "I64i" #ifdef _WIN64 // [ -# define SCNdPTR "I64d" -# define SCNiPTR "I64i" -#else // _WIN64 ][ -# define SCNdPTR "ld" -# define SCNiPTR "li" -#endif // _WIN64 ] +#define SCNdPTR "I64d" +#define SCNiPTR "I64i" +#else // _WIN64 ][ +#define SCNdPTR "ld" +#define SCNiPTR "li" +#endif // _WIN64 ] // The fscanf macros for unsigned integers are: -#define SCNo8 "o" -#define SCNu8 "u" -#define SCNx8 "x" -#define SCNX8 "X" -#define SCNoLEAST8 "o" -#define SCNuLEAST8 "u" -#define SCNxLEAST8 "x" -#define SCNXLEAST8 "X" -#define SCNoFAST8 "o" -#define SCNuFAST8 "u" -#define SCNxFAST8 "x" -#define SCNXFAST8 "X" - -#define SCNo16 "ho" -#define SCNu16 "hu" -#define SCNx16 "hx" -#define SCNX16 "hX" -#define SCNoLEAST16 "ho" -#define SCNuLEAST16 "hu" -#define SCNxLEAST16 "hx" -#define SCNXLEAST16 "hX" -#define SCNoFAST16 "ho" -#define SCNuFAST16 "hu" -#define SCNxFAST16 "hx" -#define SCNXFAST16 "hX" - -#define SCNo32 "lo" -#define SCNu32 "lu" -#define SCNx32 "lx" -#define SCNX32 "lX" -#define SCNoLEAST32 "lo" -#define SCNuLEAST32 "lu" -#define SCNxLEAST32 "lx" -#define SCNXLEAST32 "lX" -#define SCNoFAST32 "lo" -#define SCNuFAST32 "lu" -#define SCNxFAST32 "lx" -#define SCNXFAST32 "lX" - -#define SCNo64 "I64o" -#define SCNu64 "I64u" -#define SCNx64 "I64x" -#define SCNX64 "I64X" -#define SCNoLEAST64 "I64o" -#define SCNuLEAST64 "I64u" -#define SCNxLEAST64 "I64x" -#define SCNXLEAST64 "I64X" -#define SCNoFAST64 "I64o" -#define SCNuFAST64 "I64u" -#define SCNxFAST64 "I64x" -#define SCNXFAST64 "I64X" - -#define SCNoMAX "I64o" -#define SCNuMAX "I64u" -#define SCNxMAX "I64x" -#define SCNXMAX "I64X" +#define SCNo8 "o" +#define SCNu8 "u" +#define SCNx8 "x" +#define SCNX8 "X" +#define SCNoLEAST8 "o" +#define SCNuLEAST8 "u" +#define SCNxLEAST8 "x" +#define SCNXLEAST8 "X" +#define SCNoFAST8 "o" +#define SCNuFAST8 "u" +#define SCNxFAST8 "x" +#define SCNXFAST8 "X" + +#define SCNo16 "ho" +#define SCNu16 "hu" +#define SCNx16 "hx" +#define SCNX16 "hX" +#define SCNoLEAST16 "ho" +#define SCNuLEAST16 "hu" +#define SCNxLEAST16 "hx" +#define SCNXLEAST16 "hX" +#define SCNoFAST16 "ho" +#define SCNuFAST16 "hu" +#define SCNxFAST16 "hx" +#define SCNXFAST16 "hX" + +#define SCNo32 "lo" +#define SCNu32 "lu" +#define SCNx32 "lx" +#define SCNX32 "lX" +#define SCNoLEAST32 "lo" +#define SCNuLEAST32 "lu" +#define SCNxLEAST32 "lx" +#define SCNXLEAST32 "lX" +#define SCNoFAST32 "lo" +#define SCNuFAST32 "lu" +#define SCNxFAST32 "lx" +#define SCNXFAST32 "lX" + +#define SCNo64 "I64o" +#define SCNu64 "I64u" +#define SCNx64 "I64x" +#define SCNX64 "I64X" +#define SCNoLEAST64 "I64o" +#define SCNuLEAST64 "I64u" +#define SCNxLEAST64 "I64x" +#define SCNXLEAST64 "I64X" +#define SCNoFAST64 "I64o" +#define SCNuFAST64 "I64u" +#define SCNxFAST64 "I64x" +#define SCNXFAST64 "I64X" + +#define SCNoMAX "I64o" +#define SCNuMAX "I64u" +#define SCNxMAX "I64x" +#define SCNXMAX "I64X" #ifdef _WIN64 // [ -# define SCNoPTR "I64o" -# define SCNuPTR "I64u" -# define SCNxPTR "I64x" -# define SCNXPTR "I64X" -#else // _WIN64 ][ -# define SCNoPTR "lo" -# define SCNuPTR "lu" -# define SCNxPTR "lx" -# define SCNXPTR "lX" -#endif // _WIN64 ] +#define SCNoPTR "I64o" +#define SCNuPTR "I64u" +#define SCNxPTR "I64x" +#define SCNXPTR "I64X" +#else // _WIN64 ][ +#define SCNoPTR "lo" +#define SCNuPTR "lu" +#define SCNxPTR "lx" +#define SCNXPTR "lX" +#endif // _WIN64 ] #endif // __STDC_FORMAT_MACROS ] @@ -293,23 +293,22 @@ typedef struct { // in %MSVC.NET%\crt\src\div.c #ifdef STATIC_IMAXDIV // [ static -#else // STATIC_IMAXDIV ][ +#else // STATIC_IMAXDIV ][ _inline #endif // STATIC_IMAXDIV ] -imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) -{ - imaxdiv_t result; + imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) { + imaxdiv_t result; - result.quot = numer / denom; - result.rem = numer % denom; + result.quot = numer / denom; + result.rem = numer % denom; - if (numer < 0 && result.rem > 0) { - // did division wrong; must fix up - ++result.quot; - result.rem -= denom; - } + if (numer < 0 && result.rem > 0) { + // did division wrong; must fix up + ++result.quot; + result.rem -= denom; + } - return result; + return result; } // 7.8.2.3 The strtoimax and strtoumax functions @@ -320,5 +319,4 @@ imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) #define wcstoimax _wcstoi64 #define wcstoumax _wcstoui64 - #endif // _MSC_INTTYPES_H_ ] diff --git a/include/MSVC/stdint.h b/include/MSVC/stdint.h index 6e099532..765f251b 100644 --- a/include/MSVC/stdint.h +++ b/include/MSVC/stdint.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,34 +18,34 @@ * along with this program. If not, see . */ // ISO C9x compliant stdint.h for Microsoft Visual Studio -// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 -// +// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 +// // Copyright (c) 2006-2008 Alexander Chemeris -// +// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: -// +// // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. -// +// // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. -// +// // 3. The name of the author may be used to endorse or promote products // derived from this software without specific prior written permission. -// +// // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// +// /////////////////////////////////////////////////////////////////////////////// #ifndef _MSC_VER // [ @@ -68,20 +68,19 @@ #ifdef __cplusplus extern "C" { #endif -# include +#include #ifdef __cplusplus } #endif // Define _W64 macros to mark types changing their size, like intptr_t. #ifndef _W64 -# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 -# define _W64 __w64 -# else -# define _W64 -# endif +#if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 +#define _W64 __w64 +#else +#define _W64 +#endif #endif - // 7.18.1 Integer types @@ -91,176 +90,173 @@ extern "C" { // realize that, e.g. char has the same size as __int8 // so we give up on __intX for them. #if (_MSC_VER < 1300) - typedef signed char int8_t; - typedef signed short int16_t; - typedef signed int int32_t; - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned int uint32_t; +typedef signed char int8_t; +typedef signed short int16_t; +typedef signed int int32_t; +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; +typedef unsigned int uint32_t; #else - typedef signed __int8 int8_t; - typedef signed __int16 int16_t; - typedef signed __int32 int32_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; +typedef signed __int8 int8_t; +typedef signed __int16 int16_t; +typedef signed __int32 int32_t; +typedef unsigned __int8 uint8_t; +typedef unsigned __int16 uint16_t; +typedef unsigned __int32 uint32_t; #endif -typedef signed __int64 int64_t; -typedef unsigned __int64 uint64_t; - +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; // 7.18.1.2 Minimum-width integer types -typedef int8_t int_least8_t; -typedef int16_t int_least16_t; -typedef int32_t int_least32_t; -typedef int64_t int_least64_t; -typedef uint8_t uint_least8_t; -typedef uint16_t uint_least16_t; -typedef uint32_t uint_least32_t; -typedef uint64_t uint_least64_t; +typedef int8_t int_least8_t; +typedef int16_t int_least16_t; +typedef int32_t int_least32_t; +typedef int64_t int_least64_t; +typedef uint8_t uint_least8_t; +typedef uint16_t uint_least16_t; +typedef uint32_t uint_least32_t; +typedef uint64_t uint_least64_t; // 7.18.1.3 Fastest minimum-width integer types -typedef int8_t int_fast8_t; -typedef int16_t int_fast16_t; -typedef int32_t int_fast32_t; -typedef int64_t int_fast64_t; -typedef uint8_t uint_fast8_t; -typedef uint16_t uint_fast16_t; -typedef uint32_t uint_fast32_t; -typedef uint64_t uint_fast64_t; +typedef int8_t int_fast8_t; +typedef int16_t int_fast16_t; +typedef int32_t int_fast32_t; +typedef int64_t int_fast64_t; +typedef uint8_t uint_fast8_t; +typedef uint16_t uint_fast16_t; +typedef uint32_t uint_fast32_t; +typedef uint64_t uint_fast64_t; // 7.18.1.4 Integer types capable of holding object pointers #ifdef _WIN64 // [ - typedef signed __int64 intptr_t; - typedef unsigned __int64 uintptr_t; -#else // _WIN64 ][ - typedef _W64 signed int intptr_t; - typedef _W64 unsigned int uintptr_t; +typedef signed __int64 intptr_t; +typedef unsigned __int64 uintptr_t; +#else // _WIN64 ][ +typedef _W64 signed int intptr_t; +typedef _W64 unsigned int uintptr_t; #endif // _WIN64 ] // 7.18.1.5 Greatest-width integer types -typedef int64_t intmax_t; -typedef uint64_t uintmax_t; - +typedef int64_t intmax_t; +typedef uint64_t uintmax_t; // 7.18.2 Limits of specified-width integer types -#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 +#if !defined(__cplusplus) || \ + defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 // 7.18.2.1 Limits of exact-width integer types -#define INT8_MIN ((int8_t)_I8_MIN) -#define INT8_MAX _I8_MAX -#define INT16_MIN ((int16_t)_I16_MIN) -#define INT16_MAX _I16_MAX -#define INT32_MIN ((int32_t)_I32_MIN) -#define INT32_MAX _I32_MAX -#define INT64_MIN ((int64_t)_I64_MIN) -#define INT64_MAX _I64_MAX -#define UINT8_MAX _UI8_MAX -#define UINT16_MAX _UI16_MAX -#define UINT32_MAX _UI32_MAX -#define UINT64_MAX _UI64_MAX +#define INT8_MIN ((int8_t)_I8_MIN) +#define INT8_MAX _I8_MAX +#define INT16_MIN ((int16_t)_I16_MIN) +#define INT16_MAX _I16_MAX +#define INT32_MIN ((int32_t)_I32_MIN) +#define INT32_MAX _I32_MAX +#define INT64_MIN ((int64_t)_I64_MIN) +#define INT64_MAX _I64_MAX +#define UINT8_MAX _UI8_MAX +#define UINT16_MAX _UI16_MAX +#define UINT32_MAX _UI32_MAX +#define UINT64_MAX _UI64_MAX // 7.18.2.2 Limits of minimum-width integer types -#define INT_LEAST8_MIN INT8_MIN -#define INT_LEAST8_MAX INT8_MAX -#define INT_LEAST16_MIN INT16_MIN -#define INT_LEAST16_MAX INT16_MAX -#define INT_LEAST32_MIN INT32_MIN -#define INT_LEAST32_MAX INT32_MAX -#define INT_LEAST64_MIN INT64_MIN -#define INT_LEAST64_MAX INT64_MAX -#define UINT_LEAST8_MAX UINT8_MAX -#define UINT_LEAST16_MAX UINT16_MAX -#define UINT_LEAST32_MAX UINT32_MAX -#define UINT_LEAST64_MAX UINT64_MAX +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST8_MAX INT8_MAX +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST16_MAX INT16_MAX +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST32_MAX INT32_MAX +#define INT_LEAST64_MIN INT64_MIN +#define INT_LEAST64_MAX INT64_MAX +#define UINT_LEAST8_MAX UINT8_MAX +#define UINT_LEAST16_MAX UINT16_MAX +#define UINT_LEAST32_MAX UINT32_MAX +#define UINT_LEAST64_MAX UINT64_MAX // 7.18.2.3 Limits of fastest minimum-width integer types -#define INT_FAST8_MIN INT8_MIN -#define INT_FAST8_MAX INT8_MAX -#define INT_FAST16_MIN INT16_MIN -#define INT_FAST16_MAX INT16_MAX -#define INT_FAST32_MIN INT32_MIN -#define INT_FAST32_MAX INT32_MAX -#define INT_FAST64_MIN INT64_MIN -#define INT_FAST64_MAX INT64_MAX -#define UINT_FAST8_MAX UINT8_MAX -#define UINT_FAST16_MAX UINT16_MAX -#define UINT_FAST32_MAX UINT32_MAX -#define UINT_FAST64_MAX UINT64_MAX +#define INT_FAST8_MIN INT8_MIN +#define INT_FAST8_MAX INT8_MAX +#define INT_FAST16_MIN INT16_MIN +#define INT_FAST16_MAX INT16_MAX +#define INT_FAST32_MIN INT32_MIN +#define INT_FAST32_MAX INT32_MAX +#define INT_FAST64_MIN INT64_MIN +#define INT_FAST64_MAX INT64_MAX +#define UINT_FAST8_MAX UINT8_MAX +#define UINT_FAST16_MAX UINT16_MAX +#define UINT_FAST32_MAX UINT32_MAX +#define UINT_FAST64_MAX UINT64_MAX // 7.18.2.4 Limits of integer types capable of holding object pointers #ifdef _WIN64 // [ -# define INTPTR_MIN INT64_MIN -# define INTPTR_MAX INT64_MAX -# define UINTPTR_MAX UINT64_MAX +#define INTPTR_MIN INT64_MIN +#define INTPTR_MAX INT64_MAX +#define UINTPTR_MAX UINT64_MAX #else // _WIN64 ][ -# define INTPTR_MIN INT32_MIN -# define INTPTR_MAX INT32_MAX -# define UINTPTR_MAX UINT32_MAX +#define INTPTR_MIN INT32_MIN +#define INTPTR_MAX INT32_MAX +#define UINTPTR_MAX UINT32_MAX #endif // _WIN64 ] // 7.18.2.5 Limits of greatest-width integer types -#define INTMAX_MIN INT64_MIN -#define INTMAX_MAX INT64_MAX -#define UINTMAX_MAX UINT64_MAX +#define INTMAX_MIN INT64_MIN +#define INTMAX_MAX INT64_MAX +#define UINTMAX_MAX UINT64_MAX // 7.18.3 Limits of other integer types #ifdef _WIN64 // [ -# define PTRDIFF_MIN _I64_MIN -# define PTRDIFF_MAX _I64_MAX -#else // _WIN64 ][ -# define PTRDIFF_MIN _I32_MIN -# define PTRDIFF_MAX _I32_MAX -#endif // _WIN64 ] +#define PTRDIFF_MIN _I64_MIN +#define PTRDIFF_MAX _I64_MAX +#else // _WIN64 ][ +#define PTRDIFF_MIN _I32_MIN +#define PTRDIFF_MAX _I32_MAX +#endif // _WIN64 ] -#define SIG_ATOMIC_MIN INT_MIN -#define SIG_ATOMIC_MAX INT_MAX +#define SIG_ATOMIC_MIN INT_MIN +#define SIG_ATOMIC_MAX INT_MAX #ifndef SIZE_MAX // [ -# ifdef _WIN64 // [ -# define SIZE_MAX _UI64_MAX -# else // _WIN64 ][ -# define SIZE_MAX _UI32_MAX -# endif // _WIN64 ] +#ifdef _WIN64 // [ +#define SIZE_MAX _UI64_MAX +#else // _WIN64 ][ +#define SIZE_MAX _UI32_MAX +#endif // _WIN64 ] #endif // SIZE_MAX ] // WCHAR_MIN and WCHAR_MAX are also defined in #ifndef WCHAR_MIN // [ -# define WCHAR_MIN 0 -#endif // WCHAR_MIN ] +#define WCHAR_MIN 0 +#endif // WCHAR_MIN ] #ifndef WCHAR_MAX // [ -# define WCHAR_MAX _UI16_MAX -#endif // WCHAR_MAX ] +#define WCHAR_MAX _UI16_MAX +#endif // WCHAR_MAX ] -#define WINT_MIN 0 -#define WINT_MAX _UI16_MAX +#define WINT_MIN 0 +#define WINT_MAX _UI16_MAX #endif // __STDC_LIMIT_MACROS ] - // 7.18.4 Limits of other integer types #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 // 7.18.4.1 Macros for minimum-width integer constants -#define INT8_C(val) val##i8 +#define INT8_C(val) val##i8 #define INT16_C(val) val##i16 #define INT32_C(val) val##i32 #define INT64_C(val) val##i64 -#define UINT8_C(val) val##ui8 +#define UINT8_C(val) val##ui8 #define UINT16_C(val) val##ui16 #define UINT32_C(val) val##ui32 #define UINT64_C(val) val##ui64 // 7.18.4.2 Macros for greatest-width integer constants -#define INTMAX_C INT64_C -#define UINTMAX_C UINT64_C +#define INTMAX_C INT64_C +#define UINTMAX_C UINT64_C #endif // __STDC_CONSTANT_MACROS ] - #endif // _MSC_STDINT_H_ ] diff --git a/include/ortp/b64.h b/include/ortp/b64.h index ce4289bf..fdfc3653 100644 --- a/include/ortp/b64.h +++ b/include/ortp/b64.h @@ -40,7 +40,6 @@ * * ////////////////////////////////////////////////////////////////////////// */ - /** \file ortp/b64.h * * \brief [C/C++] Header file for the b64 library. @@ -54,10 +53,10 @@ */ #ifndef B64_DOCUMENTATION_SKIP_SECTION -# define B64_VER_B64_H_B64_MAJOR 1 -# define B64_VER_B64_H_B64_MINOR 5 -# define B64_VER_B64_H_B64_REVISION 4 -# define B64_VER_B64_H_B64_EDIT 28 +#define B64_VER_B64_H_B64_MAJOR 1 +#define B64_VER_B64_H_B64_MINOR 5 +#define B64_VER_B64_H_B64_REVISION 4 +#define B64_VER_B64_H_B64_EDIT 28 #endif /* !B64_DOCUMENTATION_SKIP_SECTION */ /** \def B64_VER_MAJOR @@ -77,73 +76,69 @@ */ #ifndef B64_DOCUMENTATION_SKIP_SECTION -# define B64_VER_1_0_1 0x01000100 -# define B64_VER_1_0_2 0x01000200 -# define B64_VER_1_0_3 0x01000300 -# define B64_VER_1_1_1 0x01010100 -# define B64_VER_1_1_2 0x01010200 -# define B64_VER_1_1_3 0x01010300 -# define B64_VER_1_2_1 0x01020100 -# define B64_VER_1_2_2 0x01020200 -# define B64_VER_1_2_3 0x01020300 -# define B64_VER_1_2_4 0x01020400 -# define B64_VER_1_2_5 0x01020500 -# define B64_VER_1_2_6 0x01020600 -# define B64_VER_1_2_7 0x01020700 -# define B64_VER_1_3_1 0x010301ff -# define B64_VER_1_3_2 0x010302ff -# define B64_VER_1_3_3 0x010303ff -# define B64_VER_1_3_4 0x010304ff - -# define B64_VER B64_VER_1_3_4 +#define B64_VER_1_0_1 0x01000100 +#define B64_VER_1_0_2 0x01000200 +#define B64_VER_1_0_3 0x01000300 +#define B64_VER_1_1_1 0x01010100 +#define B64_VER_1_1_2 0x01010200 +#define B64_VER_1_1_3 0x01010300 +#define B64_VER_1_2_1 0x01020100 +#define B64_VER_1_2_2 0x01020200 +#define B64_VER_1_2_3 0x01020300 +#define B64_VER_1_2_4 0x01020400 +#define B64_VER_1_2_5 0x01020500 +#define B64_VER_1_2_6 0x01020600 +#define B64_VER_1_2_7 0x01020700 +#define B64_VER_1_3_1 0x010301ff +#define B64_VER_1_3_2 0x010302ff +#define B64_VER_1_3_3 0x010303ff +#define B64_VER_1_3_4 0x010304ff + +#define B64_VER B64_VER_1_3_4 #else /* ? B64_DOCUMENTATION_SKIP_SECTION */ -# define B64_VER 0x010304ff +#define B64_VER 0x010304ff #endif /* !B64_DOCUMENTATION_SKIP_SECTION */ -#define B64_VER_MAJOR 1 -#define B64_VER_MINOR 3 -#define B64_VER_REVISION 4 +#define B64_VER_MAJOR 1 +#define B64_VER_MINOR 3 +#define B64_VER_REVISION 4 /* ///////////////////////////////////////////////////////////////////////////// * Includes */ -#include #include "ortp/port.h" +#include /* ///////////////////////////////////////////////////////////////////////////// * Namespace */ -#if !defined(B64_NO_NAMESPACE) && \ - !defined(__cplusplus) -# define B64_NO_NAMESPACE +#if !defined(B64_NO_NAMESPACE) && !defined(__cplusplus) +#define B64_NO_NAMESPACE #endif /* !B64_NO_NAMESPACE && !__cplusplus */ #ifdef B64_NAMESPACE -# undef B64_NAMESPACE +#undef B64_NAMESPACE #endif /* B64_NAMESPACE */ #ifdef B64_NAMESPACE_QUALIFIER -# undef B64_NAMESPACE_QUALIFIER +#undef B64_NAMESPACE_QUALIFIER #endif /* B64_NAMESPACE_QUALIFIER */ - #ifndef B64_NO_NAMESPACE -# ifdef B64_CUSTOM_NAMESPACE -# define B64_NAMESPACE B64_CUSTOM_NAMESPACE -# else /* ? B64_CUSTOM_NAMESPACE */ -# define B64_NAMESPACE b64 -# endif /* B64_CUSTOM_NAMESPACE */ - -# if defined(B64_CUSTOM_NAMESPACE) && \ - defined(B64_CUSTOM_NAMESPACE_QUALIFIER) -# define B64_NAMESPACE_QUALIFIER B64_CUSTOM_NAMESPACE_QUALIFIER -# else /* B64_CUSTOM_NAMESPACE && B64_CUSTOM_NAMESPACE_QUALIFIER */ -# define B64_NAMESPACE_QUALIFIER ::B64_NAMESPACE -# endif /* B64_CUSTOM_NAMESPACE && B64_CUSTOM_NAMESPACE_QUALIFIER */ +#ifdef B64_CUSTOM_NAMESPACE +#define B64_NAMESPACE B64_CUSTOM_NAMESPACE +#else /* ? B64_CUSTOM_NAMESPACE */ +#define B64_NAMESPACE b64 +#endif /* B64_CUSTOM_NAMESPACE */ +#if defined(B64_CUSTOM_NAMESPACE) && defined(B64_CUSTOM_NAMESPACE_QUALIFIER) +#define B64_NAMESPACE_QUALIFIER B64_CUSTOM_NAMESPACE_QUALIFIER +#else /* B64_CUSTOM_NAMESPACE && B64_CUSTOM_NAMESPACE_QUALIFIER */ +#define B64_NAMESPACE_QUALIFIER ::B64_NAMESPACE +#endif /* B64_CUSTOM_NAMESPACE && B64_CUSTOM_NAMESPACE_QUALIFIER */ /** \brief [C/C++] The b64 namespace, within which the core library types and functions * reside in C++ compilation. In C compilation, they all reside in the global @@ -153,8 +148,7 @@ *
* \endhtmlonly */ -namespace B64_NAMESPACE -{ +namespace B64_NAMESPACE { #endif /* !B64_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////////// @@ -163,14 +157,17 @@ namespace B64_NAMESPACE /** \brief Return codes (from b64_encode2() / b64_decode2()) */ -enum B64_RC -{ - B64_RC_OK = 0 /*!< Operation was successful. */ - , B64_RC_INSUFFICIENT_BUFFER = 1 /*!< The given translation buffer was not of sufficient size. */ - , B64_RC_TRUNCATED_INPUT = 2 /*!< The input did not represent a fully formed stream of octet couplings. */ - , B64_RC_DATA_ERROR = 3 /*!< Invalid data. */ +enum B64_RC { + B64_RC_OK = 0 /*!< Operation was successful. */ + , + B64_RC_INSUFFICIENT_BUFFER = 1 /*!< The given translation buffer was not of sufficient size. */ + , + B64_RC_TRUNCATED_INPUT = 2 /*!< The input did not represent a fully formed stream of octet couplings. */ + , + B64_RC_DATA_ERROR = 3 /*!< Invalid data. */ #ifndef B64_DOCUMENTATION_SKIP_SECTION - , B64_max_RC_value + , + B64_max_RC_value #endif /* !B64_DOCUMENTATION_SKIP_SECTION */ }; @@ -180,21 +177,35 @@ typedef enum B64_RC B64_RC; /** \brief Coding behaviour modification flags (for b64_encode2() / b64_decode2()) */ -enum B64_FLAGS -{ - B64_F_LINE_LEN_USE_PARAM = 0x0000 /*!< Uses the lineLen parameter to b64_encode2(). Ignored by b64_decode2(). */ - , B64_F_LINE_LEN_INFINITE = 0x0001 /*!< Ignores the lineLen parameter to b64_encode2(). Line length is infinite. Ignored by b64_decode2(). */ - , B64_F_LINE_LEN_64 = 0x0002 /*!< Ignores the lineLen parameter to b64_encode2(). Line length is 64. Ignored by b64_decode2(). */ - , B64_F_LINE_LEN_76 = 0x0003 /*!< Ignores the lineLen parameter to b64_encode2(). Line length is 76. Ignored by b64_decode2(). */ - , B64_F_LINE_LEN_MASK = 0x000f /*!< Mask for testing line length flags to b64_encode2(). Ignored by b64_encode2(). */ - , B64_F_STOP_ON_NOTHING = 0x0000 /*!< Decoding ignores all invalid characters in the input data. Ignored by b64_encode2(). */ - , B64_F_STOP_ON_UNKNOWN_CHAR = 0x0100 /*!< Causes decoding to break if any non-Base-64 [a-zA-Z0-9=+/], non-whitespace character is encountered. Ignored by b64_encode2(). */ - , B64_F_STOP_ON_UNEXPECTED_WS = 0x0200 /*!< Causes decoding to break if any unexpected whitespace is encountered. Ignored by b64_encode2(). */ - , B64_F_STOP_ON_BAD_CHAR = 0x0300 /*!< Causes decoding to break if any non-Base-64 [a-zA-Z0-9=+/] character is encountered. Ignored by b64_encode2(). */ +enum B64_FLAGS { + B64_F_LINE_LEN_USE_PARAM = 0x0000 /*!< Uses the lineLen parameter to b64_encode2(). Ignored by b64_decode2(). */ + , + B64_F_LINE_LEN_INFINITE = 0x0001 /*!< Ignores the lineLen parameter to b64_encode2(). Line length is infinite. + Ignored by b64_decode2(). */ + , + B64_F_LINE_LEN_64 = + 0x0002 /*!< Ignores the lineLen parameter to b64_encode2(). Line length is 64. Ignored by b64_decode2(). */ + , + B64_F_LINE_LEN_76 = + 0x0003 /*!< Ignores the lineLen parameter to b64_encode2(). Line length is 76. Ignored by b64_decode2(). */ + , + B64_F_LINE_LEN_MASK = 0x000f /*!< Mask for testing line length flags to b64_encode2(). Ignored by b64_encode2(). */ + , + B64_F_STOP_ON_NOTHING = + 0x0000 /*!< Decoding ignores all invalid characters in the input data. Ignored by b64_encode2(). */ + , + B64_F_STOP_ON_UNKNOWN_CHAR = 0x0100 /*!< Causes decoding to break if any non-Base-64 [a-zA-Z0-9=+/], non-whitespace + character is encountered. Ignored by b64_encode2(). */ + , + B64_F_STOP_ON_UNEXPECTED_WS = + 0x0200 /*!< Causes decoding to break if any unexpected whitespace is encountered. Ignored by b64_encode2(). */ + , + B64_F_STOP_ON_BAD_CHAR = 0x0300 /*!< Causes decoding to break if any non-Base-64 [a-zA-Z0-9=+/] character is + encountered. Ignored by b64_encode2(). */ }; #ifndef __cplusplus -typedef enum B64_FLAGS B64_FLAGS; +typedef enum B64_FLAGS B64_FLAGS; #endif /* !__cplusplus */ /* ///////////////////////////////////////////////////////////////////////////// @@ -258,13 +269,14 @@ ORTP_PUBLIC size_t b64_encode(void const *src, size_t srcSize, char *dest, size_ * * \see b64::encode() */ -size_t b64_encode2( void const *src - , size_t srcSize - , char *dest - , size_t destLen - , unsigned flags - , int lineLen /* = 0 */ - , B64_RC *rc /* = NULL */); +size_t b64_encode2(void const *src, + size_t srcSize, + char *dest, + size_t destLen, + unsigned flags, + int lineLen /* = 0 */ + , + B64_RC *rc /* = NULL */); /** \brief Decodes a sequence of Base-64 into a block of binary data * @@ -341,14 +353,14 @@ ORTP_PUBLIC size_t b64_decode(char const *src, size_t srcLen, void *dest, size_t * * \see b64::decode() */ -size_t b64_decode2( char const *src - , size_t srcLen - , void *dest - , size_t destSize - , unsigned flags - , char const **badChar /* = NULL */ - , B64_RC *rc /* = NULL */); - +size_t b64_decode2(char const *src, + size_t srcLen, + void *dest, + size_t destSize, + unsigned flags, + char const **badChar /* = NULL */ + , + B64_RC *rc /* = NULL */); /** \brief Returns the textual description of the error * @@ -364,7 +376,6 @@ char const *b64_getErrorString(B64_RC code); */ size_t b64_getErrorStringLength(B64_RC code); - #ifdef __cplusplus } /* extern "C" */ #endif /* __cplusplus */ @@ -376,41 +387,34 @@ size_t b64_getErrorStringLength(B64_RC code); #ifndef B64_NO_NAMESPACE } /* namespace B64_NAMESPACE */ -# ifndef B64_DOCUMENTATION_SKIP_SECTION - -namespace stlsoft -{ - - inline char const *c_str_data_a( B64_NAMESPACE_QUALIFIER::B64_RC code) - { - return B64_NAMESPACE_QUALIFIER::b64_getErrorString(code); - } - inline char const *c_str_data( B64_NAMESPACE_QUALIFIER::B64_RC code) - { - return B64_NAMESPACE_QUALIFIER::b64_getErrorString(code); - } - - inline size_t c_str_len_a( B64_NAMESPACE_QUALIFIER::B64_RC code) - { - return B64_NAMESPACE_QUALIFIER::b64_getErrorStringLength(code); - } - inline size_t c_str_len( B64_NAMESPACE_QUALIFIER::B64_RC code) - { - return B64_NAMESPACE_QUALIFIER::b64_getErrorStringLength(code); - } - - inline char const *c_str_ptr_a( B64_NAMESPACE_QUALIFIER::B64_RC code) - { - return B64_NAMESPACE_QUALIFIER::b64_getErrorString(code); - } - inline char const *c_str_ptr( B64_NAMESPACE_QUALIFIER::B64_RC code) - { - return B64_NAMESPACE_QUALIFIER::b64_getErrorString(code); - } +#ifndef B64_DOCUMENTATION_SKIP_SECTION + +namespace stlsoft { + +inline char const *c_str_data_a(B64_NAMESPACE_QUALIFIER::B64_RC code) { + return B64_NAMESPACE_QUALIFIER::b64_getErrorString(code); +} +inline char const *c_str_data(B64_NAMESPACE_QUALIFIER::B64_RC code) { + return B64_NAMESPACE_QUALIFIER::b64_getErrorString(code); +} + +inline size_t c_str_len_a(B64_NAMESPACE_QUALIFIER::B64_RC code) { + return B64_NAMESPACE_QUALIFIER::b64_getErrorStringLength(code); +} +inline size_t c_str_len(B64_NAMESPACE_QUALIFIER::B64_RC code) { + return B64_NAMESPACE_QUALIFIER::b64_getErrorStringLength(code); +} + +inline char const *c_str_ptr_a(B64_NAMESPACE_QUALIFIER::B64_RC code) { + return B64_NAMESPACE_QUALIFIER::b64_getErrorString(code); +} +inline char const *c_str_ptr(B64_NAMESPACE_QUALIFIER::B64_RC code) { + return B64_NAMESPACE_QUALIFIER::b64_getErrorString(code); +} } /* namespace stlsoft */ -# endif /* !B64_DOCUMENTATION_SKIP_SECTION */ +#endif /* !B64_DOCUMENTATION_SKIP_SECTION */ #endif /* !B64_NO_NAMESPACE */ diff --git a/include/ortp/event.h b/include/ortp/event.h index 1056d722..1e718ee3 100644 --- a/include/ortp/event.h +++ b/include/ortp/event.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -21,21 +21,18 @@ #ifndef ortp_events_h #define ortp_events_h -#include "ortp/str_utils.h" -#include "ortp/rtcp.h" #include "bctoolbox/list.h" +#include "ortp/rtcp.h" +#include "ortp/str_utils.h" typedef mblk_t OrtpEvent; typedef unsigned long OrtpEventType; -typedef enum { - OrtpRTPSocket, - OrtpRTCPSocket -} OrtpSocketType; +typedef enum { OrtpRTPSocket, OrtpRTCPSocket } OrtpSocketType; -struct _OrtpEventData{ - mblk_t *packet; /* most events are associated to a received packet */ +struct _OrtpEventData { + mblk_t *packet; /* most events are associated to a received packet */ struct sockaddr_storage source_addr; socklen_t source_addrlen; ortpTimeSpec ts; @@ -45,7 +42,7 @@ struct _OrtpEventData{ bool_t dtls_stream_encrypted; bool_t zrtp_stream_encrypted; bool_t ice_processing_successful; - struct _ZrtpInfo{ + struct _ZrtpInfo { char sas[32]; // up to 31 + null characters bool_t verified; bool_t cache_mismatch; @@ -56,73 +53,72 @@ struct _OrtpEventData{ int authTagAlgo; int sasAlgo; } zrtp_info; - struct _SrtpInfo{ - bool_t is_send; /**< stream direction this is applied too */ + struct _SrtpInfo { + bool_t is_send; /**< stream direction this is applied too */ bool_t is_inner; /**< this info applies to inner encryption (in case of SRTP double encryption) */ - int source; /**< the source of the key material as defined in MSSrtpKeySource enum in ms_strp.h */ - int suite; /**< the srtp crypto suite used as defined in MSCryptoSuite enum in ms_srtp.h */ + int source; /**< the source of the key material as defined in MSSrtpKeySource enum in ms_strp.h */ + int suite; /**< the srtp crypto suite used as defined in MSCryptoSuite enum in ms_srtp.h */ } srtp_info; OrtpSocketType socket_type; uint32_t received_rtt_character; bool_t congestion_detected; float video_bandwidth_available; int jitter_min_size_for_nack; - uint16_t reconstructed_packet_seq_number; + uint16_t reconstructed_packet_seq_number; } info; }; typedef struct _OrtpEventData OrtpEventData; - #ifdef __cplusplus -extern "C"{ +extern "C" { #endif -ORTP_PUBLIC OrtpEvent * ortp_event_new(OrtpEventType tp); +ORTP_PUBLIC OrtpEvent *ortp_event_new(OrtpEventType tp); ORTP_PUBLIC OrtpEventType ortp_event_get_type(const OrtpEvent *ev); /* type is one of the following*/ -#define ORTP_EVENT_STUN_PACKET_RECEIVED 1 -#define ORTP_EVENT_PAYLOAD_TYPE_CHANGED 2 -#define ORTP_EVENT_TELEPHONE_EVENT 3 -#define ORTP_EVENT_RTCP_PACKET_RECEIVED 4 /** #ifdef __cplusplus -extern "C"{ +extern "C" { #endif struct _OrtpNackContext { diff --git a/include/ortp/ortp.h b/include/ortp/ortp.h index d0ea674e..86ef6c6f 100644 --- a/include/ortp/ortp.h +++ b/include/ortp/ortp.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -60,7 +60,7 @@ * \file ortp.h * \brief General purpose library functions. * -**/ + **/ #ifndef ORTP_H #define ORTP_H @@ -69,8 +69,7 @@ #include "ortp/sessionset.h" #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif ORTP_PUBLIC bool_t ortp_min_version_required(int major, int minor, int micro); diff --git a/include/ortp/payloadtype.h b/include/ortp/payloadtype.h index a7bf5ef7..b6fa3445 100644 --- a/include/ortp/payloadtype.h +++ b/include/ortp/payloadtype.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -22,30 +22,30 @@ * \file payloadtype.h * \brief Definition of payload types * -**/ + **/ #ifndef PAYLOADTYPE_H #define PAYLOADTYPE_H #include #ifdef __cplusplus -extern "C"{ +extern "C" { #endif /* flags for PayloadType::flags */ -#define PAYLOAD_TYPE_ALLOCATED (1) +#define PAYLOAD_TYPE_ALLOCATED (1) /*payload type represents a VBR codec*/ -#define PAYLOAD_TYPE_IS_VBR (1<<1) -#define PAYLOAD_TYPE_RTCP_FEEDBACK_ENABLED (1<<2) +#define PAYLOAD_TYPE_IS_VBR (1 << 1) +#define PAYLOAD_TYPE_RTCP_FEEDBACK_ENABLED (1 << 2) /* private flags for future use by ortp */ -#define PAYLOAD_TYPE_PRIV1 (1<<3) +#define PAYLOAD_TYPE_PRIV1 (1 << 3) /* user flags, can be used by the application on top of oRTP */ -#define PAYLOAD_TYPE_USER_FLAG_0 (1<<4) -#define PAYLOAD_TYPE_USER_FLAG_1 (1<<5) -#define PAYLOAD_TYPE_USER_FLAG_2 (1<<6) -#define PAYLOAD_TYPE_USER_FLAG_3 (1<<7) -#define PAYLOAD_TYPE_USER_FLAG_4 (1<<8) +#define PAYLOAD_TYPE_USER_FLAG_0 (1 << 4) +#define PAYLOAD_TYPE_USER_FLAG_1 (1 << 5) +#define PAYLOAD_TYPE_USER_FLAG_2 (1 << 6) +#define PAYLOAD_TYPE_USER_FLAG_3 (1 << 7) +#define PAYLOAD_TYPE_USER_FLAG_4 (1 << 8) /* ask for more if you need*/ #define PAYLOAD_TYPE_FLAG_CAN_RECV PAYLOAD_TYPE_USER_FLAG_1 @@ -55,7 +55,7 @@ extern "C"{ #define PAYLOAD_AUDIO_PACKETIZED 1 #define PAYLOAD_VIDEO 2 #define PAYLOAD_TEXT 3 -#define PAYLOAD_OTHER 4 /* ?? */ +#define PAYLOAD_OTHER 4 /* ?? */ #define PAYLOAD_TYPE_AVPF_NONE 0 #define PAYLOAD_TYPE_AVPF_FIR (1 << 0) @@ -64,26 +64,25 @@ extern "C"{ #define PAYLOAD_TYPE_AVPF_RPSI (1 << 3) struct _PayloadTypeAvpfParams { - unsigned char features; /**< A bitmask of PAYLOAD_TYPE_AVPF_* macros. */ + unsigned char features; /**< A bitmask of PAYLOAD_TYPE_AVPF_* macros. */ bool_t rpsi_compatibility; /*< Linphone uses positive feeback for RPSI. However first versions handling - AVPF wrongly declared RPSI as negative feedback, so this is kept for compatibility - with these versions but will probably be removed at some point in time. */ - uint16_t trr_interval; /**< The interval in milliseconds between regular RTCP packets. */ + AVPF wrongly declared RPSI as negative feedback, so this is kept for compatibility + with these versions but will probably be removed at some point in time. */ + uint16_t trr_interval; /**< The interval in milliseconds between regular RTCP packets. */ }; -struct _OrtpPayloadType -{ - int type; /**< one of PAYLOAD_* macros*/ - int clock_rate; /**< rtp clock rate*/ - char bits_per_sample; /* in case of continuous audio data */ +struct _OrtpPayloadType { + int type; /**< one of PAYLOAD_* macros*/ + int clock_rate; /**< rtp clock rate*/ + char bits_per_sample; /* in case of continuous audio data */ char *zero_pattern; int pattern_length; /* other useful information for the application*/ - int normal_bitrate; /*in bit/s */ - char *mime_type; /**flags|=((int)flag) -#define payload_type_unset_flag(pt,flag) (pt)->flags&=(~(int)flag) -#define payload_type_get_flags(pt) (pt)->flags - +#define payload_type_set_flag(pt, flag) (pt)->flags |= ((int)flag) +#define payload_type_unset_flag(pt, flag) (pt)->flags &= (~(int)flag) +#define payload_type_get_flags(pt) (pt)->flags ORTP_PUBLIC PayloadType *payload_type_new(void); ORTP_PUBLIC PayloadType *payload_type_clone(const PayloadType *payload); @@ -109,19 +107,18 @@ ORTP_PUBLIC void payload_type_set_recv_fmtp(PayloadType *pt, const char *fmtp); ORTP_PUBLIC void payload_type_set_send_fmtp(PayloadType *pt, const char *fmtp); ORTP_PUBLIC void payload_type_append_recv_fmtp(PayloadType *pt, const char *fmtp); ORTP_PUBLIC void payload_type_append_send_fmtp(PayloadType *pt, const char *fmtp); -#define payload_type_get_avpf_params(pt) ((pt)->avpf) +#define payload_type_get_avpf_params(pt) ((pt)->avpf) ORTP_PUBLIC void payload_type_set_avpf_params(PayloadType *pt, PayloadTypeAvpfParams params); ORTP_PUBLIC bool_t payload_type_is_vbr(const PayloadType *pt); -#define payload_type_get_bitrate(pt) ((pt)->normal_bitrate) -#define payload_type_get_rate(pt) ((pt)->clock_rate) -#define payload_type_get_mime(pt) ((pt)->mime_type) +#define payload_type_get_bitrate(pt) ((pt)->normal_bitrate) +#define payload_type_get_rate(pt) ((pt)->clock_rate) +#define payload_type_get_mime(pt) ((pt)->mime_type) ORTP_PUBLIC bool_t fmtp_get_value(const char *fmtp, const char *param_name, char *result, size_t result_len); -#define payload_type_set_user_data(pt,p) (pt)->user_data=(p) -#define payload_type_get_user_data(pt) ((pt)->user_data) - +#define payload_type_set_user_data(pt, p) (pt)->user_data = (p) +#define payload_type_get_user_data(pt) ((pt)->user_data) /* some payload types */ /* audio */ diff --git a/include/ortp/port.h b/include/ortp/port.h index 068dc548..b3780bd9 100644 --- a/include/ortp/port.h +++ b/include/ortp/port.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -26,7 +26,7 @@ #if defined(_MSC_VER) #define ORTP_DEPRECATED __declspec(deprecated) #else -#define ORTP_DEPRECATED __attribute__ ((deprecated)) +#define ORTP_DEPRECATED __attribute__((deprecated)) #endif #endif @@ -40,22 +40,22 @@ /********************************/ #include -#include -#include -#include #include -#include -#include +#include #include +#include +#include #include +#include +#include #ifdef __linux__ #include #endif -#include -#include #include +#include +#include #if defined(_XOPEN_SOURCE_EXTENDED) || !defined(__hpux) #include #endif @@ -70,56 +70,54 @@ typedef pthread_mutex_t ortp_mutex_t; typedef pthread_cond_t ortp_cond_t; #ifdef __INTEL_COMPILER -#pragma warning(disable : 111) // statement is unreachable -#pragma warning(disable : 181) // argument is incompatible with corresponding format string conversion -#pragma warning(disable : 188) // enumerated type mixed with another type -#pragma warning(disable : 593) // variable "xxx" was set but never used -#pragma warning(disable : 810) // conversion from "int" to "unsigned short" may lose significant bits -#pragma warning(disable : 869) // parameter "xxx" was never referenced -#pragma warning(disable : 981) // operands are evaluated in unspecified order -#pragma warning(disable : 1418) // external function definition with no prior declaration -#pragma warning(disable : 1419) // external declaration in primary source file -#pragma warning(disable : 1469) // "cc" clobber ignored +#pragma warning(disable : 111) // statement is unreachable +#pragma warning(disable : 181) // argument is incompatible with corresponding format string conversion +#pragma warning(disable : 188) // enumerated type mixed with another type +#pragma warning(disable : 593) // variable "xxx" was set but never used +#pragma warning(disable : 810) // conversion from "int" to "unsigned short" may lose significant bits +#pragma warning(disable : 869) // parameter "xxx" was never referenced +#pragma warning(disable : 981) // operands are evaluated in unspecified order +#pragma warning(disable : 1418) // external function definition with no prior declaration +#pragma warning(disable : 1419) // external declaration in primary source file +#pragma warning(disable : 1469) // "cc" clobber ignored #endif #define ORTP_PUBLIC -#define ORTP_INLINE inline +#define ORTP_INLINE inline #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif int __ortp_thread_join(ortp_thread_t thread, void **ptr); -int __ortp_thread_create(ortp_thread_t *thread, pthread_attr_t *attr, void * (*routine)(void*), void *arg); +int __ortp_thread_create(ortp_thread_t *thread, pthread_attr_t *attr, void *(*routine)(void *), void *arg); unsigned long __ortp_thread_self(void); #ifdef __cplusplus } #endif -#define ortp_thread_create __ortp_thread_create -#define ortp_thread_join __ortp_thread_join -#define ortp_thread_self __ortp_thread_self -#define ortp_thread_exit pthread_exit -#define ortp_mutex_init pthread_mutex_init -#define ortp_mutex_lock pthread_mutex_lock -#define ortp_mutex_unlock pthread_mutex_unlock -#define ortp_mutex_destroy pthread_mutex_destroy -#define ortp_cond_init pthread_cond_init -#define ortp_cond_signal pthread_cond_signal -#define ortp_cond_broadcast pthread_cond_broadcast -#define ortp_cond_wait pthread_cond_wait -#define ortp_cond_destroy pthread_cond_destroy +#define ortp_thread_create __ortp_thread_create +#define ortp_thread_join __ortp_thread_join +#define ortp_thread_self __ortp_thread_self +#define ortp_thread_exit pthread_exit +#define ortp_mutex_init pthread_mutex_init +#define ortp_mutex_lock pthread_mutex_lock +#define ortp_mutex_unlock pthread_mutex_unlock +#define ortp_mutex_destroy pthread_mutex_destroy +#define ortp_cond_init pthread_cond_init +#define ortp_cond_signal pthread_cond_signal +#define ortp_cond_broadcast pthread_cond_broadcast +#define ortp_cond_wait pthread_cond_wait +#define ortp_cond_destroy pthread_cond_destroy -#define SOCKET_OPTION_VALUE void * -#define SOCKET_BUFFER void * +#define SOCKET_OPTION_VALUE void * +#define SOCKET_BUFFER void * #define getSocketError() strerror(errno) #define getSocketErrorCode() (errno) -#define ortp_gettimeofday(tv,tz) gettimeofday(tv,tz) -#define ortp_log10f(x) log10f(x) - +#define ortp_gettimeofday(tv, tz) gettimeofday(tv, tz) +#define ortp_log10f(x) log10f(x) #else /*********************************/ @@ -128,8 +126,8 @@ unsigned long __ortp_thread_self(void); #include #define _CRT_RAND_S -#include #include +#include #include #include #ifdef _MSC_VER @@ -142,7 +140,7 @@ unsigned long __ortp_thread_self(void); // See bctoolbox/include/port.h for WINAPI_PARTITION checker #if defined(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #define ORTP_WINDOWS_DESKTOP 1 -#elif defined (WINAPI_PARTITION_PC_APP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PC_APP) +#elif defined(WINAPI_PARTITION_PC_APP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PC_APP) #define ORTP_WINDOWS_DESKTOP 1 #define ORTP_WINDOWS_UWP 1 #elif defined(WINAPI_PARTITION_PHONE_APP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) @@ -157,9 +155,9 @@ unsigned long __ortp_thread_self(void); #define ORTP_PUBLIC #else #ifdef ORTP_EXPORTS -#define ORTP_PUBLIC __declspec(dllexport) +#define ORTP_PUBLIC __declspec(dllexport) #else -#define ORTP_PUBLIC __declspec(dllimport) +#define ORTP_PUBLIC __declspec(dllimport) #endif #endif #pragma push_macro("_WINSOCKAPI_") @@ -167,18 +165,18 @@ unsigned long __ortp_thread_self(void); #define _WINSOCKAPI_ #endif -typedef unsigned __int64 uint64_t; -typedef __int64 int64_t; -typedef unsigned short uint16_t; -typedef unsigned int uint32_t; -typedef int int32_t; -typedef unsigned char uint8_t; +typedef unsigned __int64 uint64_t; +typedef __int64 int64_t; +typedef unsigned short uint16_t; +typedef unsigned int uint32_t; +typedef int int32_t; +typedef unsigned char uint8_t; typedef __int16 int16_t; #else -#include /*provided by mingw32*/ #include +#include /*provided by mingw32*/ #define ORTP_PUBLIC -ORTP_PUBLIC char* strtok_r(char *str, const char *delim, char **nextp); +ORTP_PUBLIC char *strtok_r(char *str, const char *delim, char **nextp); #endif #define vsnprintf _vsnprintf @@ -193,69 +191,66 @@ typedef SRWLOCK ortp_mutex_t; #endif typedef HANDLE ortp_thread_t; -#define ortp_thread_create WIN_thread_create -#define ortp_thread_join WIN_thread_join -#define ortp_thread_self WIN_thread_self +#define ortp_thread_create WIN_thread_create +#define ortp_thread_join WIN_thread_join +#define ortp_thread_self WIN_thread_self #define ortp_thread_exit(arg) -#define ortp_mutex_init WIN_mutex_init -#define ortp_mutex_lock WIN_mutex_lock -#define ortp_mutex_unlock WIN_mutex_unlock -#define ortp_mutex_destroy WIN_mutex_destroy -#define ortp_cond_init WIN_cond_init -#define ortp_cond_signal WIN_cond_signal -#define ortp_cond_broadcast WIN_cond_broadcast -#define ortp_cond_wait WIN_cond_wait -#define ortp_cond_destroy WIN_cond_destroy - +#define ortp_mutex_init WIN_mutex_init +#define ortp_mutex_lock WIN_mutex_lock +#define ortp_mutex_unlock WIN_mutex_unlock +#define ortp_mutex_destroy WIN_mutex_destroy +#define ortp_cond_init WIN_cond_init +#define ortp_cond_signal WIN_cond_signal +#define ortp_cond_broadcast WIN_cond_broadcast +#define ortp_cond_wait WIN_cond_wait +#define ortp_cond_destroy WIN_cond_destroy #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif ORTP_PUBLIC int WIN_mutex_init(ortp_mutex_t *m, void *attr_unused); ORTP_PUBLIC int WIN_mutex_lock(ortp_mutex_t *mutex); ORTP_PUBLIC int WIN_mutex_unlock(ortp_mutex_t *mutex); ORTP_PUBLIC int WIN_mutex_destroy(ortp_mutex_t *mutex); -ORTP_PUBLIC int WIN_thread_create(ortp_thread_t *t, void *attr_unused, void *(*func)(void*), void *arg); +ORTP_PUBLIC int WIN_thread_create(ortp_thread_t *t, void *attr_unused, void *(*func)(void *), void *arg); ORTP_PUBLIC int WIN_thread_join(ortp_thread_t thread, void **unused); ORTP_PUBLIC unsigned long WIN_thread_self(void); ORTP_PUBLIC int WIN_cond_init(ortp_cond_t *cond, void *attr_unused); -ORTP_PUBLIC int WIN_cond_wait(ortp_cond_t * cond, ortp_mutex_t * mutex); -ORTP_PUBLIC int WIN_cond_signal(ortp_cond_t * cond); -ORTP_PUBLIC int WIN_cond_broadcast(ortp_cond_t * cond); -ORTP_PUBLIC int WIN_cond_destroy(ortp_cond_t * cond); +ORTP_PUBLIC int WIN_cond_wait(ortp_cond_t *cond, ortp_mutex_t *mutex); +ORTP_PUBLIC int WIN_cond_signal(ortp_cond_t *cond); +ORTP_PUBLIC int WIN_cond_broadcast(ortp_cond_t *cond); +ORTP_PUBLIC int WIN_cond_destroy(ortp_cond_t *cond); #ifdef __cplusplus } #endif -#define SOCKET_OPTION_VALUE char * -#define ORTP_INLINE __inline +#define SOCKET_OPTION_VALUE char * +#define ORTP_INLINE __inline #if defined(_WIN32_WCE) -#define ortp_log10f(x) (float)log10 ((double)x) +#define ortp_log10f(x) (float)log10((double)x) #ifdef assert - #undef assert +#undef assert #endif /*assert*/ -#define assert(exp) ((void)0) +#define assert(exp) ((void)0) #ifdef errno - #undef errno +#undef errno #endif /*errno*/ -#define errno GetLastError() +#define errno GetLastError() #ifdef strerror - #undef strerror +#undef strerror #endif /*strerror*/ -const char * ortp_strerror(DWORD value); +const char *ortp_strerror(DWORD value); #define strerror ortp_strerror - #else /*_WIN32_WCE*/ -#define ortp_log10f(x) log10f(x) +#define ortp_log10f(x) log10f(x) #endif @@ -263,7 +258,7 @@ const char * ortp_strerror(DWORD value); extern "C" { #endif - ORTP_PUBLIC const char *getWinSocketError(int error); +ORTP_PUBLIC const char *getWinSocketError(int error); #ifndef getSocketErrorCode #define getSocketErrorCode() WSAGetLastError() #endif @@ -275,10 +270,9 @@ extern "C" { #define F_OK 00 /* Visual Studio does not define F_OK */ #endif - -ORTP_PUBLIC int ortp_gettimeofday (struct timeval *tv, void* tz); +ORTP_PUBLIC int ortp_gettimeofday(struct timeval *tv, void *tz); #ifdef _WORKAROUND_MINGW32_BUGS -char * WSAAPI gai_strerror(int errnum); +char *WSAAPI gai_strerror(int errnum); #endif #ifdef __cplusplus @@ -296,39 +290,38 @@ typedef unsigned char bool_t; #define TRUE 1 #define FALSE 0 - -typedef struct ortpTimeSpec{ +typedef struct ortpTimeSpec { int64_t tv_sec; int64_t tv_nsec; -}ortpTimeSpec; +} ortpTimeSpec; #ifdef __cplusplus -extern "C"{ +extern "C" { #endif -ORTP_PUBLIC void* ortp_malloc(size_t sz); +ORTP_PUBLIC void *ortp_malloc(size_t sz); ORTP_PUBLIC void ortp_free(void *ptr); -ORTP_PUBLIC void* ortp_realloc(void *ptr, size_t sz); -ORTP_PUBLIC void* ortp_malloc0(size_t sz); -ORTP_PUBLIC char * ortp_strdup(const char *tmp); +ORTP_PUBLIC void *ortp_realloc(void *ptr, size_t sz); +ORTP_PUBLIC void *ortp_malloc0(size_t sz); +ORTP_PUBLIC char *ortp_strdup(const char *tmp); /*override the allocator with this method, to be called BEFORE ortp_init()*/ -typedef struct _OrtpMemoryFunctions{ +typedef struct _OrtpMemoryFunctions { void *(*malloc_fun)(size_t sz); void *(*realloc_fun)(void *ptr, size_t sz); void (*free_fun)(void *ptr); -}OrtpMemoryFunctions; +} OrtpMemoryFunctions; void ortp_set_memory_functions(OrtpMemoryFunctions *functions); -#define ortp_new(type,count) (type*)ortp_malloc(sizeof(type)*(count)) -#define ortp_new0(type,count) (type*)ortp_malloc0(sizeof(type)*(count)) +#define ortp_new(type, count) (type *)ortp_malloc(sizeof(type) * (count)) +#define ortp_new0(type, count) (type *)ortp_malloc0(sizeof(type) * (count)) ORTP_PUBLIC int close_socket(ortp_socket_t sock); ORTP_PUBLIC int set_non_blocking_socket(ortp_socket_t sock); ORTP_PUBLIC int set_blocking_socket(ortp_socket_t sock); -ORTP_PUBLIC char *ortp_strndup(const char *str,int n); +ORTP_PUBLIC char *ortp_strndup(const char *str, int n); #define ortp_strdup_printf bctbx_strdup_printf /*ORTP_PUBLIC char *ortp_strdup_printf(const char *fmt,...);*/ #define ortp_strdup_vprintf bctbx_strdup_vprintf @@ -363,7 +356,7 @@ typedef int ortp_pipe_t; * warning: on win32 ortp_server_pipe_accept_client() might return INVALID_HANDLE_VALUE without * any specific error, this happens when ortp_server_pipe_close() is called on another pipe. * This pipe api is not thread-safe. -*/ + */ #define ortp_server_pipe_accept_client(server) bctbx_server_pipe_accept_client(server) #define ortp_server_pipe_close(spipe) bctbx_server_pipe_close(spipe) @@ -387,19 +380,18 @@ typedef int ortp_pipe_t; #endif - #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(ORTP_STATIC) #ifdef ORTP_EXPORTS - #define ORTP_VAR_PUBLIC extern __declspec(dllexport) +#define ORTP_VAR_PUBLIC extern __declspec(dllexport) #else - #define ORTP_VAR_PUBLIC __declspec(dllimport) +#define ORTP_VAR_PUBLIC __declspec(dllimport) #endif #else - #define ORTP_VAR_PUBLIC extern +#define ORTP_VAR_PUBLIC extern #endif #ifndef IN6_IS_ADDR_MULTICAST -#define IN6_IS_ADDR_MULTICAST(i) (((uint8_t *) (i))[0] == 0xff) +#define IN6_IS_ADDR_MULTICAST(i) (((uint8_t *)(i))[0] == 0xff) #endif /*define __ios when we are compiling for ios. diff --git a/include/ortp/rtcp.h b/include/ortp/rtcp.h index f82e7328..596ec3c6 100644 --- a/include/ortp/rtcp.h +++ b/include/ortp/rtcp.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,10 +18,10 @@ * along with this program. If not, see . */ - #ifndef RTCP_H #define RTCP_H +#include "ortp/str_utils.h" #include #define RTCP_MAX_RECV_BUFSIZE 1500 @@ -32,7 +32,7 @@ #define RTCP_SSRC_FIELD_SIZE 4 #ifdef __cplusplus -extern "C"{ +extern "C" { #endif /* RTCP common header */ @@ -48,40 +48,36 @@ typedef enum { RTCP_XR = 207 } rtcp_type_t; - -typedef struct rtcp_common_header -{ +typedef struct rtcp_common_header { #ifdef ORTP_BIGENDIAN - uint16_t version:2; - uint16_t padbit:1; - uint16_t rc:5; - uint16_t packet_type:8; + uint16_t version : 2; + uint16_t padbit : 1; + uint16_t rc : 5; + uint16_t packet_type : 8; #else - uint16_t rc:5; - uint16_t padbit:1; - uint16_t version:2; - uint16_t packet_type:8; + uint16_t rc : 5; + uint16_t padbit : 1; + uint16_t version : 2; + uint16_t packet_type : 8; #endif - uint16_t length:16; + uint16_t length : 16; } rtcp_common_header_t; -#define rtcp_common_header_set_version(ch,v) (ch)->version=v -#define rtcp_common_header_set_padbit(ch,p) (ch)->padbit=p -#define rtcp_common_header_set_rc(ch,rc) (ch)->rc=rc -#define rtcp_common_header_set_packet_type(ch,pt) (ch)->packet_type=pt -#define rtcp_common_header_set_length(ch,l) (ch)->length=htons(l) +#define rtcp_common_header_set_version(ch, v) (ch)->version = v +#define rtcp_common_header_set_padbit(ch, p) (ch)->padbit = p +#define rtcp_common_header_set_rc(ch, rc) (ch)->rc = rc +#define rtcp_common_header_set_packet_type(ch, pt) (ch)->packet_type = pt +#define rtcp_common_header_set_length(ch, l) (ch)->length = htons(l) #define rtcp_common_header_get_version(ch) ((ch)->version) #define rtcp_common_header_get_padbit(ch) ((ch)->padbit) #define rtcp_common_header_get_rc(ch) ((ch)->rc) #define rtcp_common_header_get_packet_type(ch) ((ch)->packet_type) -#define rtcp_common_header_get_length(ch) ntohs((ch)->length) - +#define rtcp_common_header_get_length(ch) ntohs((ch)->length) /* RTCP SR or RR packets */ -typedef struct sender_info -{ +typedef struct sender_info { uint32_t ntp_timestamp_msw; uint32_t ntp_timestamp_lsw; uint32_t rtp_timestamp; @@ -90,64 +86,55 @@ typedef struct sender_info } sender_info_t; static ORTP_INLINE uint64_t sender_info_get_ntp_timestamp(const sender_info_t *si) { - return ((((uint64_t)ntohl(si->ntp_timestamp_msw)) << 32) + - ((uint64_t) ntohl(si->ntp_timestamp_lsw))); + return ((((uint64_t)ntohl(si->ntp_timestamp_msw)) << 32) + ((uint64_t)ntohl(si->ntp_timestamp_lsw))); } -#define sender_info_get_rtp_timestamp(si) ntohl((si)->rtp_timestamp) -#define sender_info_get_packet_count(si) \ - ntohl((si)->senders_packet_count) -#define sender_info_get_octet_count(si) \ - ntohl((si)->senders_octet_count) +#define sender_info_get_rtp_timestamp(si) ntohl((si)->rtp_timestamp) +#define sender_info_get_packet_count(si) ntohl((si)->senders_packet_count) +#define sender_info_get_octet_count(si) ntohl((si)->senders_octet_count) - -typedef struct report_block -{ +typedef struct report_block { uint32_t ssrc; - uint32_t fl_cnpl;/*fraction lost + cumulative number of packet lost*/ + uint32_t fl_cnpl; /*fraction lost + cumulative number of packet lost*/ uint32_t ext_high_seq_num_rec; /*extended highest sequence number received */ uint32_t interarrival_jitter; - uint32_t lsr; /*last SR */ + uint32_t lsr; /*last SR */ uint32_t delay_snc_last_sr; /*delay since last sr*/ } report_block_t; -static ORTP_INLINE uint32_t report_block_get_ssrc(const report_block_t * rb) { +static ORTP_INLINE uint32_t report_block_get_ssrc(const report_block_t *rb) { return ntohl(rb->ssrc); } -static ORTP_INLINE uint32_t report_block_get_high_ext_seq(const report_block_t * rb) { +static ORTP_INLINE uint32_t report_block_get_high_ext_seq(const report_block_t *rb) { return ntohl(rb->ext_high_seq_num_rec); } -static ORTP_INLINE uint32_t report_block_get_interarrival_jitter(const report_block_t * rb) { +static ORTP_INLINE uint32_t report_block_get_interarrival_jitter(const report_block_t *rb) { return ntohl(rb->interarrival_jitter); } -static ORTP_INLINE uint32_t report_block_get_last_SR_time(const report_block_t * rb) { +static ORTP_INLINE uint32_t report_block_get_last_SR_time(const report_block_t *rb) { return ntohl(rb->lsr); } -static ORTP_INLINE uint32_t report_block_get_last_SR_delay(const report_block_t * rb) { +static ORTP_INLINE uint32_t report_block_get_last_SR_delay(const report_block_t *rb) { return ntohl(rb->delay_snc_last_sr); } -static ORTP_INLINE uint32_t report_block_get_fraction_lost(const report_block_t * rb) { - return (ntohl(rb->fl_cnpl)>>24); +static ORTP_INLINE uint32_t report_block_get_fraction_lost(const report_block_t *rb) { + return (ntohl(rb->fl_cnpl) >> 24); } -static ORTP_INLINE int32_t report_block_get_cum_packet_lost(const report_block_t * rb){ +static ORTP_INLINE int32_t report_block_get_cum_packet_lost(const report_block_t *rb) { uint32_t cum_loss = (uint32_t)ntohl(rb->fl_cnpl); - if (((cum_loss>>23)&1)==0) - return (int32_t) (0x00FFFFFF & cum_loss); - else - return (int32_t)(0xFF000000 | (cum_loss-0xFFFFFF-1)); + if (((cum_loss >> 23) & 1) == 0) return (int32_t)(0x00FFFFFF & cum_loss); + else return (int32_t)(0xFF000000 | (cum_loss - 0xFFFFFF - 1)); } -static ORTP_INLINE void report_block_set_fraction_lost(report_block_t * rb, int fl){ - rb->fl_cnpl = (uint32_t)htonl( ((uint32_t)ntohl(rb->fl_cnpl) & 0xFFFFFF) | ((uint32_t)fl&0xFF)<<24); +static ORTP_INLINE void report_block_set_fraction_lost(report_block_t *rb, int fl) { + rb->fl_cnpl = (uint32_t)htonl(((uint32_t)ntohl(rb->fl_cnpl) & 0xFFFFFF) | ((uint32_t)fl & 0xFF) << 24); } -static ORTP_INLINE void report_block_set_cum_packet_lost(report_block_t * rb, int64_t cpl) { - uint32_t clamp = (uint32_t)((1<<24) + ((cpl>=0) ? (cpl>0x7FFFFF?0x7FFFFF:cpl) : (-cpl>0x800000?-0x800000:cpl))); +static ORTP_INLINE void report_block_set_cum_packet_lost(report_block_t *rb, int64_t cpl) { + uint32_t clamp = + (uint32_t)((1 << 24) + ((cpl >= 0) ? (cpl > 0x7FFFFF ? 0x7FFFFF : cpl) : (-cpl > 0x800000 ? -0x800000 : cpl))); - rb->fl_cnpl=htonl( - (ntohl(rb->fl_cnpl) & 0xFF000000) | - (cpl >= 0 ? clamp&0x7FFFFF : clamp|0x800000) - ); + rb->fl_cnpl = htonl((ntohl(rb->fl_cnpl) & 0xFF000000) | (cpl >= 0 ? clamp & 0x7FFFFF : clamp | 0x800000)); } /* SDES packets */ @@ -166,17 +153,14 @@ typedef enum { RTCP_SDES_MAX = 11 } rtcp_sdes_type_t; -typedef struct sdes_chunk -{ +typedef struct sdes_chunk { uint32_t csrc; } sdes_chunk_t; - -#define sdes_chunk_get_ssrc(m) ntohl(((sdes_chunk_t*)((m)->b_rptr))->csrc) +#define sdes_chunk_get_ssrc(m) ntohl(((sdes_chunk_t *)((m)->b_rptr))->csrc) #define sdes_chunk_get_csrc(c) ntohl((c)->csrc) -typedef struct sdes_item -{ +typedef struct sdes_item { uint8_t item_type; uint8_t len; char content[1]; @@ -189,21 +173,18 @@ typedef struct sdes_item /* RTCP bye packet */ -typedef struct rtcp_bye_reason -{ +typedef struct rtcp_bye_reason { uint8_t len; char content[1]; } rtcp_bye_reason_t; -typedef struct rtcp_bye -{ +typedef struct rtcp_bye { rtcp_common_header_t ch; - uint32_t ssrc[1]; /* the bye may contain several ssrc/csrc */ + uint32_t ssrc[1]; /* the bye may contain several ssrc/csrc */ } rtcp_bye_t; #define RTCP_BYE_HEADER_SIZE sizeof(rtcp_bye_t) #define RTCP_BYE_REASON_MAX_STRING_SIZE 255 - /* RTCP XR packet */ #define RTCP_XR_VOIP_METRICS_CONFIG_PLC_STD ((1 << 7) | (1 << 6)) @@ -298,11 +279,7 @@ typedef struct rtcp_xr_voip_metrics_report_block { #define MIN_RTCP_XR_PACKET_SIZE (sizeof(rtcp_xr_header_t) + 4) /* RTCP FB packet */ -typedef enum { - RTCP_RTPFB_NACK = 1, - RTCP_RTPFB_TMMBR = 3, - RTCP_RTPFB_TMMBN = 4 -} rtcp_rtpfb_type_t; +typedef enum { RTCP_RTPFB_NACK = 1, RTCP_RTPFB_TMMBR = 3, RTCP_RTPFB_TMMBN = 4 } rtcp_rtpfb_type_t; typedef enum { RTCP_PSFB_PLI = 1, @@ -333,18 +310,15 @@ typedef struct rtcp_fb_tmmbr_fci { } rtcp_fb_tmmbr_fci_t; #define rtcp_fb_tmmbr_fci_get_ssrc(tmmbr) ntohl((tmmbr)->ssrc) -#define rtcp_fb_tmmbr_fci_get_mxtbr_exp(tmmbr) \ - ((uint8_t)((ntohl((tmmbr)->value) >> 26) & 0x0000003F)) -#define rtcp_fb_tmmbr_fci_set_mxtbr_exp(tmmbr, mxtbr_exp) \ - ((tmmbr)->value) = htonl((ntohl((tmmbr)->value) & 0x03FFFFFF) | (((mxtbr_exp) & 0x0000003F) << 26)) -#define rtcp_fb_tmmbr_fci_get_mxtbr_mantissa(tmmbr) \ - ((uint32_t)((ntohl((tmmbr)->value) >> 9) & 0x0001FFFF)) -#define rtcp_fb_tmmbr_fci_set_mxtbr_mantissa(tmmbr, mxtbr_mantissa) \ - ((tmmbr)->value) = htonl((ntohl((tmmbr)->value) & 0xFC0001FF) | (((mxtbr_mantissa) & 0x0001FFFF) << 9)) -#define rtcp_fb_tmmbr_fci_get_measured_overhead(tmmbr) \ - ((uint16_t)(ntohl((tmmbr)->value) & 0x000001FF)) -#define rtcp_fb_tmmbr_fci_set_measured_overhead(tmmbr, measured_overhead) \ - ((tmmbr)->value) = htonl((ntohl((tmmbr)->value) & 0xFFFFFE00) | ((measured_overhead) & 0x000001FF)) +#define rtcp_fb_tmmbr_fci_get_mxtbr_exp(tmmbr) ((uint8_t)((ntohl((tmmbr)->value) >> 26) & 0x0000003F)) +#define rtcp_fb_tmmbr_fci_set_mxtbr_exp(tmmbr, mxtbr_exp) \ + ((tmmbr)->value) = htonl((ntohl((tmmbr)->value) & 0x03FFFFFF) | (((mxtbr_exp)&0x0000003F) << 26)) +#define rtcp_fb_tmmbr_fci_get_mxtbr_mantissa(tmmbr) ((uint32_t)((ntohl((tmmbr)->value) >> 9) & 0x0001FFFF)) +#define rtcp_fb_tmmbr_fci_set_mxtbr_mantissa(tmmbr, mxtbr_mantissa) \ + ((tmmbr)->value) = htonl((ntohl((tmmbr)->value) & 0xFC0001FF) | (((mxtbr_mantissa)&0x0001FFFF) << 9)) +#define rtcp_fb_tmmbr_fci_get_measured_overhead(tmmbr) ((uint16_t)(ntohl((tmmbr)->value) & 0x000001FF)) +#define rtcp_fb_tmmbr_fci_set_measured_overhead(tmmbr, measured_overhead) \ + ((tmmbr)->value) = htonl((ntohl((tmmbr)->value) & 0xFFFFFE00) | ((measured_overhead)&0x000001FF)) typedef struct rtcp_fb_fir_fci { uint32_t ssrc; @@ -360,18 +334,15 @@ typedef struct rtcp_fb_sli_fci { uint32_t value; } rtcp_fb_sli_fci_t; -#define rtcp_fb_sli_fci_get_first(fci) \ - ((uint16_t)((ntohl((fci)->value) >> 19) & 0x00001FFF)) -#define rtcp_fb_sli_fci_set_first(fci, first) \ - ((fci)->value) = htonl((ntohl((fci)->value) & 0x0007FFFF) | (((first) & 0x00001FFF) << 19)) -#define rtcp_fb_sli_fci_get_number(fci) \ - ((uint16_t)((ntohl((fci)->value) >> 6) & 0x00001FFF)) -#define rtcp_fb_sli_fci_set_number(fci, number) \ - ((fci)->value) = htonl((ntohl((fci)->value) & 0xFFF8003F) | (((number) & 0x00001FFF) << 6)) -#define rtcp_fb_sli_fci_get_picture_id(fci) \ - ((uint8_t)(ntohl((fci)->value) & 0x0000003F)) -#define rtcp_fb_sli_fci_set_picture_id(fci, picture_id) \ - ((fci)->value) = htonl((ntohl((fci)->value) & 0xFFFFFFC0) | ((picture_id) & 0x0000003F)) +#define rtcp_fb_sli_fci_get_first(fci) ((uint16_t)((ntohl((fci)->value) >> 19) & 0x00001FFF)) +#define rtcp_fb_sli_fci_set_first(fci, first) \ + ((fci)->value) = htonl((ntohl((fci)->value) & 0x0007FFFF) | (((first)&0x00001FFF) << 19)) +#define rtcp_fb_sli_fci_get_number(fci) ((uint16_t)((ntohl((fci)->value) >> 6) & 0x00001FFF)) +#define rtcp_fb_sli_fci_set_number(fci, number) \ + ((fci)->value) = htonl((ntohl((fci)->value) & 0xFFF8003F) | (((number)&0x00001FFF) << 6)) +#define rtcp_fb_sli_fci_get_picture_id(fci) ((uint8_t)(ntohl((fci)->value) & 0x0000003F)) +#define rtcp_fb_sli_fci_set_picture_id(fci, picture_id) \ + ((fci)->value) = htonl((ntohl((fci)->value) & 0xFFFFFFC0) | ((picture_id)&0x0000003F)) typedef struct rtcp_fb_rpsi_fci { uint8_t pb; @@ -387,20 +358,20 @@ typedef struct rtcp_fb_rpsi_fci { /* RTCP structs */ -typedef struct rtcp_sr{ +typedef struct rtcp_sr { rtcp_common_header_t ch; uint32_t ssrc; sender_info_t si; report_block_t rb[1]; } rtcp_sr_t; -typedef struct rtcp_rr{ +typedef struct rtcp_rr { rtcp_common_header_t ch; uint32_t ssrc; report_block_t rb[1]; } rtcp_rr_t; -typedef struct rtcp_app{ +typedef struct rtcp_app { rtcp_common_header_t ch; uint32_t ssrc; char name[4]; @@ -411,10 +382,8 @@ struct _RtpStream; ORTP_PUBLIC void rtp_session_rtcp_process_send(struct _RtpSession *s); ORTP_PUBLIC void rtp_session_rtcp_process_recv(struct _RtpSession *s); - #define RTCP_DEFAULT_REPORT_INTERVAL 5000 /* in milliseconds */ - /* packet parsing api */ /*return the size of the rtcp packet*/ @@ -422,26 +391,28 @@ ORTP_PUBLIC size_t rtcp_get_size(const mblk_t *m); /*in case of coumpound packet, set read pointer of m to the beginning of the next RTCP packet */ ORTP_PUBLIC bool_t rtcp_next_packet(mblk_t *m); -/* put the read pointer at the first RTCP packet of the compound packet (as before any previous calls ot rtcp_next_packet() */ +/* put the read pointer at the first RTCP packet of the compound packet (as before any previous calls ot + * rtcp_next_packet() */ ORTP_PUBLIC void rtcp_rewind(mblk_t *m); /* get common header*/ -ORTP_PUBLIC const rtcp_common_header_t * rtcp_get_common_header(const mblk_t *m); +ORTP_PUBLIC const rtcp_common_header_t *rtcp_get_common_header(const mblk_t *m); /*Sender Report accessors */ /* check if this packet is a SR and if it is correct */ ORTP_PUBLIC bool_t rtcp_is_SR(const mblk_t *m); ORTP_PUBLIC uint32_t rtcp_SR_get_ssrc(const mblk_t *m); -ORTP_PUBLIC const sender_info_t * rtcp_SR_get_sender_info(const mblk_t *m); -ORTP_PUBLIC const report_block_t * rtcp_SR_get_report_block(const mblk_t *m, int idx); +ORTP_PUBLIC const sender_info_t *rtcp_SR_get_sender_info(const mblk_t *m); +ORTP_PUBLIC const report_block_t *rtcp_SR_get_report_block(const mblk_t *m, int idx); /*Receiver report accessors*/ ORTP_PUBLIC bool_t rtcp_is_RR(const mblk_t *m); ORTP_PUBLIC uint32_t rtcp_RR_get_ssrc(const mblk_t *m); -ORTP_PUBLIC const report_block_t * rtcp_RR_get_report_block(const mblk_t *m,int idx); +ORTP_PUBLIC const report_block_t *rtcp_RR_get_report_block(const mblk_t *m, int idx); /*SDES accessors */ ORTP_PUBLIC bool_t rtcp_is_SDES(const mblk_t *m); -typedef void (*SdesItemFoundCallback)(void *user_data, uint32_t csrc, rtcp_sdes_type_t t, const char *content, uint8_t content_len); +typedef void (*SdesItemFoundCallback)( + void *user_data, uint32_t csrc, rtcp_sdes_type_t t, const char *content, uint8_t content_len); ORTP_PUBLIC void rtcp_sdes_parse(const mblk_t *m, SdesItemFoundCallback cb, void *user_data); /*BYE accessors */ @@ -505,8 +476,8 @@ ORTP_PUBLIC uint16_t rtcp_XR_voip_metrics_get_jb_abs_max(const mblk_t *m); /* RTCP RTPFB accessors */ ORTP_PUBLIC bool_t rtcp_is_RTPFB(const mblk_t *m); ORTP_PUBLIC rtcp_rtpfb_type_t rtcp_RTPFB_get_type(const mblk_t *m); -ORTP_PUBLIC rtcp_fb_generic_nack_fci_t * rtcp_RTPFB_generic_nack_get_fci(const mblk_t *m); -ORTP_PUBLIC rtcp_fb_tmmbr_fci_t * rtcp_RTPFB_tmmbr_get_fci(const mblk_t *m); +ORTP_PUBLIC rtcp_fb_generic_nack_fci_t *rtcp_RTPFB_generic_nack_get_fci(const mblk_t *m); +ORTP_PUBLIC rtcp_fb_tmmbr_fci_t *rtcp_RTPFB_tmmbr_get_fci(const mblk_t *m); /** * Return the maximum bitrate in bits / sec contained in the packet. * @@ -522,13 +493,12 @@ ORTP_PUBLIC bool_t rtcp_is_PSFB(const mblk_t *m); ORTP_PUBLIC rtcp_psfb_type_t rtcp_PSFB_get_type(const mblk_t *m); ORTP_PUBLIC uint32_t rtcp_PSFB_get_packet_sender_ssrc(const mblk_t *m); ORTP_PUBLIC uint32_t rtcp_PSFB_get_media_source_ssrc(const mblk_t *m); -ORTP_PUBLIC rtcp_fb_fir_fci_t * rtcp_PSFB_fir_get_fci(const mblk_t *m, unsigned int idx); -ORTP_PUBLIC rtcp_fb_sli_fci_t * rtcp_PSFB_sli_get_fci(const mblk_t *m, unsigned int idx); -ORTP_PUBLIC rtcp_fb_rpsi_fci_t * rtcp_PSFB_rpsi_get_fci(const mblk_t *m); +ORTP_PUBLIC rtcp_fb_fir_fci_t *rtcp_PSFB_fir_get_fci(const mblk_t *m, unsigned int idx); +ORTP_PUBLIC rtcp_fb_sli_fci_t *rtcp_PSFB_sli_get_fci(const mblk_t *m, unsigned int idx); +ORTP_PUBLIC rtcp_fb_rpsi_fci_t *rtcp_PSFB_rpsi_get_fci(const mblk_t *m); ORTP_PUBLIC uint16_t rtcp_PSFB_rpsi_get_fci_bit_string_len(const mblk_t *m); - -typedef struct OrtpLossRateEstimator{ +typedef struct OrtpLossRateEstimator { int min_packet_count_interval; uint64_t min_time_ms_interval; uint64_t last_estimate_time_ms; @@ -536,22 +506,24 @@ typedef struct OrtpLossRateEstimator{ int32_t last_ext_seq; float loss_rate; /** - * Total number of outgoing duplicate packets on last - * ortp_loss_rate_estimator_process_report_block iteration. - **/ + * Total number of outgoing duplicate packets on last + * ortp_loss_rate_estimator_process_report_block iteration. + **/ int64_t last_dup_packet_sent_count; /** - * Total number of outgoing unique packets on last - * ortp_loss_rate_estimator_process_report_block iteration. - **/ + * Total number of outgoing unique packets on last + * ortp_loss_rate_estimator_process_report_block iteration. + **/ int64_t last_packet_sent_count; -}OrtpLossRateEstimator; - - -ORTP_PUBLIC OrtpLossRateEstimator * ortp_loss_rate_estimator_new(int min_packet_count_interval, uint64_t min_time_ms_interval, struct _RtpSession *session); +} OrtpLossRateEstimator; -ORTP_PUBLIC void ortp_loss_rate_estimator_init(OrtpLossRateEstimator *obj, int min_packet_count_interval, uint64_t min_time_ms_interval, struct _RtpSession *session); +ORTP_PUBLIC OrtpLossRateEstimator * +ortp_loss_rate_estimator_new(int min_packet_count_interval, uint64_t min_time_ms_interval, struct _RtpSession *session); +ORTP_PUBLIC void ortp_loss_rate_estimator_init(OrtpLossRateEstimator *obj, + int min_packet_count_interval, + uint64_t min_time_ms_interval, + struct _RtpSession *session); /** * Process an incoming report block to compute loss rate percentage. It tries to compute @@ -569,8 +541,8 @@ ORTP_PUBLIC void ortp_loss_rate_estimator_init(OrtpLossRateEstimator *obj, int m * @return TRUE if a new loss rate estimation is ready, FALSE otherwise. */ ORTP_PUBLIC bool_t ortp_loss_rate_estimator_process_report_block(OrtpLossRateEstimator *obj, - const struct _RtpSession *session, - const report_block_t *rb); + const struct _RtpSession *session, + const report_block_t *rb); /** * Get the latest loss rate in percentage estimation computed. * diff --git a/include/ortp/rtp.h b/include/ortp/rtp.h index 496cd0bf..58473b9b 100644 --- a/include/ortp/rtp.h +++ b/include/ortp/rtp.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,7 +18,6 @@ * along with this program. If not, see . */ - #ifndef RTP_H #define RTP_H @@ -28,29 +27,27 @@ #define IPMAXLEN 20 #define UDP_MAX_SIZE 1500 #define RTP_FIXED_HEADER_SIZE 12 -#define RTP_DEFAULT_JITTER_TIME 80 /*miliseconds*/ -#define RTP_DEFAULT_MULTICAST_TTL 5 /*hops*/ -#define RTP_DEFAULT_MULTICAST_LOOPBACK 0 /*false*/ -#define RTP_DEFAULT_DSCP 0x00 /*best effort*/ +#define RTP_DEFAULT_JITTER_TIME 80 /*miliseconds*/ +#define RTP_DEFAULT_MULTICAST_TTL 5 /*hops*/ +#define RTP_DEFAULT_MULTICAST_LOOPBACK 0 /*false*/ +#define RTP_DEFAULT_DSCP 0x00 /*best effort*/ #define RTP_MAX_MIXER_TO_CLIENT_AUDIO_LEVEL 15 /* 15 because we can only put 15 csrc in a rtp packet */ - -typedef struct rtp_header -{ +typedef struct rtp_header { #ifdef ORTP_BIGENDIAN - uint16_t version:2; - uint16_t padbit:1; - uint16_t extbit:1; - uint16_t cc:4; - uint16_t markbit:1; - uint16_t paytype:7; + uint16_t version : 2; + uint16_t padbit : 1; + uint16_t extbit : 1; + uint16_t cc : 4; + uint16_t markbit : 1; + uint16_t paytype : 7; #else - uint16_t cc:4; - uint16_t extbit:1; - uint16_t padbit:1; - uint16_t version:2; - uint16_t paytype:7; - uint16_t markbit:1; + uint16_t cc : 4; + uint16_t extbit : 1; + uint16_t padbit : 1; + uint16_t version : 2; + uint16_t paytype : 7; + uint16_t markbit : 1; #endif uint16_t seq_number; uint32_t timestamp; @@ -58,31 +55,30 @@ typedef struct rtp_header uint32_t csrc[16]; } rtp_header_t; -typedef struct rtp_stats -{ - uint64_t packet_sent; /*number of outgoing packets */ - uint64_t packet_dup_sent; /*number of outgoing duplicate packets */ - uint64_t sent; /* outgoing total bytes (excluding IP header) */ - uint64_t packet_recv; /* number of incoming packets */ - uint64_t packet_dup_recv; /* number of incoming duplicate packets */ - uint64_t recv; /* incoming bytes of payload and delivered in time to the application */ - uint64_t hw_recv; /* incoming bytes of payload */ - uint64_t outoftime; /* number of incoming packets that were received too late */ - int64_t cum_packet_loss; /* cumulative number of incoming packet lost */ - uint64_t bad; /* incoming packets that did not appear to be RTP */ - uint64_t discarded; /* incoming packets discarded because the queue exceeds its max size */ - uint64_t sent_rtcp_packets; /* outgoing RTCP packets counter (only packets that embed a report block are considered) */ - uint64_t recv_rtcp_packets; /* incoming RTCP packets counter (only packets that embed a report block are considered) */ +typedef struct rtp_stats { + uint64_t packet_sent; /*number of outgoing packets */ + uint64_t packet_dup_sent; /*number of outgoing duplicate packets */ + uint64_t sent; /* outgoing total bytes (excluding IP header) */ + uint64_t packet_recv; /* number of incoming packets */ + uint64_t packet_dup_recv; /* number of incoming duplicate packets */ + uint64_t recv; /* incoming bytes of payload and delivered in time to the application */ + uint64_t hw_recv; /* incoming bytes of payload */ + uint64_t outoftime; /* number of incoming packets that were received too late */ + int64_t cum_packet_loss; /* cumulative number of incoming packet lost */ + uint64_t bad; /* incoming packets that did not appear to be RTP */ + uint64_t discarded; /* incoming packets discarded because the queue exceeds its max size */ + uint64_t + sent_rtcp_packets; /* outgoing RTCP packets counter (only packets that embed a report block are considered) */ + uint64_t + recv_rtcp_packets; /* incoming RTCP packets counter (only packets that embed a report block are considered) */ } rtp_stats_t; - -typedef struct jitter_stats -{ - uint32_t jitter; /* interarrival jitter at last emitted sender report */ - uint32_t max_jitter; /* biggest interarrival jitter (value in stream clock unit) */ - uint64_t sum_jitter; /* sum of all interarrival jitter (value in stream clock unit) */ - uint64_t max_jitter_ts; /* date (in ms since Epoch) of the biggest interarrival jitter */ - float jitter_buffer_size_ms;/* mean jitter buffer size in milliseconds.*/ +typedef struct jitter_stats { + uint32_t jitter; /* interarrival jitter at last emitted sender report */ + uint32_t max_jitter; /* biggest interarrival jitter (value in stream clock unit) */ + uint64_t sum_jitter; /* sum of all interarrival jitter (value in stream clock unit) */ + uint64_t max_jitter_ts; /* date (in ms since Epoch) of the biggest interarrival jitter */ + float jitter_buffer_size_ms; /* mean jitter buffer size in milliseconds.*/ } jitter_stats_t; /* MAX is 15 because we use 1-byte header */ @@ -100,63 +96,61 @@ typedef struct rtp_audio_level { int dbov; } rtp_audio_level_t; -#define RTP_FRAME_MARKER_START (1 << 7) -#define RTP_FRAME_MARKER_END (1 << 6) -#define RTP_FRAME_MARKER_INDEPENDENT (1 << 5) -#define RTP_FRAME_MARKER_DISCARDABLE (1 << 4) +#define RTP_FRAME_MARKER_START (1 << 7) +#define RTP_FRAME_MARKER_END (1 << 6) +#define RTP_FRAME_MARKER_INDEPENDENT (1 << 5) +#define RTP_FRAME_MARKER_DISCARDABLE (1 << 4) -#define RTP_TIMESTAMP_IS_NEWER_THAN(ts1, ts2) \ - ((uint32_t)((uint32_t)(ts1) - (uint32_t)(ts2)) < ((uint32_t)1 << 31)) +#define RTP_TIMESTAMP_IS_NEWER_THAN(ts1, ts2) ((uint32_t)((uint32_t)(ts1) - (uint32_t)(ts2)) < ((uint32_t)1 << 31)) -#define RTP_TIMESTAMP_IS_STRICTLY_NEWER_THAN(ts1, ts2) \ +#define RTP_TIMESTAMP_IS_STRICTLY_NEWER_THAN(ts1, ts2) \ (((uint32_t)((uint32_t)(ts1) - (uint32_t)(ts2)) < ((uint32_t)1 << 31)) && (ts1) != (ts2)) -#define RTP_SEQ_IS_STRICTLY_GREATER_THAN(seq1, seq2) \ +#define RTP_SEQ_IS_STRICTLY_GREATER_THAN(seq1, seq2) \ (((uint16_t)((uint16_t)(seq1) - (uint16_t)(seq2)) < ((uint16_t)1 << 15)) && (seq1) != (seq2)) -#define TIME_IS_NEWER_THAN(t1,t2) RTP_TIMESTAMP_IS_NEWER_THAN(t1,t2) - -#define TIME_IS_STRICTLY_NEWER_THAN(t1,t2) RTP_TIMESTAMP_IS_STRICTLY_NEWER_THAN(t1,t2) +#define TIME_IS_NEWER_THAN(t1, t2) RTP_TIMESTAMP_IS_NEWER_THAN(t1, t2) +#define TIME_IS_STRICTLY_NEWER_THAN(t1, t2) RTP_TIMESTAMP_IS_STRICTLY_NEWER_THAN(t1, t2) #ifdef __cplusplus -extern "C"{ +extern "C" { #endif /* packet api */ /* the first argument is a rtp_header_t */ -#define rtp_header_set_seqnumber(hdr,seq) (hdr)->seq_number=(htons(seq)) -#define rtp_header_set_timestamp(hdr,ts) (hdr)->timestamp=(htonl(ts)) -#define rtp_header_set_ssrc(hdr,_ssrc) (hdr)->ssrc=(htonl(_ssrc)) +#define rtp_header_set_seqnumber(hdr, seq) (hdr)->seq_number = (htons(seq)) +#define rtp_header_set_timestamp(hdr, ts) (hdr)->timestamp = (htonl(ts)) +#define rtp_header_set_ssrc(hdr, _ssrc) (hdr)->ssrc = (htonl(_ssrc)) ORTP_PUBLIC void rtp_header_add_csrc(rtp_header_t *hdr, uint32_t csrc); -#define rtp_header_get_seqnumber(hdr) (ntohs((hdr)->seq_number)) -#define rtp_header_get_timestamp(hdr) (ntohl((hdr)->timestamp)) -#define rtp_header_get_ssrc(hdr) (ntohl((hdr)->ssrc)) -#define rtp_header_get_csrc(hdr, idx) (ntohl((hdr)->csrc[idx])) +#define rtp_header_get_seqnumber(hdr) (ntohs((hdr)->seq_number)) +#define rtp_header_get_timestamp(hdr) (ntohl((hdr)->timestamp)) +#define rtp_header_get_ssrc(hdr) (ntohl((hdr)->ssrc)) +#define rtp_header_get_csrc(hdr, idx) (ntohl((hdr)->csrc[idx])) /* the first argument is a mblk_t. The header is supposed to be not splitted */ -#define rtp_set_version(mp,value) ((rtp_header_t*)((mp)->b_rptr))->version=(value) -#define rtp_set_padbit(mp,value) ((rtp_header_t*)((mp)->b_rptr))->padbit=(value) -#define rtp_set_extbit(mp,value) ((rtp_header_t*)((mp)->b_rptr))->extbit=(value) -#define rtp_set_cc(mp,value) ((rtp_header_t*)((mp)->b_rptr))->cc=(value) -#define rtp_set_markbit(mp,value) ((rtp_header_t*)((mp)->b_rptr))->markbit=(value) -#define rtp_set_payload_type(mp,pt) ((rtp_header_t*)((mp)->b_rptr))->paytype=(pt) -#define rtp_set_seqnumber(mp,seq) rtp_header_set_seqnumber((rtp_header_t*)((mp)->b_rptr),(seq)) -#define rtp_set_timestamp(mp,ts) rtp_header_set_timestamp((rtp_header_t*)((mp)->b_rptr),(ts)) -#define rtp_set_ssrc(mp,_ssrc) rtp_header_set_ssrc((rtp_header_t*)((mp)->b_rptr),(_ssrc)) +#define rtp_set_version(mp, value) ((rtp_header_t *)((mp)->b_rptr))->version = (value) +#define rtp_set_padbit(mp, value) ((rtp_header_t *)((mp)->b_rptr))->padbit = (value) +#define rtp_set_extbit(mp, value) ((rtp_header_t *)((mp)->b_rptr))->extbit = (value) +#define rtp_set_cc(mp, value) ((rtp_header_t *)((mp)->b_rptr))->cc = (value) +#define rtp_set_markbit(mp, value) ((rtp_header_t *)((mp)->b_rptr))->markbit = (value) +#define rtp_set_payload_type(mp, pt) ((rtp_header_t *)((mp)->b_rptr))->paytype = (pt) +#define rtp_set_seqnumber(mp, seq) rtp_header_set_seqnumber((rtp_header_t *)((mp)->b_rptr), (seq)) +#define rtp_set_timestamp(mp, ts) rtp_header_set_timestamp((rtp_header_t *)((mp)->b_rptr), (ts)) +#define rtp_set_ssrc(mp, _ssrc) rtp_header_set_ssrc((rtp_header_t *)((mp)->b_rptr), (_ssrc)) ORTP_PUBLIC void rtp_add_csrc(mblk_t *mp, uint32_t csrc); -#define rtp_get_version(mp) (((rtp_header_t*)((mp)->b_rptr))->version) -#define rtp_get_padbit(mp) (((rtp_header_t*)((mp)->b_rptr))->padbit) -#define rtp_get_markbit(mp) (((rtp_header_t*)((mp)->b_rptr))->markbit) -#define rtp_get_extbit(mp) (((rtp_header_t*)((mp)->b_rptr))->extbit) -#define rtp_get_timestamp(mp) rtp_header_get_timestamp((rtp_header_t*)((mp)->b_rptr)) -#define rtp_get_seqnumber(mp) rtp_header_get_seqnumber((rtp_header_t*)((mp)->b_rptr)) -#define rtp_get_payload_type(mp) (((rtp_header_t*)((mp)->b_rptr))->paytype) -#define rtp_get_ssrc(mp) rtp_header_get_ssrc((rtp_header_t*)((mp)->b_rptr)) -#define rtp_get_cc(mp) (((rtp_header_t*)((mp)->b_rptr))->cc) -#define rtp_get_csrc(mp, idx) rtp_header_get_csrc((rtp_header_t*)((mp)->b_rptr),(idx)) +#define rtp_get_version(mp) (((rtp_header_t *)((mp)->b_rptr))->version) +#define rtp_get_padbit(mp) (((rtp_header_t *)((mp)->b_rptr))->padbit) +#define rtp_get_markbit(mp) (((rtp_header_t *)((mp)->b_rptr))->markbit) +#define rtp_get_extbit(mp) (((rtp_header_t *)((mp)->b_rptr))->extbit) +#define rtp_get_timestamp(mp) rtp_header_get_timestamp((rtp_header_t *)((mp)->b_rptr)) +#define rtp_get_seqnumber(mp) rtp_header_get_seqnumber((rtp_header_t *)((mp)->b_rptr)) +#define rtp_get_payload_type(mp) (((rtp_header_t *)((mp)->b_rptr))->paytype) +#define rtp_get_ssrc(mp) rtp_header_get_ssrc((rtp_header_t *)((mp)->b_rptr)) +#define rtp_get_cc(mp) (((rtp_header_t *)((mp)->b_rptr))->cc) +#define rtp_get_csrc(mp, idx) rtp_header_get_csrc((rtp_header_t *)((mp)->b_rptr), (idx)) ORTP_PUBLIC int rtp_get_payload(mblk_t *packet, unsigned char **start); ORTP_PUBLIC int rtp_get_extheader(mblk_t *packet, uint16_t *profile, uint8_t **start_ext); @@ -170,9 +164,11 @@ ORTP_PUBLIC int rtp_get_extension_header(mblk_t *packet, int id, uint8_t **data) ORTP_PUBLIC void rtp_add_client_to_mixer_audio_level(mblk_t *packet, int id, bool_t voice_activity, int audio_level); ORTP_PUBLIC int rtp_get_client_to_mixer_audio_level(mblk_t *packet, int id, bool_t *voice_activity); -ORTP_PUBLIC void rtp_add_mixer_to_client_audio_level(mblk_t *packet, int id, size_t size, rtp_audio_level_t *audio_levels); -ORTP_PUBLIC void rtp_write_mixer_to_client_audio_level(mblk_t *packet, int id, size_t size, rtp_audio_level_t *audio_levels); -ORTP_PUBLIC int rtp_get_mixer_to_client_audio_level(mblk_t *packet, int id, rtp_audio_level_t* audio_levels); +ORTP_PUBLIC void +rtp_add_mixer_to_client_audio_level(mblk_t *packet, int id, size_t size, rtp_audio_level_t *audio_levels); +ORTP_PUBLIC void +rtp_write_mixer_to_client_audio_level(mblk_t *packet, int id, size_t size, rtp_audio_level_t *audio_levels); +ORTP_PUBLIC int rtp_get_mixer_to_client_audio_level(mblk_t *packet, int id, rtp_audio_level_t *audio_levels); /* Frame marking api */ ORTP_PUBLIC void rtp_add_frame_marker(mblk_t *packet, int id, uint8_t marker); diff --git a/include/ortp/rtpprofile.h b/include/ortp/rtpprofile.h index 501f8ccc..034cf1e5 100644 --- a/include/ortp/rtpprofile.h +++ b/include/ortp/rtpprofile.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -22,14 +22,14 @@ * \file rtpprofile.h * \brief Using and creating standart and custom RTP profiles * -**/ + **/ #ifndef RTPPROFILE_H #define RTPPROFILE_H #include #ifdef __cplusplus -extern "C"{ +extern "C" { #endif #define RTP_PROFILE_MAX_PAYLOADS 128 @@ -38,19 +38,17 @@ extern "C"{ * The RTP profile is a table RTP_PROFILE_MAX_PAYLOADS entries to make the matching * between RTP payload type number and the PayloadType that defines the type of * media. -**/ -struct _RtpProfile -{ + **/ +struct _RtpProfile { char *name; PayloadType *payload[RTP_PROFILE_MAX_PAYLOADS]; }; - typedef struct _RtpProfile RtpProfile; ORTP_VAR_PUBLIC RtpProfile av_profile; -#define rtp_profile_get_name(profile) (const char*)((profile)->name) +#define rtp_profile_get_name(profile) (const char *)((profile)->name) ORTP_PUBLIC void rtp_profile_set_payload(RtpProfile *prof, int idx, PayloadType *pt); @@ -59,9 +57,8 @@ ORTP_PUBLIC void rtp_profile_set_payload(RtpProfile *prof, int idx, PayloadType * *@param profile an RTP profile *@param index the payload type number -**/ -#define rtp_profile_clear_payload(profile,index) \ - rtp_profile_set_payload(profile,index,NULL) + **/ +#define rtp_profile_clear_payload(profile, index) rtp_profile_set_payload(profile, index, NULL) /* I prefer have this function inlined because it is very often called in the code */ /** @@ -71,31 +68,31 @@ ORTP_PUBLIC void rtp_profile_set_payload(RtpProfile *prof, int idx, PayloadType *@param prof an RTP profile (a #_RtpProfile object) *@param idx the payload type number *@return the payload description (a PayloadType object) -**/ -static ORTP_INLINE PayloadType * rtp_profile_get_payload(const RtpProfile *prof, int idx){ - if (idx<0 || idx>=RTP_PROFILE_MAX_PAYLOADS) { + **/ +static ORTP_INLINE PayloadType *rtp_profile_get_payload(const RtpProfile *prof, int idx) { + if (idx < 0 || idx >= RTP_PROFILE_MAX_PAYLOADS) { return NULL; } return prof->payload[idx]; } ORTP_PUBLIC void rtp_profile_clear_all(RtpProfile *prof); ORTP_PUBLIC void rtp_profile_set_name(RtpProfile *prof, const char *name); -ORTP_PUBLIC PayloadType * rtp_profile_get_payload_from_mime(RtpProfile *profile,const char *mime); -ORTP_PUBLIC PayloadType * rtp_profile_get_payload_from_rtpmap(RtpProfile *profile, const char *rtpmap); +ORTP_PUBLIC PayloadType *rtp_profile_get_payload_from_mime(RtpProfile *profile, const char *mime); +ORTP_PUBLIC PayloadType *rtp_profile_get_payload_from_rtpmap(RtpProfile *profile, const char *rtpmap); ORTP_PUBLIC int rtp_profile_get_payload_number_from_mime(RtpProfile *profile, const char *mime); ORTP_PUBLIC int rtp_profile_get_payload_number_from_mime_and_flag(RtpProfile *profile, const char *mime, int flag); ORTP_PUBLIC int rtp_profile_get_payload_number_from_rtpmap(RtpProfile *profile, const char *rtpmap); -ORTP_PUBLIC int rtp_profile_find_payload_number(RtpProfile *prof,const char *mime,int rate, int channels); -ORTP_PUBLIC PayloadType * rtp_profile_find_payload(RtpProfile *prof,const char *mime,int rate, int channels); -ORTP_PUBLIC int rtp_profile_move_payload(RtpProfile *prof,int oldpos,int newpos); +ORTP_PUBLIC int rtp_profile_find_payload_number(RtpProfile *prof, const char *mime, int rate, int channels); +ORTP_PUBLIC PayloadType *rtp_profile_find_payload(RtpProfile *prof, const char *mime, int rate, int channels); +ORTP_PUBLIC int rtp_profile_move_payload(RtpProfile *prof, int oldpos, int newpos); -ORTP_PUBLIC RtpProfile * rtp_profile_new(const char *name); +ORTP_PUBLIC RtpProfile *rtp_profile_new(const char *name); /* clone a profile, payload are not cloned */ -ORTP_PUBLIC RtpProfile * rtp_profile_clone(RtpProfile *prof); - +ORTP_PUBLIC RtpProfile *rtp_profile_clone(RtpProfile *prof); -/*clone a profile and its payloads (ie payload type are newly allocated, not reusing payload types of the reference profile) */ -ORTP_PUBLIC RtpProfile * rtp_profile_clone_full(RtpProfile *prof); +/*clone a profile and its payloads (ie payload type are newly allocated, not reusing payload types of the reference + * profile) */ +ORTP_PUBLIC RtpProfile *rtp_profile_clone_full(RtpProfile *prof); /* frees the profile and all its PayloadTypes*/ ORTP_PUBLIC void rtp_profile_destroy(RtpProfile *prof); diff --git a/include/ortp/rtpsignaltable.h b/include/ortp/rtpsignaltable.h index 7aca96d5..207919dd 100644 --- a/include/ortp/rtpsignaltable.h +++ b/include/ortp/rtpsignaltable.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -21,14 +21,13 @@ #ifndef rtpsignaltable_h #define rtpsignaltable_h -#define RTP_CALLBACK_TABLE_MAX_ENTRIES 5 +#define RTP_CALLBACK_TABLE_MAX_ENTRIES 5 typedef void (*RtpCallback)(struct _RtpSession *, void *arg1, void *arg2, void *arg3); -struct _RtpSignalTable -{ +struct _RtpSignalTable { RtpCallback callback[RTP_CALLBACK_TABLE_MAX_ENTRIES]; - void * user_data[RTP_CALLBACK_TABLE_MAX_ENTRIES]; + void *user_data[RTP_CALLBACK_TABLE_MAX_ENTRIES]; struct _RtpSession *session; const char *signal_name; int count; @@ -36,9 +35,9 @@ struct _RtpSignalTable typedef struct _RtpSignalTable RtpSignalTable; -void rtp_signal_table_init(RtpSignalTable *table,struct _RtpSession *session, const char *signal_name); +void rtp_signal_table_init(RtpSignalTable *table, struct _RtpSession *session, const char *signal_name); -int rtp_signal_table_add(RtpSignalTable *table,RtpCallback cb, void *user_data); +int rtp_signal_table_add(RtpSignalTable *table, RtpCallback cb, void *user_data); void rtp_signal_table_emit(RtpSignalTable *table); @@ -48,7 +47,6 @@ void rtp_signal_table_emit2(RtpSignalTable *table, void *arg); /* emit but with a third arg */ void rtp_signal_table_emit3(RtpSignalTable *table, void *arg1, void *arg2); -int rtp_signal_table_remove_by_callback(RtpSignalTable *table,RtpCallback cb); +int rtp_signal_table_remove_by_callback(RtpSignalTable *table, RtpCallback cb); #endif - diff --git a/include/ortp/sessionset.h b/include/ortp/sessionset.h index eecbafc6..ae824e27 100644 --- a/include/ortp/sessionset.h +++ b/include/ortp/sessionset.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -21,96 +21,85 @@ * \file sessionset.h * \brief Sending and receiving multiple streams together with only one thread. * -**/ + **/ #ifndef SESSIONSET_H #define SESSIONSET_H - #include #ifdef __cplusplus -extern "C"{ +extern "C" { #endif - -#if !defined(_WIN32) && !defined(_WIN32_WCE) +#if !defined(_WIN32) && !defined(_WIN32_WCE) /* UNIX */ #include #include #include -#define ORTP_FD_SET(d, s) FD_SET(d, s) -#define ORTP_FD_CLR(d, s) FD_CLR(d, s) -#define ORTP_FD_ISSET(d, s) FD_ISSET(d, s) -#define ORTP_FD_ZERO(s) FD_ZERO(s) +#define ORTP_FD_SET(d, s) FD_SET(d, s) +#define ORTP_FD_CLR(d, s) FD_CLR(d, s) +#define ORTP_FD_ISSET(d, s) FD_ISSET(d, s) +#define ORTP_FD_ZERO(s) FD_ZERO(s) typedef fd_set ortp_fd_set; - #else /* _WIN32 */ -#define ORTP_FD_ZERO(s) \ - do { \ - unsigned int __i; \ - ortp_fd_set *__arr = (s); \ - for (__i = 0; __i < sizeof (ortp_fd_set) / sizeof (ortp__fd_mask); ++__i) \ - ORTP__FDS_BITS (__arr)[__i] = 0; \ - } while (0) -#define ORTP_FD_SET(d, s) (ORTP__FDS_BITS (s)[ORTP__FDELT(d)] |= ORTP__FDMASK(d)) -#define ORTP_FD_CLR(d, s) (ORTP__FDS_BITS (s)[ORTP__FDELT(d)] &= ~ORTP__FDMASK(d)) -#define ORTP_FD_ISSET(d, s) ((ORTP__FDS_BITS (s)[ORTP__FDELT(d)] & ORTP__FDMASK(d)) != 0) - - +#define ORTP_FD_ZERO(s) \ + do { \ + unsigned int __i; \ + ortp_fd_set *__arr = (s); \ + for (__i = 0; __i < sizeof(ortp_fd_set) / sizeof(ortp__fd_mask); ++__i) \ + ORTP__FDS_BITS(__arr)[__i] = 0; \ + } while (0) +#define ORTP_FD_SET(d, s) (ORTP__FDS_BITS(s)[ORTP__FDELT(d)] |= ORTP__FDMASK(d)) +#define ORTP_FD_CLR(d, s) (ORTP__FDS_BITS(s)[ORTP__FDELT(d)] &= ~ORTP__FDMASK(d)) +#define ORTP_FD_ISSET(d, s) ((ORTP__FDS_BITS(s)[ORTP__FDELT(d)] & ORTP__FDMASK(d)) != 0) /* The fd_set member is required to be an array of longs. */ typedef long int ortp__fd_mask; - /* Number of bits per word of `fd_set' (some code assumes this is 32). */ #define ORTP__FD_SETSIZE 1024 /* It's easier to assume 8-bit bytes than to get CHAR_BIT. */ -#define ORTP__NFDBITS (8 * sizeof (ortp__fd_mask)) -#define ORTP__FDELT(d) ((d) / ORTP__NFDBITS) -#define ORTP__FDMASK(d) ((ortp__fd_mask) 1 << ((d) % ORTP__NFDBITS)) - +#define ORTP__NFDBITS (8 * sizeof(ortp__fd_mask)) +#define ORTP__FDELT(d) ((d) / ORTP__NFDBITS) +#define ORTP__FDMASK(d) ((ortp__fd_mask)1 << ((d) % ORTP__NFDBITS)) /* fd_set for select and pselect. */ -typedef struct - { - ortp__fd_mask fds_bits[ORTP__FD_SETSIZE / ORTP__NFDBITS]; -# define ORTP__FDS_BITS(set) ((set)->fds_bits) - } ortp_fd_set; - +typedef struct { + ortp__fd_mask fds_bits[ORTP__FD_SETSIZE / ORTP__NFDBITS]; +#define ORTP__FDS_BITS(set) ((set)->fds_bits) +} ortp_fd_set; #endif /*end _WIN32*/ -struct _SessionSet -{ +struct _SessionSet { ortp_fd_set rtpset; }; - typedef struct _SessionSet SessionSet; -#define session_set_init(ss) ORTP_FD_ZERO(&(ss)->rtpset) +#define session_set_init(ss) ORTP_FD_ZERO(&(ss)->rtpset) -ORTP_PUBLIC SessionSet * session_set_new(void); +ORTP_PUBLIC SessionSet *session_set_new(void); /** * This macro adds the rtp session to the set. * @param ss a set (SessionSet object) * @param rtpsession a RtpSession -**/ -#define session_set_set(ss,rtpsession) ORTP_FD_SET((rtpsession)->mask_pos,&(ss)->rtpset) + **/ +#define session_set_set(ss, rtpsession) ORTP_FD_SET((rtpsession)->mask_pos, &(ss)->rtpset) /** * This macro tests if the session is part of the set. 1 is returned if true, 0 else. *@param ss a set *@param rtpsession a rtp session * -**/ -#define session_set_is_set(ss,rtpsession) ORTP_FD_ISSET((rtpsession)->mask_pos,&(ss)->rtpset) + **/ +#define session_set_is_set(ss, rtpsession) ORTP_FD_ISSET((rtpsession)->mask_pos, &(ss)->rtpset) /** * Removes the session from the set. @@ -118,20 +107,19 @@ ORTP_PUBLIC SessionSet * session_set_new(void); *@param rtpsession a rtp session. * * -**/ -#define session_set_clr(ss,rtpsession) ORTP_FD_CLR((rtpsession)->mask_pos,&(ss)->rtpset) - -#define session_set_copy(dest,src) memcpy(&(dest)->rtpset,&(src)->rtpset,sizeof(ortp_fd_set)) + **/ +#define session_set_clr(ss, rtpsession) ORTP_FD_CLR((rtpsession)->mask_pos, &(ss)->rtpset) +#define session_set_copy(dest, src) memcpy(&(dest)->rtpset, &(src)->rtpset, sizeof(ortp_fd_set)) /** * Frees a SessionSet. -**/ + **/ ORTP_PUBLIC void session_set_destroy(SessionSet *set); - ORTP_PUBLIC int session_set_select(SessionSet *recvs, SessionSet *sends, SessionSet *errors); -ORTP_PUBLIC int session_set_timedselect(SessionSet *recvs, SessionSet *sends, SessionSet *errors, struct timeval *timeout); +ORTP_PUBLIC int +session_set_timedselect(SessionSet *recvs, SessionSet *sends, SessionSet *errors, struct timeval *timeout); #ifdef __cplusplus } diff --git a/include/ortp/str_utils.h b/include/ortp/str_utils.h index 0817c2b9..312bb679 100644 --- a/include/ortp/str_utils.h +++ b/include/ortp/str_utils.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -21,23 +21,28 @@ #ifndef STR_UTILS_H #define STR_UTILS_H - #include #if defined(ORTP_TIMESTAMP) #include #endif - #ifndef MIN -#define MIN(a,b) (((a)>(b)) ? (b) : (a)) +#define MIN(a, b) (((a) > (b)) ? (b) : (a)) #endif #ifndef MAX -#define MAX(a,b) (((a)>(b)) ? (a) : (b)) +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) #endif -#define return_if_fail(expr) if (!(expr)) {printf("%s:%i- assertion"#expr "failed\n",__FILE__,__LINE__); return;} -#define return_val_if_fail(expr,ret) if (!(expr)) {printf("%s:%i- assertion" #expr "failed\n",__FILE__,__LINE__); return (ret);} - +#define return_if_fail(expr) \ + if (!(expr)) { \ + printf("%s:%i- assertion" #expr "failed\n", __FILE__, __LINE__); \ + return; \ + } +#define return_val_if_fail(expr, ret) \ + if (!(expr)) { \ + printf("%s:%i- assertion" #expr "failed\n", __FILE__, __LINE__); \ + return (ret); \ + } typedef struct ortp_recv_addr { int family; @@ -54,8 +59,7 @@ typedef struct ortp_recv_addr_map { uint64_t ts; } ortp_recv_addr_map_t; -typedef struct msgb -{ +typedef struct msgb { struct msgb *b_prev; struct msgb *b_next; struct msgb *b_cont; @@ -65,25 +69,25 @@ typedef struct msgb uint32_t reserved1; uint32_t reserved2; struct timeval timestamp; - ortp_recv_addr_t recv_addr; /*contains the destination address of incoming packets, used for ICE processing*/ - struct sockaddr_storage net_addr; /*source address of incoming packet, or dest address of outgoing packet, used only by simulator and modifiers*/ - socklen_t net_addrlen; /*source (dest) address of incoming (outgoing) packet length used by simulator and modifiers*/ + ortp_recv_addr_t recv_addr; /*contains the destination address of incoming packets, used for ICE processing*/ + struct sockaddr_storage net_addr; /*source address of incoming packet, or dest address of outgoing packet, used only + by simulator and modifiers*/ + socklen_t + net_addrlen; /*source (dest) address of incoming (outgoing) packet length used by simulator and modifiers*/ uint8_t ttl_or_hl; } mblk_t; - // Data Block typedef struct datab { unsigned char *db_base; unsigned char *db_lim; - void (*db_freefn)(void*); - void * db_ref; // Atomic variable + void (*db_freefn)(void *); + void *db_ref; // Atomic variable } dblk_t; -typedef struct _queue -{ +typedef struct _queue { mblk_t _q_stopper; - int q_mcount; /*number of packet in the q */ + int q_mcount; /*number of packet in the q */ } queue_t; #ifdef __cplusplus @@ -91,25 +95,24 @@ extern "C" { #endif ORTP_PUBLIC dblk_t *dblk_alloc(size_t size); -ORTP_PUBLIC dblk_t *dblk_alloc2(uint8_t *buf, size_t size, void (*freefn)(void*)); +ORTP_PUBLIC dblk_t *dblk_alloc2(uint8_t *buf, size_t size, void (*freefn)(void *)); ORTP_PUBLIC void dblk_ref(dblk_t *d); ORTP_PUBLIC void dblk_unref(dblk_t *d); ORTP_PUBLIC int dblk_ref_value(dblk_t *db); -ORTP_PUBLIC unsigned char * dblk_base(dblk_t *db); -ORTP_PUBLIC unsigned char * dblk_lim(dblk_t *db); - +ORTP_PUBLIC unsigned char *dblk_base(dblk_t *db); +ORTP_PUBLIC unsigned char *dblk_lim(dblk_t *db); ORTP_PUBLIC void qinit(queue_t *q); ORTP_PUBLIC void putq(queue_t *q, mblk_t *m); -ORTP_PUBLIC mblk_t * getq(queue_t *q); +ORTP_PUBLIC mblk_t *getq(queue_t *q); -ORTP_PUBLIC void insq(queue_t *q,mblk_t *emp, mblk_t *mp); +ORTP_PUBLIC void insq(queue_t *q, mblk_t *emp, mblk_t *mp); ORTP_PUBLIC void remq(queue_t *q, mblk_t *mp); -ORTP_PUBLIC mblk_t * peekq(queue_t *q); +ORTP_PUBLIC mblk_t *peekq(queue_t *q); /* remove and free all messages in the q */ #define FLUSHALL 0 @@ -124,7 +127,7 @@ ORTP_PUBLIC mblk_t *allocb(size_t size, int unused); #define BPRI_MED 0 /* allocates a mblk_t, that points to a datab_t, that points to buf; buf will be freed using freefn */ -ORTP_PUBLIC mblk_t *esballoc(uint8_t *buf, size_t size, int pri, void (*freefn)(void*) ); +ORTP_PUBLIC mblk_t *esballoc(uint8_t *buf, size_t size, int pri, void (*freefn)(void *)); /* frees a mblk_t, and if the datab ref_count is 0, frees it and the buffer too */ ORTP_PUBLIC void freeb(mblk_t *m); @@ -137,16 +140,16 @@ ORTP_PUBLIC void freemsg(mblk_t *mp); ORTP_PUBLIC mblk_t *dupb(mblk_t *m); /* duplicates a complex mblk_t, buffer is not duplicated */ -ORTP_PUBLIC mblk_t *dupmsg(mblk_t* m); +ORTP_PUBLIC mblk_t *dupmsg(mblk_t *m); /* returns the size of data of a message */ ORTP_PUBLIC size_t msgdsize(const mblk_t *mp); /* concatenates all fragment of a complex message and crop or extend the buffer to the given length */ -ORTP_PUBLIC void msgpullup(mblk_t *mp,size_t len); +ORTP_PUBLIC void msgpullup(mblk_t *mp, size_t len); /* concatenates all fragment of a complex message and insert an empty buffer of the given length at the given offset */ -ORTP_PUBLIC void msgpullup_with_insert(mblk_t *mp,size_t offset, size_t len); +ORTP_PUBLIC void msgpullup_with_insert(mblk_t *mp, size_t offset, size_t len); /* duplicates a single message, but with buffer included */ ORTP_PUBLIC mblk_t *copyb(const mblk_t *mp); @@ -154,26 +157,27 @@ ORTP_PUBLIC mblk_t *copyb(const mblk_t *mp); /* duplicates a complex message with buffer included */ ORTP_PUBLIC mblk_t *copymsg(const mblk_t *mp); -ORTP_PUBLIC mblk_t * appendb(mblk_t *mp, const char *data, size_t size, bool_t pad); +ORTP_PUBLIC mblk_t *appendb(mblk_t *mp, const char *data, size_t size, bool_t pad); ORTP_PUBLIC void msgappend(mblk_t *mp, const char *data, size_t size, bool_t pad); ORTP_PUBLIC mblk_t *concatb(mblk_t *mp, mblk_t *newm); -/*Make sure the message has a unique owner, if not duplicate the underlying data buffer so that it can be changed without impacting others. - Note that in case of copy, the message will be un-fragmented, exactly the way msgpullup() does. Always returns mp.*/ -ORTP_PUBLIC mblk_t * msgown(mblk_t *mp); +/*Make sure the message has a unique owner, if not duplicate the underlying data buffer so that it can be changed + without impacting others. Note that in case of copy, the message will be un-fragmented, exactly the way msgpullup() + does. Always returns mp.*/ +ORTP_PUBLIC mblk_t *msgown(mblk_t *mp); -#define qempty(q) (&(q)->_q_stopper==(q)->_q_stopper.b_next) -#define qfirst(q) ((q)->_q_stopper.b_next!=&(q)->_q_stopper ? (q)->_q_stopper.b_next : NULL) +#define qempty(q) (&(q)->_q_stopper == (q)->_q_stopper.b_next) +#define qfirst(q) ((q)->_q_stopper.b_next != &(q)->_q_stopper ? (q)->_q_stopper.b_next : NULL) #define qbegin(q) ((q)->_q_stopper.b_next) -#define qlast(q) ((q)->_q_stopper.b_prev!=&(q)->_q_stopper ? (q)->_q_stopper.b_prev : NULL) -#define qend(q,mp) ((mp)==&(q)->_q_stopper) -#define qnext(q,mp) ((mp)->b_next) +#define qlast(q) ((q)->_q_stopper.b_prev != &(q)->_q_stopper ? (q)->_q_stopper.b_prev : NULL) +#define qend(q, mp) ((mp) == &(q)->_q_stopper) +#define qnext(q, mp) ((mp)->b_next) -typedef struct _msgb_allocator{ +typedef struct _msgb_allocator { queue_t q; int max_blocks; -}msgb_allocator_t; +} msgb_allocator_t; ORTP_PUBLIC void msgb_allocator_init(msgb_allocator_t *pa); /* Set a maximum number of blocks that can be managed by the allocator. @@ -183,7 +187,7 @@ ORTP_PUBLIC mblk_t *msgb_allocator_alloc(msgb_allocator_t *pa, size_t size); ORTP_PUBLIC void msgb_allocator_uninit(msgb_allocator_t *pa); ORTP_PUBLIC void ortp_recvaddr_to_sockaddr(ortp_recv_addr_t *recvaddr, struct sockaddr *addr, socklen_t *socklen); -ORTP_PUBLIC void ortp_sockaddr_to_recvaddr(const struct sockaddr * addr, ortp_recv_addr_t * recvaddr); +ORTP_PUBLIC void ortp_sockaddr_to_recvaddr(const struct sockaddr *addr, ortp_recv_addr_t *recvaddr); #ifdef __cplusplus } diff --git a/include/ortp/telephonyevents.h b/include/ortp/telephonyevents.h index c7fa26e1..a2111de9 100644 --- a/include/ortp/telephonyevents.h +++ b/include/ortp/telephonyevents.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,33 +18,30 @@ * along with this program. If not, see . */ -/** +/** * \file telephonyevents.h * \brief Receiving and sending telephone events (RFC2833) * -**/ - + **/ #ifndef TELEPHONYEVENTS_H #define TELEPHONYEVENTS_H #include - -struct _telephone_event -{ +struct _telephone_event { #ifdef ORTP_BIGENDIAN - uint32_t event:8; - uint32_t E:1; - uint32_t R:1; - uint32_t volume:6; - uint32_t duration:16; + uint32_t event : 8; + uint32_t E : 1; + uint32_t R : 1; + uint32_t volume : 6; + uint32_t duration : 16; #else - uint32_t event:8; - uint32_t volume:6; - uint32_t R:1; - uint32_t E:1; - uint32_t duration:16; + uint32_t event : 8; + uint32_t volume : 6; + uint32_t R : 1; + uint32_t E : 1; + uint32_t duration : 16; #endif }; @@ -54,20 +51,19 @@ typedef struct _telephone_event telephone_event_t; extern "C" { #endif -/* tell if the session supports telephony events. For this the telephony events payload_type - must be present in the rtp profile used by the session */ - -/* low level functions */ +/* tell if the session supports telephony events. For this the telephony events payload_type + must be present in the rtp profile used by the session */ + +/* low level functions */ ORTP_PUBLIC int rtp_session_telephone_events_supported(RtpSession *session); ORTP_PUBLIC int rtp_session_send_telephone_events_supported(RtpSession *session); ORTP_PUBLIC int rtp_session_recv_telephone_events_supported(RtpSession *session); -ORTP_PUBLIC mblk_t *rtp_session_create_telephone_event_packet(RtpSession *session, int start); +ORTP_PUBLIC mblk_t *rtp_session_create_telephone_event_packet(RtpSession *session, int start); -ORTP_PUBLIC int rtp_session_add_telephone_event(RtpSession *session, - mblk_t *packet, uint8_t event, int end, uint8_t volume, uint16_t duration); - -ORTP_PUBLIC int rtp_session_read_telephone_event(RtpSession *session, - mblk_t *packet,telephone_event_t **tab); +ORTP_PUBLIC int rtp_session_add_telephone_event( + RtpSession *session, mblk_t *packet, uint8_t event, int end, uint8_t volume, uint16_t duration); + +ORTP_PUBLIC int rtp_session_read_telephone_event(RtpSession *session, mblk_t *packet, telephone_event_t **tab); /* high level functions*/ ORTP_PUBLIC int rtp_session_send_dtmf(RtpSession *session, char dtmf, uint32_t userts); @@ -78,28 +74,27 @@ ORTP_PUBLIC void rtp_session_check_telephone_events(RtpSession *session, mblk_t #ifdef __cplusplus } #endif - + /* the size allocated for telephony events packets */ -#define TELEPHONY_EVENTS_ALLOCATED_SIZE (4*sizeof(telephone_event_t)) +#define TELEPHONY_EVENTS_ALLOCATED_SIZE (4 * sizeof(telephone_event_t)) /* list of named events */ -#define TEV_DTMF_0 (0) -#define TEV_DTMF_1 (1) -#define TEV_DTMF_2 (2) -#define TEV_DTMF_3 (3) -#define TEV_DTMF_4 (4) -#define TEV_DTMF_5 (5) -#define TEV_DTMF_6 (6) -#define TEV_DTMF_7 (7) -#define TEV_DTMF_8 (8) -#define TEV_DTMF_9 (9) -#define TEV_DTMF_STAR (10) -#define TEV_DTMF_POUND (11) -#define TEV_DTMF_A (12) -#define TEV_DTMF_B (13) -#define TEV_DTMF_C (14) -#define TEV_DTMF_D (15) -#define TEV_FLASH (16) - +#define TEV_DTMF_0 (0) +#define TEV_DTMF_1 (1) +#define TEV_DTMF_2 (2) +#define TEV_DTMF_3 (3) +#define TEV_DTMF_4 (4) +#define TEV_DTMF_5 (5) +#define TEV_DTMF_6 (6) +#define TEV_DTMF_7 (7) +#define TEV_DTMF_8 (8) +#define TEV_DTMF_9 (9) +#define TEV_DTMF_STAR (10) +#define TEV_DTMF_POUND (11) +#define TEV_DTMF_A (12) +#define TEV_DTMF_B (13) +#define TEV_DTMF_C (14) +#define TEV_DTMF_D (15) +#define TEV_FLASH (16) #endif diff --git a/include/ortp/utils.h b/include/ortp/utils.h index 044ea90a..1a62ecf4 100644 --- a/include/ortp/utils.h +++ b/include/ortp/utils.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -31,12 +31,12 @@ extern "C" { * Utility object to determine a maximum or minimum (but not both at the same * time), of a signal during a sliding period of time. */ -typedef struct _OrtpExtremum{ +typedef struct _OrtpExtremum { float current_extremum; float last_stable; uint64_t extremum_time; int period; -}OrtpExtremum; +} OrtpExtremum; ORTP_PUBLIC void ortp_extremum_reset(OrtpExtremum *obj); ORTP_PUBLIC void ortp_extremum_init(OrtpExtremum *obj, int period); /** @@ -47,8 +47,9 @@ ORTP_PUBLIC bool_t ortp_extremum_record_min(OrtpExtremum *obj, uint64_t curtime, ORTP_PUBLIC bool_t ortp_extremum_record_max(OrtpExtremum *obj, uint64_t curtime, float value); ORTP_PUBLIC float ortp_extremum_get_current(OrtpExtremum *obj); /** - * Unlike ortp_extremum_get_current() which can be very fluctuating, ortp_extremum_get_previous() returns the extremum found for the previous period. -**/ + * Unlike ortp_extremum_get_current() which can be very fluctuating, ortp_extremum_get_previous() returns the extremum + *found for the previous period. + **/ ORTP_PUBLIC float ortp_extremum_get_previous(OrtpExtremum *obj); /** @@ -59,36 +60,35 @@ ORTP_PUBLIC float ortp_extremum_get_previous(OrtpExtremum *obj); * Note: If noise is NOT white, the residue will be absorbed by one of the estimators. * It is an implementation of recursive least square algorithm, based on Kalman filter. */ -typedef struct _OrtpKalmanRLS{ +typedef struct _OrtpKalmanRLS { /* Unknown parameters to estimate */ double m, b; /* Gain matrix, must not be modified */ double P[2][2]; /** Forgetting factor in [94, .999]. Used when unknown parameters vary in time. **/ double lambda; -}OrtpKalmanRLS; +} OrtpKalmanRLS; ORTP_PUBLIC void ortp_kalman_rls_init(OrtpKalmanRLS *obj, double m0, double b0); ORTP_PUBLIC void ortp_kalman_rls_record(OrtpKalmanRLS *obj, double xmes, double ymes); - -typedef struct _OrtpBwEstimator{ +typedef struct _OrtpBwEstimator { float one_minus_alpha; float inv_step; float exp_constant; struct timeval last_packet_recv; float value; -}OrtpBwEstimator; +} OrtpBwEstimator; /** * Utility object to compute a sliding exponential mean bitrate. * @param obj the estimator structure to initialize * @param alpha the weight of previous estimation (between 0 and 1) * @param step a time constant in seconds representing the sampling period -**/ + **/ ORTP_PUBLIC void ortp_bw_estimator_init(OrtpBwEstimator *obj, float alpha, float step); -ORTP_PUBLIC void ortp_bw_estimator_packet_received (OrtpBwEstimator *obj, size_t bytes, const struct timeval *recv_time); +ORTP_PUBLIC void ortp_bw_estimator_packet_received(OrtpBwEstimator *obj, size_t bytes, const struct timeval *recv_time); ORTP_PUBLIC float ortp_bw_estimator_get_value(OrtpBwEstimator *obj); diff --git a/src/avprofile.c b/src/avprofile.c index 6a4e6e1c..b6535f36 100644 --- a/src/avprofile.c +++ b/src/avprofile.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,14 +18,13 @@ * along with this program. If not, see . */ - -#include -#include #include +#include #include +#include -char offset127=127; -char offset0xD5=(char)0xD5; +char offset127 = 127; +char offset0xD5 = (char)0xD5; char offset0[4] = {0x00, 0x00, 0x00, 0x00}; /* @@ -36,995 +35,813 @@ char offset0[4] = {0x00, 0x00, 0x00, 0x00}; */ #if defined(_ISOC99_SOURCE) || defined(__clang__) // ISO C99's tagged syntax -#define TYPE(val) .type=(val) -#define CLOCK_RATE(val) .clock_rate=(val) -#define BITS_PER_SAMPLE(val) .bits_per_sample=(val) -#define ZERO_PATTERN(val) .zero_pattern=(val) -#define PATTERN_LENGTH(val) .pattern_length=(val) -#define NORMAL_BITRATE(val) .normal_bitrate=(val) -#define MIME_TYPE(val) .mime_type=(val) -#define CHANNELS(val) .channels=(val) -#define RECV_FMTP(val) .recv_fmtp=(val) -#define SEND_FMTP(val) .send_fmtp=(val) -#define NO_AVPF .avpf={.features=PAYLOAD_TYPE_AVPF_NONE, .trr_interval=0} -#define AVPF(feat, intv) .avpf={.features=(feat), .trr_interval=(intv)} -#define FLAGS(val) .flags=(val) +#define TYPE(val) .type = (val) +#define CLOCK_RATE(val) .clock_rate = (val) +#define BITS_PER_SAMPLE(val) .bits_per_sample = (val) +#define ZERO_PATTERN(val) .zero_pattern = (val) +#define PATTERN_LENGTH(val) .pattern_length = (val) +#define NORMAL_BITRATE(val) .normal_bitrate = (val) +#define MIME_TYPE(val) .mime_type = (val) +#define CHANNELS(val) .channels = (val) +#define RECV_FMTP(val) .recv_fmtp = (val) +#define SEND_FMTP(val) .send_fmtp = (val) +#define NO_AVPF .avpf = {.features = PAYLOAD_TYPE_AVPF_NONE, .trr_interval = 0} +#define AVPF(feat, intv) .avpf = {.features = (feat), .trr_interval = (intv)} +#define FLAGS(val) .flags = (val) #elif defined(__GNUC__) // GCC's legacy tagged syntax (even old versions have it) -#define TYPE(val) type: (val) -#define CLOCK_RATE(val) clock_rate: (val) -#define BITS_PER_SAMPLE(val) bits_per_sample: (val) -#define ZERO_PATTERN(val) zero_pattern: (val) -#define PATTERN_LENGTH(val) pattern_length: (val) -#define NORMAL_BITRATE(val) normal_bitrate: (val) -#define MIME_TYPE(val) mime_type: (val) -#define CHANNELS(val) channels: (val) -#define RECV_FMTP(val) recv_fmtp: (val) -#define SEND_FMTP(val) send_fmtp: (val) -#define NO_AVPF avpf: {features: PAYLOAD_TYPE_AVPF_NONE, trr_interval: 0} -#define AVPF(feat, intv) avpf: {features: (feat), trr_interval: (intv)} -#define FLAGS(val) flags: (val) +#define TYPE(val) \ + type: \ + (val) +#define CLOCK_RATE(val) \ + clock_rate: \ + (val) +#define BITS_PER_SAMPLE(val) \ + bits_per_sample: \ + (val) +#define ZERO_PATTERN(val) \ + zero_pattern: \ + (val) +#define PATTERN_LENGTH(val) \ + pattern_length: \ + (val) +#define NORMAL_BITRATE(val) \ + normal_bitrate: \ + (val) +#define MIME_TYPE(val) \ + mime_type: \ + (val) +#define CHANNELS(val) \ + channels: \ + (val) +#define RECV_FMTP(val) \ + recv_fmtp: \ + (val) +#define SEND_FMTP(val) \ + send_fmtp: \ + (val) +#define NO_AVPF \ + avpf : { \ + features: \ + PAYLOAD_TYPE_AVPF_NONE, trr_interval : 0 \ + } +#define AVPF(feat, intv) \ + avpf : { \ + features: \ + (feat), trr_interval : (intv) \ + } +#define FLAGS(val) \ + flags: \ + (val) #else // No tagged syntax supported -#define TYPE(val) (val) -#define CLOCK_RATE(val) (val) -#define BITS_PER_SAMPLE(val) (val) -#define ZERO_PATTERN(val) (val) -#define PATTERN_LENGTH(val) (val) -#define NORMAL_BITRATE(val) (val) -#define MIME_TYPE(val) (val) -#define CHANNELS(val) (val) -#define RECV_FMTP(val) (val) -#define SEND_FMTP(val) (val) -#define NO_AVPF {PAYLOAD_TYPE_AVPF_NONE, 0} -#define AVPF(feat, intv) {(feat), FALSE, (intv)} -#define FLAGS(val) (val) +#define TYPE(val) (val) +#define CLOCK_RATE(val) (val) +#define BITS_PER_SAMPLE(val) (val) +#define ZERO_PATTERN(val) (val) +#define PATTERN_LENGTH(val) (val) +#define NORMAL_BITRATE(val) (val) +#define MIME_TYPE(val) (val) +#define CHANNELS(val) (val) +#define RECV_FMTP(val) (val) +#define SEND_FMTP(val) (val) +#define NO_AVPF \ + { PAYLOAD_TYPE_AVPF_NONE, 0 } +#define AVPF(feat, intv) \ + { (feat), FALSE, (intv) } +#define FLAGS(val) (val) #endif -PayloadType payload_type_pcmu8000={ - TYPE(PAYLOAD_AUDIO_CONTINUOUS), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(8), - ZERO_PATTERN( &offset127), - PATTERN_LENGTH(1), - NORMAL_BITRATE(64000), - MIME_TYPE("PCMU"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_pcma8000={ - TYPE(PAYLOAD_AUDIO_CONTINUOUS), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(8), - ZERO_PATTERN(&offset0xD5), - PATTERN_LENGTH(1), - NORMAL_BITRATE(64000), - MIME_TYPE("PCMA"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_pcm8000={ - TYPE(PAYLOAD_AUDIO_CONTINUOUS), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(16), - ZERO_PATTERN(offset0), - PATTERN_LENGTH(1), - NORMAL_BITRATE(128000), - MIME_TYPE("PCM"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_l16_mono={ - TYPE(PAYLOAD_AUDIO_CONTINUOUS), - CLOCK_RATE(44100), - BITS_PER_SAMPLE(16), - ZERO_PATTERN(offset0), - PATTERN_LENGTH(2), - NORMAL_BITRATE(705600), /* (44100 x 16bits per frame x 1 channel) */ - MIME_TYPE("L16"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_l16_stereo={ - TYPE(PAYLOAD_AUDIO_CONTINUOUS), - CLOCK_RATE(44100), - BITS_PER_SAMPLE(32), /* 16bits x 2 channels */ - ZERO_PATTERN(offset0), - PATTERN_LENGTH(4), - NORMAL_BITRATE(1411200), /* (44100 x 16bits per frame x 2 channels) */ - MIME_TYPE("L16"), - CHANNELS(2), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_lpc1016={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(2400), - MIME_TYPE("1016"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_gsm={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(13500), - MIME_TYPE("GSM"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_lpc={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(5600), /* 20ms / 14 octets per frame */ - MIME_TYPE("LPC"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_g7231={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(6300), - MIME_TYPE("G723"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_cn={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(8000), - MIME_TYPE("CN"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_g729={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(8000), - MIME_TYPE("G729"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_g7221={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(16000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(24000), - MIME_TYPE("G7221"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_g726_40={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(40000), - MIME_TYPE("G726-40"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_g726_32={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(32000), - MIME_TYPE("G726-32"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_g726_24={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(24000), - MIME_TYPE("G726-24"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_g726_16={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(16000), - MIME_TYPE("G726-16"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_aal2_g726_40={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(40000), - MIME_TYPE("AAL2-G726-40"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_aal2_g726_32={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(32000), - MIME_TYPE("AAL2-G726-32"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_aal2_g726_24={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(24000), - MIME_TYPE("AAL2-G726-24"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_aal2_g726_16={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(16000), - MIME_TYPE("AAL2-G726-16"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_mpv={ - TYPE(PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE("MPV"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - - -PayloadType payload_type_h261={ - TYPE(PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE("H261"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_h263={ - TYPE(PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE("H263"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_truespeech={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(8536), - MIME_TYPE("TSP0"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - +PayloadType payload_type_pcmu8000 = {TYPE(PAYLOAD_AUDIO_CONTINUOUS), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(8), + ZERO_PATTERN(&offset127), + PATTERN_LENGTH(1), + NORMAL_BITRATE(64000), + MIME_TYPE("PCMU"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_pcma8000 = {TYPE(PAYLOAD_AUDIO_CONTINUOUS), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(8), + ZERO_PATTERN(&offset0xD5), + PATTERN_LENGTH(1), + NORMAL_BITRATE(64000), + MIME_TYPE("PCMA"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_pcm8000 = {TYPE(PAYLOAD_AUDIO_CONTINUOUS), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(16), + ZERO_PATTERN(offset0), + PATTERN_LENGTH(1), + NORMAL_BITRATE(128000), + MIME_TYPE("PCM"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_l16_mono = {TYPE(PAYLOAD_AUDIO_CONTINUOUS), + CLOCK_RATE(44100), + BITS_PER_SAMPLE(16), + ZERO_PATTERN(offset0), + PATTERN_LENGTH(2), + NORMAL_BITRATE(705600), /* (44100 x 16bits per frame x 1 channel) */ + MIME_TYPE("L16"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_l16_stereo = {TYPE(PAYLOAD_AUDIO_CONTINUOUS), + CLOCK_RATE(44100), + BITS_PER_SAMPLE(32), /* 16bits x 2 channels */ + ZERO_PATTERN(offset0), + PATTERN_LENGTH(4), + NORMAL_BITRATE(1411200), /* (44100 x 16bits per frame x 2 channels) */ + MIME_TYPE("L16"), + CHANNELS(2), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_lpc1016 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(2400), + MIME_TYPE("1016"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_gsm = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(13500), + MIME_TYPE("GSM"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_lpc = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(5600), /* 20ms / 14 octets per frame */ + MIME_TYPE("LPC"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_g7231 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(6300), + MIME_TYPE("G723"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_cn = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(8000), + MIME_TYPE("CN"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_g729 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(8000), + MIME_TYPE("G729"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_g7221 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(16000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(24000), + MIME_TYPE("G7221"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_g726_40 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(40000), + MIME_TYPE("G726-40"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_g726_32 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(32000), + MIME_TYPE("G726-32"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_g726_24 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(24000), + MIME_TYPE("G726-24"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_g726_16 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(16000), + MIME_TYPE("G726-16"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_aal2_g726_40 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(40000), + MIME_TYPE("AAL2-G726-40"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_aal2_g726_32 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(32000), + MIME_TYPE("AAL2-G726-32"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_aal2_g726_24 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(24000), + MIME_TYPE("AAL2-G726-24"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_aal2_g726_16 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(16000), + MIME_TYPE("AAL2-G726-16"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_mpv = {TYPE(PAYLOAD_VIDEO), CLOCK_RATE(90000), BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), PATTERN_LENGTH(0), NORMAL_BITRATE(256000), + MIME_TYPE("MPV"), CHANNELS(0), RECV_FMTP(NULL), + SEND_FMTP(NULL), NO_AVPF, FLAGS(0)}; + +PayloadType payload_type_h261 = {TYPE(PAYLOAD_VIDEO), CLOCK_RATE(90000), BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), PATTERN_LENGTH(0), NORMAL_BITRATE(0), + MIME_TYPE("H261"), CHANNELS(0), RECV_FMTP(NULL), + SEND_FMTP(NULL), NO_AVPF, FLAGS(0)}; + +PayloadType payload_type_h263 = {TYPE(PAYLOAD_VIDEO), CLOCK_RATE(90000), BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), PATTERN_LENGTH(0), NORMAL_BITRATE(256000), + MIME_TYPE("H263"), CHANNELS(0), RECV_FMTP(NULL), + SEND_FMTP(NULL), NO_AVPF, FLAGS(0)}; + +PayloadType payload_type_truespeech = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(8536), + MIME_TYPE("TSP0"), + CHANNELS(0), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif RtpProfile av_profile; #ifdef __cplusplus } #endif - -void av_profile_init(RtpProfile *profile) -{ +void av_profile_init(RtpProfile *profile) { rtp_profile_clear_all(profile); - profile->name="AV profile"; - - rtp_profile_set_payload(profile,0,&payload_type_pcmu8000); - rtp_profile_set_payload(profile,1,&payload_type_lpc1016); - rtp_profile_set_payload(profile,3,&payload_type_gsm); - rtp_profile_set_payload(profile,7,&payload_type_lpc); - rtp_profile_set_payload(profile,4,&payload_type_g7231); - rtp_profile_set_payload(profile,8,&payload_type_pcma8000); - rtp_profile_set_payload(profile,9,&payload_type_g722); - rtp_profile_set_payload(profile,10,&payload_type_l16_stereo); - rtp_profile_set_payload(profile,11,&payload_type_l16_mono); - rtp_profile_set_payload(profile,13,&payload_type_cn); - rtp_profile_set_payload(profile,18,&payload_type_g729); - rtp_profile_set_payload(profile,31,&payload_type_h261); - rtp_profile_set_payload(profile,32,&payload_type_mpv); - rtp_profile_set_payload(profile,34,&payload_type_h263); - + profile->name = "AV profile"; + + rtp_profile_set_payload(profile, 0, &payload_type_pcmu8000); + rtp_profile_set_payload(profile, 1, &payload_type_lpc1016); + rtp_profile_set_payload(profile, 3, &payload_type_gsm); + rtp_profile_set_payload(profile, 7, &payload_type_lpc); + rtp_profile_set_payload(profile, 4, &payload_type_g7231); + rtp_profile_set_payload(profile, 8, &payload_type_pcma8000); + rtp_profile_set_payload(profile, 9, &payload_type_g722); + rtp_profile_set_payload(profile, 10, &payload_type_l16_stereo); + rtp_profile_set_payload(profile, 11, &payload_type_l16_mono); + rtp_profile_set_payload(profile, 13, &payload_type_cn); + rtp_profile_set_payload(profile, 18, &payload_type_g729); + rtp_profile_set_payload(profile, 31, &payload_type_h261); + rtp_profile_set_payload(profile, 32, &payload_type_mpv); + rtp_profile_set_payload(profile, 34, &payload_type_h263); } /* these are extra payload types that can be used dynamically */ -PayloadType payload_type_lpc1015={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(2400), - MIME_TYPE("1015"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_speex_nb={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(8000), /*not true: 8000 is the minimum*/ - MIME_TYPE("speex"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_bv16={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(16000),/* 5ms / 80 bits per frame */ - MIME_TYPE("BV16"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_speex_wb={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(16000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(28000), - MIME_TYPE("speex"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_speex_uwb={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(32000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(28000), - MIME_TYPE("speex"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_ilbc={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(13300), /* the minimum, with 30ms frames */ - MIME_TYPE("iLBC"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_amr={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(12200), - MIME_TYPE("AMR"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_amrwb={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(16000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(23850), - MIME_TYPE("AMR-WB"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_gsm_efr={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(12200), - MIME_TYPE ("GSM-EFR"), - CHANNELS(1) -}; - -PayloadType payload_type_mp4v={ - TYPE(PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE("MP4V-ES"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - AVPF(PAYLOAD_TYPE_AVPF_FIR | PAYLOAD_TYPE_AVPF_PLI, RTCP_DEFAULT_REPORT_INTERVAL), - FLAGS(0) -}; - - -PayloadType payload_type_evrc0={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE("EVRC0"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_evrcb0={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE("EVRCB0"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_h263_1998={ - TYPE(PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE("H263-1998"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_h263_2000={ - TYPE(PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE("H263-2000"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_theora={ - TYPE(PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE("theora"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_h264={ - TYPE(PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE("H264"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - AVPF(PAYLOAD_TYPE_AVPF_FIR | PAYLOAD_TYPE_AVPF_PLI, RTCP_DEFAULT_REPORT_INTERVAL), - FLAGS(PAYLOAD_TYPE_RTCP_FEEDBACK_ENABLED) -}; - -PayloadType payload_type_h265={ - TYPE(PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE("H265"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - AVPF(PAYLOAD_TYPE_AVPF_FIR | PAYLOAD_TYPE_AVPF_PLI, RTCP_DEFAULT_REPORT_INTERVAL), - FLAGS(PAYLOAD_TYPE_RTCP_FEEDBACK_ENABLED) -}; - -PayloadType payload_type_x_snow={ - TYPE(PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE("x-snow"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_jpeg={ - TYPE(PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE("JPEG"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_vp8={ - TYPE(PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(256000), - MIME_TYPE("VP8"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - AVPF(PAYLOAD_TYPE_AVPF_FIR | PAYLOAD_TYPE_AVPF_PLI | PAYLOAD_TYPE_AVPF_SLI | PAYLOAD_TYPE_AVPF_RPSI, RTCP_DEFAULT_REPORT_INTERVAL), - FLAGS(PAYLOAD_TYPE_RTCP_FEEDBACK_ENABLED) -}; - -PayloadType payload_type_t140={ - TYPE(PAYLOAD_TEXT), - CLOCK_RATE(1000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE("t140"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_t140_red={ - TYPE(PAYLOAD_TEXT), - CLOCK_RATE(1000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE("red"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_x_udpftp={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(1000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(0), - MIME_TYPE("x-udpftp"), - CHANNELS(0), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_g722={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(64000), - MIME_TYPE("G722"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_silk_nb={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(13000), - MIME_TYPE("SILK"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_silk_mb={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(12000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(15000), - MIME_TYPE("SILK"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_silk_wb={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(16000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(20000), - MIME_TYPE("SILK"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_silk_swb={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(24000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(30000), - MIME_TYPE("SILK"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_aaceld_16k={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(16000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(24000), - MIME_TYPE("mpeg4-generic"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_aaceld_22k={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(22050), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(32000), - MIME_TYPE("mpeg4-generic"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_aaceld_32k={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(32000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(48000), - MIME_TYPE("mpeg4-generic"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_aaceld_44k={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(44100), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(64000), - MIME_TYPE("mpeg4-generic"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_aaceld_48k={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(48000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(64000), - MIME_TYPE("mpeg4-generic"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_opus = { - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(48000), /*mandatory according to RFC*/ - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(20000), - MIME_TYPE("opus"), - CHANNELS(2), /*mandatory according to RFC*/ - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_isac = { - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(16000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(32000), - MIME_TYPE("iSAC"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(PAYLOAD_TYPE_IS_VBR) -}; - -PayloadType payload_type_codec2={ - TYPE(PAYLOAD_AUDIO_PACKETIZED), - CLOCK_RATE(8000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(3200), - MIME_TYPE("CODEC2"), - CHANNELS(1), - RECV_FMTP(NULL), - SEND_FMTP(NULL), - NO_AVPF, - FLAGS(0) -}; - -PayloadType payload_type_flexfec={ - TYPE(PAYLOAD_VIDEO), - CLOCK_RATE(90000), - BITS_PER_SAMPLE(0), - ZERO_PATTERN(NULL), - PATTERN_LENGTH(0), - NORMAL_BITRATE(3200), - MIME_TYPE("flexfec"), - CHANNELS(0), - RECV_FMTP("repair-window=200000;L=5;D=5"), - SEND_FMTP("repair-window=200000;L=5;D=5"), - NO_AVPF, - FLAGS(0) -}; \ No newline at end of file +PayloadType payload_type_lpc1015 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(2400), + MIME_TYPE("1015"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_speex_nb = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(8000), /*not true: 8000 is the minimum*/ + MIME_TYPE("speex"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_bv16 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(16000), /* 5ms / 80 bits per frame */ + MIME_TYPE("BV16"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_speex_wb = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(16000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(28000), + MIME_TYPE("speex"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_speex_uwb = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(32000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(28000), + MIME_TYPE("speex"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_ilbc = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(13300), /* the minimum, with 30ms frames */ + MIME_TYPE("iLBC"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_amr = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(12200), + MIME_TYPE("AMR"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_amrwb = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(16000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(23850), + MIME_TYPE("AMR-WB"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_gsm_efr = { + TYPE(PAYLOAD_AUDIO_PACKETIZED), CLOCK_RATE(8000), BITS_PER_SAMPLE(0), ZERO_PATTERN(NULL), PATTERN_LENGTH(0), + NORMAL_BITRATE(12200), MIME_TYPE("GSM-EFR"), CHANNELS(1)}; + +PayloadType payload_type_mp4v = {TYPE(PAYLOAD_VIDEO), + CLOCK_RATE(90000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(0), + MIME_TYPE("MP4V-ES"), + CHANNELS(0), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + AVPF(PAYLOAD_TYPE_AVPF_FIR | PAYLOAD_TYPE_AVPF_PLI, RTCP_DEFAULT_REPORT_INTERVAL), + FLAGS(0)}; + +PayloadType payload_type_evrc0 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(0), + MIME_TYPE("EVRC0"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_evrcb0 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(0), + MIME_TYPE("EVRCB0"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_h263_1998 = {TYPE(PAYLOAD_VIDEO), CLOCK_RATE(90000), BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), PATTERN_LENGTH(0), NORMAL_BITRATE(256000), + MIME_TYPE("H263-1998"), CHANNELS(0), RECV_FMTP(NULL), + SEND_FMTP(NULL), NO_AVPF, FLAGS(0)}; + +PayloadType payload_type_h263_2000 = {TYPE(PAYLOAD_VIDEO), CLOCK_RATE(90000), BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), PATTERN_LENGTH(0), NORMAL_BITRATE(0), + MIME_TYPE("H263-2000"), CHANNELS(0), RECV_FMTP(NULL), + SEND_FMTP(NULL), NO_AVPF, FLAGS(0)}; + +PayloadType payload_type_theora = {TYPE(PAYLOAD_VIDEO), CLOCK_RATE(90000), BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), PATTERN_LENGTH(0), NORMAL_BITRATE(256000), + MIME_TYPE("theora"), CHANNELS(0), RECV_FMTP(NULL), + SEND_FMTP(NULL), NO_AVPF, FLAGS(0)}; + +PayloadType payload_type_h264 = {TYPE(PAYLOAD_VIDEO), + CLOCK_RATE(90000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(256000), + MIME_TYPE("H264"), + CHANNELS(0), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + AVPF(PAYLOAD_TYPE_AVPF_FIR | PAYLOAD_TYPE_AVPF_PLI, RTCP_DEFAULT_REPORT_INTERVAL), + FLAGS(PAYLOAD_TYPE_RTCP_FEEDBACK_ENABLED)}; + +PayloadType payload_type_h265 = {TYPE(PAYLOAD_VIDEO), + CLOCK_RATE(90000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(256000), + MIME_TYPE("H265"), + CHANNELS(0), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + AVPF(PAYLOAD_TYPE_AVPF_FIR | PAYLOAD_TYPE_AVPF_PLI, RTCP_DEFAULT_REPORT_INTERVAL), + FLAGS(PAYLOAD_TYPE_RTCP_FEEDBACK_ENABLED)}; + +PayloadType payload_type_x_snow = {TYPE(PAYLOAD_VIDEO), CLOCK_RATE(90000), BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), PATTERN_LENGTH(0), NORMAL_BITRATE(256000), + MIME_TYPE("x-snow"), CHANNELS(0), RECV_FMTP(NULL), + SEND_FMTP(NULL), NO_AVPF, FLAGS(0)}; + +PayloadType payload_type_jpeg = {TYPE(PAYLOAD_VIDEO), CLOCK_RATE(90000), BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), PATTERN_LENGTH(0), NORMAL_BITRATE(256000), + MIME_TYPE("JPEG"), CHANNELS(0), RECV_FMTP(NULL), + SEND_FMTP(NULL), NO_AVPF, FLAGS(0)}; + +PayloadType payload_type_vp8 = { + TYPE(PAYLOAD_VIDEO), + CLOCK_RATE(90000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(256000), + MIME_TYPE("VP8"), + CHANNELS(0), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + AVPF(PAYLOAD_TYPE_AVPF_FIR | PAYLOAD_TYPE_AVPF_PLI | PAYLOAD_TYPE_AVPF_SLI | PAYLOAD_TYPE_AVPF_RPSI, + RTCP_DEFAULT_REPORT_INTERVAL), + FLAGS(PAYLOAD_TYPE_RTCP_FEEDBACK_ENABLED)}; + +PayloadType payload_type_t140 = { + TYPE(PAYLOAD_TEXT), CLOCK_RATE(1000), BITS_PER_SAMPLE(0), ZERO_PATTERN(NULL), PATTERN_LENGTH(0), NORMAL_BITRATE(0), + MIME_TYPE("t140"), CHANNELS(0), RECV_FMTP(NULL), SEND_FMTP(NULL), NO_AVPF, FLAGS(0)}; + +PayloadType payload_type_t140_red = { + TYPE(PAYLOAD_TEXT), CLOCK_RATE(1000), BITS_PER_SAMPLE(0), ZERO_PATTERN(NULL), PATTERN_LENGTH(0), NORMAL_BITRATE(0), + MIME_TYPE("red"), CHANNELS(0), RECV_FMTP(NULL), SEND_FMTP(NULL), NO_AVPF, FLAGS(0)}; + +PayloadType payload_type_x_udpftp = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(1000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(0), + MIME_TYPE("x-udpftp"), + CHANNELS(0), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_g722 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(64000), + MIME_TYPE("G722"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_silk_nb = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(13000), + MIME_TYPE("SILK"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_silk_mb = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(12000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(15000), + MIME_TYPE("SILK"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_silk_wb = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(16000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(20000), + MIME_TYPE("SILK"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_silk_swb = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(24000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(30000), + MIME_TYPE("SILK"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_aaceld_16k = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(16000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(24000), + MIME_TYPE("mpeg4-generic"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_aaceld_22k = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(22050), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(32000), + MIME_TYPE("mpeg4-generic"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_aaceld_32k = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(32000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(48000), + MIME_TYPE("mpeg4-generic"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_aaceld_44k = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(44100), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(64000), + MIME_TYPE("mpeg4-generic"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_aaceld_48k = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(48000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(64000), + MIME_TYPE("mpeg4-generic"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_opus = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(48000), /*mandatory according to RFC*/ + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(20000), + MIME_TYPE("opus"), + CHANNELS(2), /*mandatory according to RFC*/ + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_isac = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(16000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(32000), + MIME_TYPE("iSAC"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(PAYLOAD_TYPE_IS_VBR)}; + +PayloadType payload_type_codec2 = {TYPE(PAYLOAD_AUDIO_PACKETIZED), + CLOCK_RATE(8000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(3200), + MIME_TYPE("CODEC2"), + CHANNELS(1), + RECV_FMTP(NULL), + SEND_FMTP(NULL), + NO_AVPF, + FLAGS(0)}; + +PayloadType payload_type_flexfec = {TYPE(PAYLOAD_VIDEO), + CLOCK_RATE(90000), + BITS_PER_SAMPLE(0), + ZERO_PATTERN(NULL), + PATTERN_LENGTH(0), + NORMAL_BITRATE(3200), + MIME_TYPE("flexfec"), + CHANNELS(0), + RECV_FMTP("repair-window=200000;L=5;D=5"), + SEND_FMTP("repair-window=200000;L=5;D=5"), + NO_AVPF, + FLAGS(0)}; \ No newline at end of file diff --git a/src/b64.c b/src/b64.c index e7cec29b..66340f8e 100644 --- a/src/b64.c +++ b/src/b64.c @@ -37,7 +37,6 @@ * * ////////////////////////////////////////////////////////////////////////// */ - /** \file b64.c Implementation file for the b64 library */ @@ -46,18 +45,18 @@ */ #ifndef B64_DOCUMENTATION_SKIP_SECTION -# define B64_VER_C_B64_MAJOR 1 -# define B64_VER_C_B64_MINOR 2 -# define B64_VER_C_B64_REVISION 3 -# define B64_VER_C_B64_EDIT 17 +#define B64_VER_C_B64_MAJOR 1 +#define B64_VER_C_B64_MINOR 2 +#define B64_VER_C_B64_REVISION 3 +#define B64_VER_C_B64_EDIT 17 #endif /* !B64_DOCUMENTATION_SKIP_SECTION */ /* ///////////////////////////////////////////////////////////////////////////// * Includes */ -#include "ortp/port.h" #include "ortp/b64.h" +#include "ortp/port.h" #include @@ -68,8 +67,8 @@ */ #ifndef B64_DOCUMENTATION_SKIP_SECTION -# define NUM_PLAIN_DATA_BYTES (3) -# define NUM_ENCODED_DATA_BYTES (4) +#define NUM_PLAIN_DATA_BYTES (3) +#define NUM_ENCODED_DATA_BYTES (4) #endif /* !B64_DOCUMENTATION_SKIP_SECTION */ /* ///////////////////////////////////////////////////////////////////////////// @@ -77,67 +76,303 @@ */ #ifndef NUM_ELEMENTS -# define NUM_ELEMENTS(x) (sizeof(x) / sizeof(x[0])) +#define NUM_ELEMENTS(x) (sizeof(x) / sizeof(x[0])) #endif /* !NUM_ELEMENTS */ /* ///////////////////////////////////////////////////////////////////////////// * Warnings */ -#if defined(_MSC_VER) && \ - _MSC_VER < 1000 -# pragma warning(disable : 4705) +#if defined(_MSC_VER) && _MSC_VER < 1000 +#pragma warning(disable : 4705) #endif /* _MSC_VER < 1000 */ /* ///////////////////////////////////////////////////////////////////////////// * Data */ -static const char b64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static const char b64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static const signed char b64_indexes[] = -{ +static const signed char b64_indexes[] = { /* 0 - 31 / 0x00 - 0x1f */ - -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1 /* 32 - 63 / 0x20 - 0x3f */ - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, 62, -1, -1, -1, 63 /* ... , '+', ... '/' */ - , 52, 53, 54, 55, 56, 57, 58, 59 /* '0' - '7' */ - , 60, 61, -1, -1, -1, -1, -1, -1 /* '8', '9', ... */ + , + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 62, + -1, + -1, + -1, + 63 /* ... , '+', ... '/' */ + , + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59 /* '0' - '7' */ + , + 60, + 61, + -1, + -1, + -1, + -1, + -1, + -1 /* '8', '9', ... */ /* 64 - 95 / 0x40 - 0x5f */ - , -1, 0, 1, 2, 3, 4, 5, 6 /* ..., 'A' - 'G' */ - , 7, 8, 9, 10, 11, 12, 13, 14 /* 'H' - 'O' */ - , 15, 16, 17, 18, 19, 20, 21, 22 /* 'P' - 'W' */ - , 23, 24, 25, -1, -1, -1, -1, -1 /* 'X', 'Y', 'Z', ... */ + , + -1, + 0, + 1, + 2, + 3, + 4, + 5, + 6 /* ..., 'A' - 'G' */ + , + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14 /* 'H' - 'O' */ + , + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22 /* 'P' - 'W' */ + , + 23, + 24, + 25, + -1, + -1, + -1, + -1, + -1 /* 'X', 'Y', 'Z', ... */ /* 96 - 127 / 0x60 - 0x7f */ - , -1, 26, 27, 28, 29, 30, 31, 32 /* ..., 'a' - 'g' */ - , 33, 34, 35, 36, 37, 38, 39, 40 /* 'h' - 'o' */ - , 41, 42, 43, 44, 45, 46, 47, 48 /* 'p' - 'w' */ - , 49, 50, 51, -1, -1, -1, -1, -1 /* 'x', 'y', 'z', ... */ - - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 -}; + , + -1, + 26, + 27, + 28, + 29, + 30, + 31, + 32 /* ..., 'a' - 'g' */ + , + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40 /* 'h' - 'o' */ + , + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48 /* 'p' - 'w' */ + , + 49, + 50, + 51, + -1, + -1, + -1, + -1, + -1 /* 'x', 'y', 'z', ... */ + + , + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1 + + , + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1 + + , + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1 + + , + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1}; /* ///////////////////////////////////////////////////////////////////////////// * Helper functions @@ -146,464 +381,405 @@ static const signed char b64_indexes[] = /** This function reads in 3 bytes at a time, and translates them into 4 * characters. */ -static size_t b64_encode_( unsigned char const *src - , size_t srcSize - , char *const dest - , size_t destLen - , unsigned lineLen - , B64_RC *rc) -{ - size_t total = ((srcSize + (NUM_PLAIN_DATA_BYTES - 1)) / NUM_PLAIN_DATA_BYTES) * NUM_ENCODED_DATA_BYTES; - - assert(NULL != rc); - *rc = B64_RC_OK; - - if(lineLen > 0) - { - size_t numLines = (total + (lineLen - 1)) / lineLen; - - total += 2 * (numLines - 1); - } - - if(NULL == dest) - { - return total; - } - else if(destLen < total) - { - *rc = B64_RC_INSUFFICIENT_BUFFER; - - return 0; - } - else - { - char *p = dest; - char *end = dest + destLen; - size_t len = 0; - - for(; NUM_PLAIN_DATA_BYTES <= srcSize; srcSize -= NUM_PLAIN_DATA_BYTES) - { - unsigned char characters[NUM_ENCODED_DATA_BYTES]; - - /* - * - * | 0 | 1 | 2 | - * - * | | | | - * | | | | | | | - * | | | | | | | | | | | | | - * | | | | | | | | | | | | | | | | | | | | | | | | | - * - * | 0 | 1 | 2 | 3 | - * - */ - - /* characters[0] is the 6 left-most bits of src[0] */ - characters[0] = ((src[0] & 0xfc) >> 2); - /* characters[0] is the right-most 2 bits of src[0] and the left-most 4 bits of src[1] */ - characters[1] = (((src[0] & 0x03) << 4) + ((src[1] & 0xf0) >> 4)); - /* characters[0] is the right-most 4 bits of src[1] and the 2 left-most bits of src[2] */ - characters[2] = (((src[1] & 0x0f) << 2) + ((src[2] & 0xc0) >> 6)); - /* characters[3] is the right-most 6 bits of src[2] */ - characters[3] = (src[2] & 0x3f); +static size_t +b64_encode_(unsigned char const *src, size_t srcSize, char *const dest, size_t destLen, unsigned lineLen, B64_RC *rc) { + size_t total = ((srcSize + (NUM_PLAIN_DATA_BYTES - 1)) / NUM_PLAIN_DATA_BYTES) * NUM_ENCODED_DATA_BYTES; + + assert(NULL != rc); + *rc = B64_RC_OK; + + if (lineLen > 0) { + size_t numLines = (total + (lineLen - 1)) / lineLen; + + total += 2 * (numLines - 1); + } + + if (NULL == dest) { + return total; + } else if (destLen < total) { + *rc = B64_RC_INSUFFICIENT_BUFFER; + + return 0; + } else { + char *p = dest; + char *end = dest + destLen; + size_t len = 0; + + for (; NUM_PLAIN_DATA_BYTES <= srcSize; srcSize -= NUM_PLAIN_DATA_BYTES) { + unsigned char characters[NUM_ENCODED_DATA_BYTES]; + + /* + * + * | 0 | 1 | 2 | + * + * | | | | + * | | | | | | | + * | | | | | | | | | | | | | + * | | | | | | | | | | | | | | | | | | | | | | | | | + * + * | 0 | 1 | 2 | 3 | + * + */ + + /* characters[0] is the 6 left-most bits of src[0] */ + characters[0] = ((src[0] & 0xfc) >> 2); + /* characters[0] is the right-most 2 bits of src[0] and the left-most 4 bits of src[1] */ + characters[1] = (((src[0] & 0x03) << 4) + ((src[1] & 0xf0) >> 4)); + /* characters[0] is the right-most 4 bits of src[1] and the 2 left-most bits of src[2] */ + characters[2] = (((src[1] & 0x0f) << 2) + ((src[2] & 0xc0) >> 6)); + /* characters[3] is the right-most 6 bits of src[2] */ + characters[3] = (src[2] & 0x3f); #ifndef __WATCOMC__ - assert(characters[0] < 64); - assert(characters[1] < 64); - assert(characters[2] < 64); - assert(characters[3] < 64); + assert(characters[0] < 64); + assert(characters[1] < 64); + assert(characters[2] < 64); + assert(characters[3] < 64); #endif /* __WATCOMC__ */ - src += NUM_PLAIN_DATA_BYTES; - *p++ = b64_chars[characters[0]]; - assert(NULL != strchr(b64_chars, *(p-1))); - ++len; - assert(len != lineLen); - - *p++ = b64_chars[characters[1]]; - assert(NULL != strchr(b64_chars, *(p-1))); - ++len; - assert(len != lineLen); - - *p++ = b64_chars[characters[2]]; - assert(NULL != strchr(b64_chars, *(p-1))); - ++len; - assert(len != lineLen); - - *p++ = b64_chars[characters[3]]; - assert(NULL != strchr(b64_chars, *(p-1))); - - if( ++len == lineLen && - p != end) - { - *p++ = '\r'; - *p++ = '\n'; - len = 0; - } - } - - if(0 != srcSize) - { - /* Deal with the overspill, by boosting it up to three bytes (using 0s) - * and then appending '=' for any missing characters. - * - * This is done into a temporary buffer, so we can call ourselves and - * have the output continue to be written direct to the destination. - */ - - unsigned char dummy[NUM_PLAIN_DATA_BYTES]; - size_t i; - - for(i = 0; i < srcSize; ++i) - { - dummy[i] = *src++; - } - - for(; i < NUM_PLAIN_DATA_BYTES; ++i) - { - dummy[i] = '\0'; - } - - b64_encode_(&dummy[0], NUM_PLAIN_DATA_BYTES, p, NUM_ENCODED_DATA_BYTES * (1 + 2), 0, rc); - - for(p += 1 + srcSize; srcSize++ < NUM_PLAIN_DATA_BYTES; ) - { - *p++ = '='; - } - } - - return total; - } + src += NUM_PLAIN_DATA_BYTES; + *p++ = b64_chars[characters[0]]; + assert(NULL != strchr(b64_chars, *(p - 1))); + ++len; + assert(len != lineLen); + + *p++ = b64_chars[characters[1]]; + assert(NULL != strchr(b64_chars, *(p - 1))); + ++len; + assert(len != lineLen); + + *p++ = b64_chars[characters[2]]; + assert(NULL != strchr(b64_chars, *(p - 1))); + ++len; + assert(len != lineLen); + + *p++ = b64_chars[characters[3]]; + assert(NULL != strchr(b64_chars, *(p - 1))); + + if (++len == lineLen && p != end) { + *p++ = '\r'; + *p++ = '\n'; + len = 0; + } + } + + if (0 != srcSize) { + /* Deal with the overspill, by boosting it up to three bytes (using 0s) + * and then appending '=' for any missing characters. + * + * This is done into a temporary buffer, so we can call ourselves and + * have the output continue to be written direct to the destination. + */ + + unsigned char dummy[NUM_PLAIN_DATA_BYTES]; + size_t i; + + for (i = 0; i < srcSize; ++i) { + dummy[i] = *src++; + } + + for (; i < NUM_PLAIN_DATA_BYTES; ++i) { + dummy[i] = '\0'; + } + + b64_encode_(&dummy[0], NUM_PLAIN_DATA_BYTES, p, NUM_ENCODED_DATA_BYTES * (1 + 2), 0, rc); + + for (p += 1 + srcSize; srcSize++ < NUM_PLAIN_DATA_BYTES;) { + *p++ = '='; + } + } + + return total; + } } /** This function reads in a character string in 4-character chunks, and writes * out the converted form in 3-byte chunks to the destination. */ -static size_t b64_decode_( char const *src - , size_t srcLen - , unsigned char *dest - , size_t destSize - , unsigned flags - , char const **badChar - , B64_RC *rc) -{ - const size_t wholeChunks = (srcLen / NUM_ENCODED_DATA_BYTES); - const size_t remainderBytes = (srcLen % NUM_ENCODED_DATA_BYTES); - size_t maxTotal = (wholeChunks + (0 != remainderBytes)) * NUM_PLAIN_DATA_BYTES; - unsigned char *dest_ = dest; - - ((void)remainderBytes); - - assert(NULL != badChar); - assert(NULL != rc); - - *badChar = NULL; - *rc = B64_RC_OK; - - if(NULL == dest) - { - return maxTotal; - } - else if(destSize < maxTotal) - { - *rc = B64_RC_INSUFFICIENT_BUFFER; - - return 0; - } - else - { - /* Now we iterate through the src, collecting together four characters - * at a time from the Base-64 alphabet, until the end-point is reached. - * - * - */ - - char const *begin = src; - char const *const end = begin + srcLen; - size_t currIndex = 0; - size_t numPads = 0; - signed char indexes[NUM_ENCODED_DATA_BYTES]; /* 4 */ - - for(; begin != end; ++begin) - { - const char ch = *begin; - - if('=' == ch) - { - assert(currIndex < NUM_ENCODED_DATA_BYTES); - - indexes[currIndex++] = '\0'; - - ++numPads; - } - else - { - /* NOTE: Had to rename 'index' to 'ix', due to name clash with GCC on 64-bit Linux. */ - signed char ix = b64_indexes[(unsigned char)ch]; - - if(-1 == ix) - { - switch(ch) - { - case ' ':BCTBX_NO_BREAK; /*intentionally no break*/ - case '\t':BCTBX_NO_BREAK; /*intentionally no break*/ - case '\b':BCTBX_NO_BREAK; /*intentionally no break*/ - case '\v': - if(B64_F_STOP_ON_UNEXPECTED_WS & flags) - { - *rc = B64_RC_DATA_ERROR; - *badChar = begin; - return 0; - } - else - { - BCTBX_NO_BREAK; /* Fall through */ - } - case '\r':BCTBX_NO_BREAK; /*intentionally no break*/ - case '\n': - continue; - default: - if(B64_F_STOP_ON_UNKNOWN_CHAR & flags) - { - *rc = B64_RC_DATA_ERROR; - *badChar = begin; - return 0; - } - else - { - continue; - } - } - } - else - { - numPads = 0; - - assert(currIndex < NUM_ENCODED_DATA_BYTES); - - indexes[currIndex++] = ix; - } - } - - if(NUM_ENCODED_DATA_BYTES == currIndex) - { - unsigned char bytes[NUM_PLAIN_DATA_BYTES]; /* 3 */ - - bytes[0] = (unsigned char)((indexes[0] << 2) + ((indexes[1] & 0x30) >> 4)); - - currIndex = 0; - - *dest++ = bytes[0]; - if(2 != numPads) - { - bytes[1] = (unsigned char)(((indexes[1] & 0xf) << 4) + ((indexes[2] & 0x3c) >> 2)); - - *dest++ = bytes[1]; - - if(1 != numPads) - { - bytes[2] = (unsigned char)(((indexes[2] & 0x3) << 6) + indexes[3]); - - *dest++ = bytes[2]; - } - } - if(0 != numPads) - { - break; - } - } - } - - return (size_t)(dest - dest_); - } +static size_t b64_decode_(char const *src, + size_t srcLen, + unsigned char *dest, + size_t destSize, + unsigned flags, + char const **badChar, + B64_RC *rc) { + const size_t wholeChunks = (srcLen / NUM_ENCODED_DATA_BYTES); + const size_t remainderBytes = (srcLen % NUM_ENCODED_DATA_BYTES); + size_t maxTotal = (wholeChunks + (0 != remainderBytes)) * NUM_PLAIN_DATA_BYTES; + unsigned char *dest_ = dest; + + ((void)remainderBytes); + + assert(NULL != badChar); + assert(NULL != rc); + + *badChar = NULL; + *rc = B64_RC_OK; + + if (NULL == dest) { + return maxTotal; + } else if (destSize < maxTotal) { + *rc = B64_RC_INSUFFICIENT_BUFFER; + + return 0; + } else { + /* Now we iterate through the src, collecting together four characters + * at a time from the Base-64 alphabet, until the end-point is reached. + * + * + */ + + char const *begin = src; + char const *const end = begin + srcLen; + size_t currIndex = 0; + size_t numPads = 0; + signed char indexes[NUM_ENCODED_DATA_BYTES]; /* 4 */ + + for (; begin != end; ++begin) { + const char ch = *begin; + + if ('=' == ch) { + assert(currIndex < NUM_ENCODED_DATA_BYTES); + + indexes[currIndex++] = '\0'; + + ++numPads; + } else { + /* NOTE: Had to rename 'index' to 'ix', due to name clash with GCC on 64-bit Linux. */ + signed char ix = b64_indexes[(unsigned char)ch]; + + if (-1 == ix) { + switch (ch) { + case ' ': + BCTBX_NO_BREAK; /*intentionally no break*/ + case '\t': + BCTBX_NO_BREAK; /*intentionally no break*/ + case '\b': + BCTBX_NO_BREAK; /*intentionally no break*/ + case '\v': + if (B64_F_STOP_ON_UNEXPECTED_WS & flags) { + *rc = B64_RC_DATA_ERROR; + *badChar = begin; + return 0; + } else { + BCTBX_NO_BREAK; /* Fall through */ + } + case '\r': + BCTBX_NO_BREAK; /*intentionally no break*/ + case '\n': + continue; + default: + if (B64_F_STOP_ON_UNKNOWN_CHAR & flags) { + *rc = B64_RC_DATA_ERROR; + *badChar = begin; + return 0; + } else { + continue; + } + } + } else { + numPads = 0; + + assert(currIndex < NUM_ENCODED_DATA_BYTES); + + indexes[currIndex++] = ix; + } + } + + if (NUM_ENCODED_DATA_BYTES == currIndex) { + unsigned char bytes[NUM_PLAIN_DATA_BYTES]; /* 3 */ + + bytes[0] = (unsigned char)((indexes[0] << 2) + ((indexes[1] & 0x30) >> 4)); + + currIndex = 0; + + *dest++ = bytes[0]; + if (2 != numPads) { + bytes[1] = (unsigned char)(((indexes[1] & 0xf) << 4) + ((indexes[2] & 0x3c) >> 2)); + + *dest++ = bytes[1]; + + if (1 != numPads) { + bytes[2] = (unsigned char)(((indexes[2] & 0x3) << 6) + indexes[3]); + + *dest++ = bytes[2]; + } + } + if (0 != numPads) { + break; + } + } + } + + return (size_t)(dest - dest_); + } } /* ///////////////////////////////////////////////////////////////////////////// * API functions */ -size_t b64_encode(void const *src, size_t srcSize, char *dest, size_t destLen) -{ - /* Use Null Object (Variable) here for rc, so do not need to check - * elsewhere. - */ - B64_RC rc_; +size_t b64_encode(void const *src, size_t srcSize, char *dest, size_t destLen) { + /* Use Null Object (Variable) here for rc, so do not need to check + * elsewhere. + */ + B64_RC rc_; - return b64_encode_((unsigned char const*)src, srcSize, dest, destLen, 0, &rc_); + return b64_encode_((unsigned char const *)src, srcSize, dest, destLen, 0, &rc_); } -size_t b64_encode2( void const *src - , size_t srcSize - , char *dest - , size_t destLen - , unsigned flags - , int lineLen /* = -1 */ - , B64_RC *rc /* = NULL */) -{ - /* Use Null Object (Variable) here for rc, so do not need to check - * elsewhere - */ - B64_RC rc_; - if(NULL == rc) - { - rc = &rc_; - } - - switch(B64_F_LINE_LEN_MASK & flags) - { - case B64_F_LINE_LEN_USE_PARAM: - if(lineLen >= 0) - { - break; - } - BCTBX_NO_BREAK; /* Fall through to 64 */ - case B64_F_LINE_LEN_64: - lineLen = 64; - break; - case B64_F_LINE_LEN_76: - lineLen = 76; - break; - default: - /*the following assert makes a compiler error with icc*/ - /*assert(!"Bad line length flag specified to b64_encode2()");*/ - case B64_F_LINE_LEN_INFINITE: - lineLen = 0; - break; - } - - assert(0 == (lineLen % 4)); - - return b64_encode_((unsigned char const*)src, srcSize, dest, destLen, (unsigned)lineLen, rc); +size_t b64_encode2(void const *src, + size_t srcSize, + char *dest, + size_t destLen, + unsigned flags, + int lineLen /* = -1 */ + , + B64_RC *rc /* = NULL */) { + /* Use Null Object (Variable) here for rc, so do not need to check + * elsewhere + */ + B64_RC rc_; + if (NULL == rc) { + rc = &rc_; + } + + switch (B64_F_LINE_LEN_MASK & flags) { + case B64_F_LINE_LEN_USE_PARAM: + if (lineLen >= 0) { + break; + } + BCTBX_NO_BREAK; /* Fall through to 64 */ + case B64_F_LINE_LEN_64: + lineLen = 64; + break; + case B64_F_LINE_LEN_76: + lineLen = 76; + break; + default: + /*the following assert makes a compiler error with icc*/ + /*assert(!"Bad line length flag specified to b64_encode2()");*/ + case B64_F_LINE_LEN_INFINITE: + lineLen = 0; + break; + } + + assert(0 == (lineLen % 4)); + + return b64_encode_((unsigned char const *)src, srcSize, dest, destLen, (unsigned)lineLen, rc); } -size_t b64_decode(char const *src, size_t srcLen, void *dest, size_t destSize) -{ - /* Use Null Object (Variable) here for rc and badChar, so do not need to - * check elsewhere. - */ - char const *badChar_; - B64_RC rc_; +size_t b64_decode(char const *src, size_t srcLen, void *dest, size_t destSize) { + /* Use Null Object (Variable) here for rc and badChar, so do not need to + * check elsewhere. + */ + char const *badChar_; + B64_RC rc_; - return b64_decode_(src, srcLen, (unsigned char*)dest, destSize, B64_F_STOP_ON_NOTHING, &badChar_, &rc_); + return b64_decode_(src, srcLen, (unsigned char *)dest, destSize, B64_F_STOP_ON_NOTHING, &badChar_, &rc_); } -size_t b64_decode2( char const *src - , size_t srcLen - , void *dest - , size_t destSize - , unsigned flags - , char const **badChar /* = NULL */ - , B64_RC *rc /* = NULL */) -{ - char const *badChar_; - B64_RC rc_; - - /* Use Null Object (Variable) here for rc and badChar, so do not need to - * check elsewhere. - */ - if(NULL == badChar) - { - badChar = &badChar_; - } - if(NULL == rc) - { - rc = &rc_; - } - - return b64_decode_(src, srcLen, (unsigned char*)dest, destSize, flags, badChar, rc); +size_t b64_decode2(char const *src, + size_t srcLen, + void *dest, + size_t destSize, + unsigned flags, + char const **badChar /* = NULL */ + , + B64_RC *rc /* = NULL */) { + char const *badChar_; + B64_RC rc_; + + /* Use Null Object (Variable) here for rc and badChar, so do not need to + * check elsewhere. + */ + if (NULL == badChar) { + badChar = &badChar_; + } + if (NULL == rc) { + rc = &rc_; + } + + return b64_decode_(src, srcLen, (unsigned char *)dest, destSize, flags, badChar, rc); } /* ////////////////////////////////////////////////////////////////////////// */ #ifdef B64_DOCUMENTATION_SKIP_SECTION struct b64ErrorString_t_ -#else /* !B64_DOCUMENTATION_SKIP_SECTION */ -typedef struct b64ErrorString_t_ b64ErrorString_t_; +#else /* !B64_DOCUMENTATION_SKIP_SECTION */ +typedef struct b64ErrorString_t_ b64ErrorString_t_; struct b64ErrorString_t_ #endif /* !B64_DOCUMENTATION_SKIP_SECTION */ { - int code; /*!< The error code. */ - char const *str; /*!< The string. */ - size_t len; /*!< The string length. */ + int code; /*!< The error code. */ + char const *str; /*!< The string. */ + size_t len; /*!< The string length. */ }; +#define SEVERITY_STR_DECL(rc, desc) \ + \ + static const char s_str##rc[] = desc; \ + static const b64ErrorString_t_ s_rct##rc = {rc, s_str##rc, NUM_ELEMENTS(s_str##rc) - 1} + +#define SEVERITY_STR_ENTRY(rc) &s_rct##rc + +static char const *b64_LookupCodeA_(int code, b64ErrorString_t_ const **mappings, size_t cMappings, size_t *len) { + /* Use Null Object (Variable) here for len, so do not need to check + * elsewhere. + */ + size_t len_; + + if (NULL == len) { + len = &len_; + } + + /* Checked, indexed search. */ + if (code >= 0 && code < B64_max_RC_value) { + if (code == mappings[code]->code) { + return (*len = mappings[code]->len, mappings[code]->str); + } + } + + /* Linear search. Should only be needed if order in + * b64_LookupErrorStringA_() messed up. + */ + { + size_t i; + for (i = 0; i < cMappings; ++i) { + if (code == mappings[i]->code) { + return (*len = mappings[i]->len, mappings[i]->str); + } + } + } + + return (*len = 0, ""); +} +static char const *b64_LookupErrorStringA_(int error, size_t *len) { + SEVERITY_STR_DECL(B64_RC_OK, "Operation was successful"); + SEVERITY_STR_DECL(B64_RC_INSUFFICIENT_BUFFER, "The given translation buffer was not of sufficient size"); + SEVERITY_STR_DECL(B64_RC_TRUNCATED_INPUT, "The input did not represent a fully formed stream of octet couplings"); + SEVERITY_STR_DECL(B64_RC_DATA_ERROR, "Invalid data"); -#define SEVERITY_STR_DECL(rc, desc) \ - \ - static const char s_str##rc[] = desc; \ - static const b64ErrorString_t_ s_rct##rc = { rc, s_str##rc, NUM_ELEMENTS(s_str##rc) - 1 } - - -#define SEVERITY_STR_ENTRY(rc) \ - \ - &s_rct##rc - - -static char const *b64_LookupCodeA_(int code, b64ErrorString_t_ const **mappings, size_t cMappings, size_t *len) -{ - /* Use Null Object (Variable) here for len, so do not need to check - * elsewhere. - */ - size_t len_; - - if(NULL == len) - { - len = &len_; - } - - /* Checked, indexed search. */ - if( code >= 0 && - code < B64_max_RC_value) - { - if(code == mappings[code]->code) - { - return (*len = mappings[code]->len, mappings[code]->str); - } - } - - /* Linear search. Should only be needed if order in - * b64_LookupErrorStringA_() messed up. - */ - { size_t i; for(i = 0; i < cMappings; ++i) - { - if(code == mappings[i]->code) - { - return (*len = mappings[i]->len, mappings[i]->str); - } - }} - - return (*len = 0, ""); -} + static const b64ErrorString_t_ *s_strings[] = { + SEVERITY_STR_ENTRY(B64_RC_OK), + SEVERITY_STR_ENTRY(B64_RC_INSUFFICIENT_BUFFER), + SEVERITY_STR_ENTRY(B64_RC_TRUNCATED_INPUT), + SEVERITY_STR_ENTRY(B64_RC_DATA_ERROR), + }; -static char const *b64_LookupErrorStringA_(int error, size_t *len) -{ - SEVERITY_STR_DECL(B64_RC_OK , "Operation was successful" ); - SEVERITY_STR_DECL(B64_RC_INSUFFICIENT_BUFFER , "The given translation buffer was not of sufficient size" ); - SEVERITY_STR_DECL(B64_RC_TRUNCATED_INPUT , "The input did not represent a fully formed stream of octet couplings" ); - SEVERITY_STR_DECL(B64_RC_DATA_ERROR , "Invalid data" ); - - static const b64ErrorString_t_ *s_strings[] = - { - SEVERITY_STR_ENTRY(B64_RC_OK), - SEVERITY_STR_ENTRY(B64_RC_INSUFFICIENT_BUFFER), - SEVERITY_STR_ENTRY(B64_RC_TRUNCATED_INPUT), - SEVERITY_STR_ENTRY(B64_RC_DATA_ERROR), - }; - - return b64_LookupCodeA_(error, s_strings, NUM_ELEMENTS(s_strings), len); + return b64_LookupCodeA_(error, s_strings, NUM_ELEMENTS(s_strings), len); } -char const *b64_getErrorString(B64_RC code) -{ - return b64_LookupErrorStringA_((int)code, NULL); +char const *b64_getErrorString(B64_RC code) { + return b64_LookupErrorStringA_((int)code, NULL); } -size_t b64_getErrorStringLength(B64_RC code) -{ - size_t len; +size_t b64_getErrorStringLength(B64_RC code) { + size_t len; - return (b64_LookupErrorStringA_((int)code, &len), len); + return (b64_LookupErrorStringA_((int)code, &len), len); } /* ////////////////////////////////////////////////////////////////////////// */ diff --git a/src/congestiondetector.c b/src/congestiondetector.c index f1e98924..f70a43b1 100644 --- a/src/congestiondetector.c +++ b/src/congestiondetector.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -20,8 +20,8 @@ #include "congestiondetector.h" -#include #include +#include #include @@ -31,40 +31,39 @@ static const float absolute_congested_clock_ratio = 0.93f; static const float relative_congested_clock_ratio = 0.96f; static const float rls_forgetting_factor = 0.97f; -const char *ortp_congestion_detector_state_to_string(OrtpCongestionState state){ - switch (state){ +const char *ortp_congestion_detector_state_to_string(OrtpCongestionState state) { + switch (state) { case CongestionStateNormal: return "CongestionStateNormal"; - break; + break; case CongestionStateSuspected: return "CongestionStatePending"; - break; + break; case CongestionStateDetected: return "CongestionStateDetected"; - break; + break; case CongestionStateResolving: return "CongestionStateResolving"; - break; + break; } return "invalid state"; } -static bool_t ortp_congestion_detector_set_state(OrtpCongestionDetector *cd, OrtpCongestionState state){ +static bool_t ortp_congestion_detector_set_state(OrtpCongestionDetector *cd, OrtpCongestionState state) { bool_t binary_state_changed = FALSE; if (state == cd->state) return FALSE; ortp_message("OrtpCongestionDetector: moving from state %s to state %s", - ortp_congestion_detector_state_to_string(cd->state), - ortp_congestion_detector_state_to_string(state)); + ortp_congestion_detector_state_to_string(cd->state), ortp_congestion_detector_state_to_string(state)); cd->state = state; cd->too_much_loss = FALSE; - if (state == CongestionStateDetected){ - if (!cd->is_in_congestion){ + if (state == CongestionStateDetected) { + if (!cd->is_in_congestion) { cd->is_in_congestion = TRUE; binary_state_changed = TRUE; } - }else if (state == CongestionStateNormal){ + } else if (state == CongestionStateNormal) { cd->start_ms = (uint64_t)-1; - if (cd->is_in_congestion){ + if (cd->is_in_congestion) { cd->is_in_congestion = FALSE; binary_state_changed = TRUE; } @@ -78,8 +77,8 @@ void ortp_congestion_detector_reset(OrtpCongestionDetector *cd) { ortp_congestion_detector_set_state(cd, CongestionStateNormal); } -OrtpCongestionDetector * ortp_congestion_detector_new(RtpSession *session) { - OrtpCongestionDetector *cd = (OrtpCongestionDetector*)ortp_malloc0(sizeof(OrtpCongestionDetector)); +OrtpCongestionDetector *ortp_congestion_detector_new(RtpSession *session) { + OrtpCongestionDetector *cd = (OrtpCongestionDetector *)ortp_malloc0(sizeof(OrtpCongestionDetector)); cd->session = session; ortp_congestion_detector_reset(cd); return cd; @@ -87,24 +86,24 @@ OrtpCongestionDetector * ortp_congestion_detector_new(RtpSession *session) { /* static uint32_t local_ts_to_remote_ts_rls(double clock_ratio, double offset, uint32_t local_ts){ - return (uint32_t)( (int64_t)(clock_ratio*(double)local_ts) + (int64_t)offset); + return (uint32_t)( (int64_t)(clock_ratio*(double)local_ts) + (int64_t)offset); } */ -static float ortp_congestion_detector_get_loss_rate(OrtpCongestionDetector *cd){ +static float ortp_congestion_detector_get_loss_rate(OrtpCongestionDetector *cd) { uint32_t cur_loss = (uint32_t)cd->session->stats.cum_packet_loss; uint32_t cur_seq = rtp_session_get_rcv_ext_seq_number(cd->session); uint32_t expected = cur_seq - cd->seq_begin; if (expected == 0) return 0; - return 100.0f*(float)(cur_loss - cd->loss_begin) / (float)expected; + return 100.0f * (float)(cur_loss - cd->loss_begin) / (float)expected; } bool_t ortp_congestion_detector_record(OrtpCongestionDetector *cd, uint32_t packet_ts, uint32_t cur_str_ts) { bool_t binary_state_changed = FALSE; bool_t clock_drift; JitterControl *jitterctl = &cd->session->rtp.jittctl; - //float deviation; + // float deviation; if (cd->skip) return FALSE; @@ -115,7 +114,7 @@ bool_t ortp_congestion_detector_record(OrtpCongestionDetector *cd, uint32_t pack cd->initialized = TRUE; ortp_kalman_rls_init(&cd->rls, 1, packet_ts - cur_str_ts); cd->rls.lambda = rls_forgetting_factor; - if (jitterctl->params.buffer_algorithm != OrtpJitterBufferRecursiveLeastSquare){ + if (jitterctl->params.buffer_algorithm != OrtpJitterBufferRecursiveLeastSquare) { ortp_error("ortp congestion detection requires RLS jitter buffer algorithm."); cd->skip = TRUE; } @@ -131,23 +130,26 @@ bool_t ortp_congestion_detector_record(OrtpCongestionDetector *cd, uint32_t pack return binary_state_changed; } - clock_drift = cd->rls.m < absolute_congested_clock_ratio || jitterctl->capped_clock_ratio < absolute_congested_clock_ratio - || cd->rls.m < relative_congested_clock_ratio * jitterctl->capped_clock_ratio ; - //deviation = ((int32_t)(packet_ts - local_ts_to_remote_ts_rls(cd->rls.m, cd->rls.b, cur_str_ts))) / (float)jitterctl->clock_rate; - //deviation = ortp_extremum_get_current(&jitterctl->max_ts_deviation)/(float)jitterctl->clock_rate; - //has_jitter = deviation > acceptable_deviation; + clock_drift = cd->rls.m < absolute_congested_clock_ratio || + jitterctl->capped_clock_ratio < absolute_congested_clock_ratio || + cd->rls.m < relative_congested_clock_ratio * jitterctl->capped_clock_ratio; + // deviation = ((int32_t)(packet_ts - local_ts_to_remote_ts_rls(cd->rls.m, cd->rls.b, cur_str_ts))) / + // (float)jitterctl->clock_rate; deviation = + // ortp_extremum_get_current(&jitterctl->max_ts_deviation)/(float)jitterctl->clock_rate; has_jitter = deviation > + // acceptable_deviation; /* if (jitterctl->clock_rate == 90000){ - ortp_message( - "OrtpCongestionDetector state=%s clock=%f" - ", jb->capped_clock_ratio=%f" - ", down_bw=%0.f, up_bw=%0.f kbits/s" - , ortp_congestion_detector_state_to_string(cd->state) - , cd->rls.m - , jitterctl->capped_clock_ratio - , rtp_session_get_recv_bandwidth_smooth(cd->session)*1e-3, rtp_session_get_send_bandwidth_smooth(cd->session)*1e-3 - ); + ortp_message( + "OrtpCongestionDetector state=%s clock=%f" + ", jb->capped_clock_ratio=%f" + ", down_bw=%0.f, up_bw=%0.f kbits/s" + , ortp_congestion_detector_state_to_string(cd->state) + , cd->rls.m + , jitterctl->capped_clock_ratio + , rtp_session_get_recv_bandwidth_smooth(cd->session)*1e-3, + rtp_session_get_send_bandwidth_smooth(cd->session)*1e-3 + ); } */ @@ -160,30 +162,32 @@ bool_t ortp_congestion_detector_record(OrtpCongestionDetector *cd, uint32_t pack cd->last_packet_recv = cd->start_ms; binary_state_changed = ortp_congestion_detector_set_state(cd, CongestionStateSuspected); } - break; - case CongestionStateSuspected: - { + break; + case CongestionStateSuspected: { uint64_t curtime = bctbx_get_cur_time_ms(); if (!clock_drift) { float loss_rate = ortp_congestion_detector_get_loss_rate(cd); - if (loss_rate >= return_from_suspected_max_loss_rate){ - if (!cd->too_much_loss){ - ortp_message("OrtpCongestionDetector: loss rate is [%f], too much for returning to CongestionStateNormal state.", loss_rate); + if (loss_rate >= return_from_suspected_max_loss_rate) { + if (!cd->too_much_loss) { + ortp_message("OrtpCongestionDetector: loss rate is [%f], too much for returning to " + "CongestionStateNormal state.", + loss_rate); cd->too_much_loss = TRUE; } - }else{ + } else { // congestion has maybe stopped binary_state_changed = ortp_congestion_detector_set_state(cd, CongestionStateNormal); } } else { - if (curtime - cd->last_packet_recv >= 1000){ + if (curtime - cd->last_packet_recv >= 1000) { /*no packet received during last second ! - It means that the drift measure is not very significant, and futhermore the banwdith computation will be - near to zero. It makes no sense to trigger a congestion detection in this case; the network is simply not working. + It means that the drift measure is not very significant, and futhermore the banwdith computation + will be near to zero. It makes no sense to trigger a congestion detection in this case; the network + is simply not working. */ binary_state_changed = ortp_congestion_detector_set_state(cd, CongestionStateNormal); - }else{ + } else { // congestion continues - if it has been for longer enough, trigger congestion flag if (curtime - cd->start_ms > congestion_pending_duration_ms) { binary_state_changed = ortp_congestion_detector_set_state(cd, CongestionStateDetected); @@ -191,15 +195,14 @@ bool_t ortp_congestion_detector_record(OrtpCongestionDetector *cd, uint32_t pack } } cd->last_packet_recv = curtime; - } - break; + } break; case CongestionStateDetected: if (!clock_drift) { // congestion is maybe terminated, go resolving state binary_state_changed = ortp_congestion_detector_set_state(cd, CongestionStateResolving); cd->start_ms = bctbx_get_cur_time_ms(); } - break; + break; case CongestionStateResolving: if (clock_drift) { binary_state_changed = ortp_congestion_detector_set_state(cd, CongestionStateDetected); @@ -208,11 +211,11 @@ bool_t ortp_congestion_detector_record(OrtpCongestionDetector *cd, uint32_t pack binary_state_changed = ortp_congestion_detector_set_state(cd, CongestionStateNormal); } } - break; + break; } return binary_state_changed; } -void ortp_congestion_detector_destroy(OrtpCongestionDetector *obj){ +void ortp_congestion_detector_destroy(OrtpCongestionDetector *obj) { ortp_free(obj); } \ No newline at end of file diff --git a/src/congestiondetector.h b/src/congestiondetector.h index aeab79ab..99b0b9aa 100644 --- a/src/congestiondetector.h +++ b/src/congestiondetector.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,13 +18,12 @@ * along with this program. If not, see . */ - #ifndef CONGESTIONDETECTOR_H #define CONGESTIONDETECTOR_H +#include #include #include -#include struct _JitterControl; typedef enum _OrtpCongestionState { @@ -34,7 +33,7 @@ typedef enum _OrtpCongestionState { CongestionStateResolving } OrtpCongestionState; -typedef struct _OrtpCongestionDetector{ +typedef struct _OrtpCongestionDetector { OrtpKalmanRLS rls; uint64_t start_ms; uint64_t last_packet_recv; @@ -45,13 +44,13 @@ typedef struct _OrtpCongestionDetector{ bool_t too_much_loss; OrtpCongestionState state; struct _RtpSession *session; -}OrtpCongestionDetector; +} OrtpCongestionDetector; -OrtpCongestionDetector * ortp_congestion_detector_new(struct _RtpSession *session); +OrtpCongestionDetector *ortp_congestion_detector_new(struct _RtpSession *session); /* * Returns TRUE if the congestion state is changed. -**/ + **/ bool_t ortp_congestion_detector_record(OrtpCongestionDetector *obj, uint32_t packet_ts, uint32_t cur_str_ts); void ortp_congestion_detector_destroy(OrtpCongestionDetector *obj); diff --git a/src/dblk.cc b/src/dblk.cc index 7116a006..4546c287 100644 --- a/src/dblk.cc +++ b/src/dblk.cc @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -17,7 +17,7 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ - + #ifdef HAVE_CONFIG_H #include "ortp-config.h" #endif @@ -27,49 +27,48 @@ using namespace std; -extern "C" -{ -dblk_t *dblk_alloc(size_t size){ +extern "C" { +dblk_t *dblk_alloc(size_t size) { struct datab *db; - size_t total_size=sizeof(struct datab)+size; - db=(struct datab *) ortp_malloc(total_size); + size_t total_size = sizeof(struct datab) + size; + db = (struct datab *)ortp_malloc(total_size); - db->db_base=(uint8_t*)db+sizeof(struct datab); - db->db_lim=db->db_base+size; - db->db_ref=new atomic_int(1); - db->db_freefn=NULL; /* the buffer pointed by db_base must never be freed !*/ + db->db_base = (uint8_t *)db + sizeof(struct datab); + db->db_lim = db->db_base + size; + db->db_ref = new atomic_int(1); + db->db_freefn = NULL; /* the buffer pointed by db_base must never be freed !*/ return db; } -struct datab* dblk_alloc2(uint8_t *buf, size_t size, void (*freefn)(void*) ){ +struct datab *dblk_alloc2(uint8_t *buf, size_t size, void (*freefn)(void *)) { struct datab *db; - db=(struct datab *) ortp_malloc(sizeof(struct datab)); + db = (struct datab *)ortp_malloc(sizeof(struct datab)); + + db->db_base = buf; + db->db_lim = buf + size; + db->db_ref = new atomic_int(1); + db->db_freefn = freefn; - db->db_base=buf; - db->db_lim=buf+size; - db->db_ref=new atomic_int(1); - db->db_freefn=freefn; - return db; } -void dblk_ref(struct datab * data){ - atomic_fetch_add_explicit(static_cast(data->db_ref), 1, memory_order_relaxed); +void dblk_ref(struct datab *data) { + atomic_fetch_add_explicit(static_cast(data->db_ref), 1, memory_order_relaxed); } -void dblk_unref(struct datab * data){ - atomic_int previous_ref(atomic_fetch_sub_explicit(static_cast(data->db_ref), 1, memory_order_release)); - if (previous_ref == 1){ - if (data->db_freefn!=NULL) - data->db_freefn(data->db_base); - delete static_cast(data->db_ref); +void dblk_unref(struct datab *data) { + atomic_int previous_ref( + atomic_fetch_sub_explicit(static_cast(data->db_ref), 1, memory_order_release)); + if (previous_ref == 1) { + if (data->db_freefn != NULL) data->db_freefn(data->db_base); + delete static_cast(data->db_ref); data->db_ref = NULL; ortp_free(data); } } -int dblk_ref_value(dblk_t *db){ - return (int)static_cast(db->db_ref)->load(); +int dblk_ref_value(dblk_t *db) { + return (int)static_cast(db->db_ref)->load(); } -}//extern "C" \ No newline at end of file +} // extern "C" \ No newline at end of file diff --git a/src/dll_entry.c b/src/dll_entry.c index 4e62c1ea..3605db70 100644 --- a/src/dll_entry.c +++ b/src/dll_entry.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -21,102 +21,94 @@ #ifdef HAVE_CONFIG_H #include "ortp-config.h" #endif -#include "ortp/ortp.h" +#include "ortp/ortp.h" -typedef struct __STRUCT_SHARED_DATA__ -{ - DWORD m_nReference; +typedef struct __STRUCT_SHARED_DATA__ { + DWORD m_nReference; #ifdef ORTP_WINDOWS_DESKTOP - DWORD m_dwStartTime; + DWORD m_dwStartTime; #else - ULONGLONG m_ullStartTime; + ULONGLONG m_ullStartTime; #endif - BOOL m_bInitialize; + BOOL m_bInitialize; -} SHARED_DATA, * LPSHARED_DATA; +} SHARED_DATA, *LPSHARED_DATA; #ifdef EXTERNAL_LOGGER #include "logger.h" #else -#define RegisterLog(logVar, logString); -#define UnregisterLog(logVar, logString); +#define RegisterLog(logVar, logString) ; +#define UnregisterLog(logVar, logString) ; #endif extern DWORD dwoRTPLogLevel; -#define SHMEMSIZE sizeof(SHARED_DATA) +#define SHMEMSIZE sizeof(SHARED_DATA) #ifndef ORTP_WINDOWS_DESKTOP -static SHARED_DATA sharedData; +static SHARED_DATA sharedData; #endif -static LPSHARED_DATA lpSharedData; -static HANDLE hMapObject = NULL; // handle to file mapping - -BOOL WINAPI DllMain( - HINSTANCE hinstDLL, // handle to DLL module - DWORD fdwReason, // reason for calling function - LPVOID lpReserved // reserved - ) -{ - BOOL fInit = FALSE; - WORD wVersionRequested; +static LPSHARED_DATA lpSharedData; +static HANDLE hMapObject = NULL; // handle to file mapping + +BOOL WINAPI DllMain(HINSTANCE hinstDLL, // handle to DLL module + DWORD fdwReason, // reason for calling function + LPVOID lpReserved // reserved +) { + BOOL fInit = FALSE; + WORD wVersionRequested; WSADATA wsaData; - // Perform actions based on the reason for calling. - switch( fdwReason ) - { - case DLL_PROCESS_ATTACH: + // Perform actions based on the reason for calling. + switch (fdwReason) { + case DLL_PROCESS_ATTACH: #ifndef _UNICODE OutputDebugStringA("--> dll_entry.c - oRTP.dll - DLL_PROCESS_ATTACH()\n"); #else OutputDebugStringW(L"--> dll_entry.c - oRTP.dll - DLL_PROCESS_ATTACH()\n"); #endif - - wVersionRequested = MAKEWORD( 1, 0 ); - if (WSAStartup(wVersionRequested,&wsaData)!=0) - { + wVersionRequested = MAKEWORD(1, 0); + + if (WSAStartup(wVersionRequested, &wsaData) != 0) { return FALSE; } #ifdef ORTP_WINDOWS_DESKTOP - // Create a named file mapping object. - hMapObject = CreateFileMapping( INVALID_HANDLE_VALUE, // use paging file - NULL, // default security attributes - PAGE_READWRITE, // read/write access - 0, // size: high 32-bits - SHMEMSIZE, // size: low 32-bits + // Create a named file mapping object. + hMapObject = CreateFileMapping(INVALID_HANDLE_VALUE, // use paging file + NULL, // default security attributes + PAGE_READWRITE, // read/write access + 0, // size: high 32-bits + SHMEMSIZE, // size: low 32-bits #ifdef ORTP_WINDOWS_UWP - L"oRTPSharedMemory"); // name of map object + L"oRTPSharedMemory"); // name of map object #else - "oRTPSharedMemory"); // name of map object + "oRTPSharedMemory"); // name of map object #endif - if (hMapObject == NULL) - return FALSE; - - // The first process to attach initializes memory. - fInit = (GetLastError() != ERROR_ALREADY_EXISTS); - - // Get a pointer to the file-mapped shared memory. - - lpSharedData = (LPSHARED_DATA) MapViewOfFile( hMapObject, // object to map view of - FILE_MAP_WRITE, // read/write access - 0, // high offset: map from - 0, // low offset: beginning - 0); // default: map entire file - if (lpSharedData == NULL) - return FALSE; + if (hMapObject == NULL) return FALSE; + + // The first process to attach initializes memory. + fInit = (GetLastError() != ERROR_ALREADY_EXISTS); + + // Get a pointer to the file-mapped shared memory. + + lpSharedData = (LPSHARED_DATA)MapViewOfFile(hMapObject, // object to map view of + FILE_MAP_WRITE, // read/write access + 0, // high offset: map from + 0, // low offset: beginning + 0); // default: map entire file + if (lpSharedData == NULL) return FALSE; #else fInit = TRUE; lpSharedData = &sharedData; #endif - - // Initialize memory if this is the first process. - - if (fInit) - { + + // Initialize memory if this is the first process. + + if (fInit) { #ifndef _UNICODE OutputDebugStringA("--> dll_entry.c - oRTP.dll - Initializing module\n"); #else @@ -124,18 +116,16 @@ BOOL WINAPI DllMain( #endif #ifdef ORTP_WINDOWS_DESKTOP - lpSharedData->m_dwStartTime = GetTickCount(); + lpSharedData->m_dwStartTime = GetTickCount(); #else lpSharedData->m_ullStartTime = GetTickCount64(); #endif - lpSharedData->m_nReference = 1; + lpSharedData->m_nReference = 1; lpSharedData->m_bInitialize = FALSE; // Register the log RegisterLog(&dwoRTPLogLevel, "LOG_ORTP"); - } - else - { + } else { #ifndef _UNICODE OutputDebugStringA("--> dll_entry.c - oRTP.dll - Binding\n"); #else @@ -143,32 +133,29 @@ BOOL WINAPI DllMain( #endif lpSharedData->m_nReference++; } - break; + break; - case DLL_THREAD_ATTACH: + case DLL_THREAD_ATTACH: - if (lpSharedData != NULL) - { - if (lpSharedData->m_bInitialize == FALSE) - { + if (lpSharedData != NULL) { + if (lpSharedData->m_bInitialize == FALSE) { // Initialize oRTP ortp_init(); // Start the scheduler - //ortp_scheduler_init(); + // ortp_scheduler_init(); lpSharedData->m_bInitialize = TRUE; } } - break; + break; - case DLL_THREAD_DETACH: + case DLL_THREAD_DETACH: break; - case DLL_PROCESS_DETACH: + case DLL_PROCESS_DETACH: - if (lpSharedData != NULL) - { + if (lpSharedData != NULL) { #ifndef _UNICODE OutputDebugStringA("--> dll_entry.c - oRTP.dll - Binding\n"); #else @@ -176,8 +163,7 @@ BOOL WINAPI DllMain( #endif lpSharedData->m_nReference--; - if (lpSharedData->m_nReference == 0) - { + if (lpSharedData->m_nReference == 0) { #ifndef _UNICODE OutputDebugStringA("--> dll_entry.c - oRTP.dll - Detaching\n"); #else @@ -188,18 +174,18 @@ BOOL WINAPI DllMain( UnregisterLog(&dwoRTPLogLevel, "LOG_ORTP"); #ifdef ORTP_WINDOWS_DESKTOP - // Unmap shared memory from the process's address space. + // Unmap shared memory from the process's address space. UnmapViewOfFile(lpSharedData); lpSharedData = NULL; - + // Close the process's handle to the file-mapping object. - CloseHandle(hMapObject); + CloseHandle(hMapObject); hMapObject = INVALID_HANDLE_VALUE; #endif } } - break; - } + break; + } - return TRUE; // Successful DLL_PROCESS_ATTACH. + return TRUE; // Successful DLL_PROCESS_ATTACH. } diff --git a/src/event.c b/src/event.c index 82e12958..c2b22d61 100644 --- a/src/event.c +++ b/src/event.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -26,83 +26,83 @@ #include "ortp/str_utils.h" #include "utils.h" -OrtpEvent * ortp_event_new(unsigned long type){ +OrtpEvent *ortp_event_new(unsigned long type) { OrtpEventData *ed; - const int size=sizeof(OrtpEventType)+sizeof(OrtpEventData); - mblk_t *m=allocb(size,0); - memset(m->b_wptr,0,size); - *((OrtpEventType*)m->b_wptr)=type; + const int size = sizeof(OrtpEventType) + sizeof(OrtpEventData); + mblk_t *m = allocb(size, 0); + memset(m->b_wptr, 0, size); + *((OrtpEventType *)m->b_wptr) = type; ed = ortp_event_get_data(m); ortp_get_cur_time(&ed->ts); return m; } -OrtpEvent *ortp_event_dup(OrtpEvent *ev){ +OrtpEvent *ortp_event_dup(OrtpEvent *ev) { OrtpEvent *nev = ortp_event_new(ortp_event_get_type(ev)); - OrtpEventData * ed = ortp_event_get_data(ev); - OrtpEventData * edv = ortp_event_get_data(nev); - memcpy(edv,ed,sizeof(OrtpEventData)); + OrtpEventData *ed = ortp_event_get_data(ev); + OrtpEventData *edv = ortp_event_get_data(nev); + memcpy(edv, ed, sizeof(OrtpEventData)); if (ed->packet) edv->packet = copymsg(ed->packet); return nev; } -OrtpEventType ortp_event_get_type(const OrtpEvent *ev){ - return ((OrtpEventType*)ev->b_rptr)[0]; +OrtpEventType ortp_event_get_type(const OrtpEvent *ev) { + return ((OrtpEventType *)ev->b_rptr)[0]; } -OrtpEventData * ortp_event_get_data(OrtpEvent *ev){ - return (OrtpEventData*)(ev->b_rptr+sizeof(OrtpEventType)); +OrtpEventData *ortp_event_get_data(OrtpEvent *ev) { + return (OrtpEventData *)(ev->b_rptr + sizeof(OrtpEventType)); } -void ortp_event_destroy(OrtpEvent *ev){ - OrtpEventData *d=ortp_event_get_data(ev); - if(dblk_ref_value(ev->b_datap) == 1){ - if (d->packet) freemsg(d->packet); +void ortp_event_destroy(OrtpEvent *ev) { + OrtpEventData *d = ortp_event_get_data(ev); + if (dblk_ref_value(ev->b_datap) == 1) { + if (d->packet) freemsg(d->packet); } freemsg(ev); } -OrtpEvQueue * ortp_ev_queue_new(){ - OrtpEvQueue *q=ortp_new(OrtpEvQueue,1); +OrtpEvQueue *ortp_ev_queue_new() { + OrtpEvQueue *q = ortp_new(OrtpEvQueue, 1); qinit(&q->q); - ortp_mutex_init(&q->mutex,NULL); + ortp_mutex_init(&q->mutex, NULL); return q; } -void ortp_ev_queue_flush(OrtpEvQueue * qp){ +void ortp_ev_queue_flush(OrtpEvQueue *qp) { OrtpEvent *ev; - while((ev=ortp_ev_queue_get(qp))!=NULL){ + while ((ev = ortp_ev_queue_get(qp)) != NULL) { ortp_event_destroy(ev); } } -OrtpEvent * ortp_ev_queue_get(OrtpEvQueue *q){ +OrtpEvent *ortp_ev_queue_get(OrtpEvQueue *q) { OrtpEvent *ev; ortp_mutex_lock(&q->mutex); - ev=getq(&q->q); + ev = getq(&q->q); ortp_mutex_unlock(&q->mutex); return ev; } -void ortp_ev_queue_destroy(OrtpEvQueue * qp){ +void ortp_ev_queue_destroy(OrtpEvQueue *qp) { ortp_ev_queue_flush(qp); ortp_mutex_destroy(&qp->mutex); ortp_free(qp); } -void ortp_ev_queue_put(OrtpEvQueue *q, OrtpEvent *ev){ +void ortp_ev_queue_put(OrtpEvQueue *q, OrtpEvent *ev) { ortp_mutex_lock(&q->mutex); - putq(&q->q,ev); + putq(&q->q, ev); ortp_mutex_unlock(&q->mutex); } -static bool_t rtcp_is_type(const mblk_t *m, rtcp_type_t type){ - const rtcp_common_header_t *ch=rtcp_get_common_header(m); - return (ch!=NULL && rtcp_common_header_get_packet_type(ch)==type); +static bool_t rtcp_is_type(const mblk_t *m, rtcp_type_t type) { + const rtcp_common_header_t *ch = rtcp_get_common_header(m); + return (ch != NULL && rtcp_common_header_get_packet_type(ch) == type); } -OrtpEvDispatcher * ortp_ev_dispatcher_new(RtpSession* session) { - OrtpEvDispatcher *d=ortp_new(OrtpEvDispatcher,1); +OrtpEvDispatcher *ortp_ev_dispatcher_new(RtpSession *session) { + OrtpEvDispatcher *d = ortp_new(OrtpEvDispatcher, 1); d->session = session; d->q = ortp_ev_queue_new(); rtp_session_register_event_queue(session, d->q); @@ -112,8 +112,8 @@ OrtpEvDispatcher * ortp_ev_dispatcher_new(RtpSession* session) { } void ortp_ev_dispatcher_destroy(OrtpEvDispatcher *d) { - OList* it; - for (it=d->cbs;it!=NULL;it=it->next){ + OList *it; + for (it = d->cbs; it != NULL; it = it->next) { ortp_free(it->data); } o_list_free(d->cbs); @@ -132,9 +132,9 @@ static void iterate_cbs(OrtpEvDispatcher *disp, OrtpEvent *ev) { /*for each packet part, if ANY iterate through the whole callback list to see if anyone is interested in it*/ OrtpEventData *d = ortp_event_get_data(ev); - OList* it; + OList *it; OrtpEventType evt = ortp_event_get_type(ev); - for (it=disp->cbs;it!=NULL;it=it->next){ + for (it = disp->cbs; it != NULL; it = it->next) { OrtpEvDispatcherData *data = (OrtpEvDispatcherData *)it->data; if (evt == data->type) { if (!is_rtcp_event(data->type) || rtcp_is_type(d->packet, data->subtype)) { @@ -142,7 +142,7 @@ static void iterate_cbs(OrtpEvDispatcher *disp, OrtpEvent *ev) { } } } - } while (d->packet!=NULL && rtcp_next_packet(d->packet)); + } while (d->packet != NULL && rtcp_next_packet(d->packet)); } void ortp_ev_dispatcher_iterate(OrtpEvDispatcher *d) { @@ -153,12 +153,9 @@ void ortp_ev_dispatcher_iterate(OrtpEvDispatcher *d) { } } -void ortp_ev_dispatcher_connect(OrtpEvDispatcher *d - , OrtpEventType type - , rtcp_type_t subtype - , OrtpEvDispatcherCb cb - , void *user_data) { - OrtpEvDispatcherData *data=ortp_new(OrtpEvDispatcherData,1); +void ortp_ev_dispatcher_connect( + OrtpEvDispatcher *d, OrtpEventType type, rtcp_type_t subtype, OrtpEvDispatcherCb cb, void *user_data) { + OrtpEvDispatcherData *data = ortp_new(OrtpEvDispatcherData, 1); data->type = type; data->subtype = subtype; data->on_found = cb; @@ -166,17 +163,17 @@ void ortp_ev_dispatcher_connect(OrtpEvDispatcher *d d->cbs = o_list_append(d->cbs, data); } -void ortp_ev_dispatcher_disconnect(OrtpEvDispatcher *d - , OrtpEventType type - , rtcp_type_t subtype - , OrtpEvDispatcherCb cb) { +void ortp_ev_dispatcher_disconnect(OrtpEvDispatcher *d, + OrtpEventType type, + rtcp_type_t subtype, + OrtpEvDispatcherCb cb) { OList *it = NULL; - if(!d) { + if (!d) { return; } it = d->cbs; while (it) { - OrtpEvDispatcherData *data = (OrtpEvDispatcherData*)it->data; + OrtpEvDispatcherData *data = (OrtpEvDispatcherData *)it->data; if (data && data->type == type && data->subtype == subtype && data->on_found == cb) { OList *tofree = it; it = it->next; diff --git a/src/extremum.c b/src/extremum.c index ee008b3b..10919eb5 100644 --- a/src/extremum.c +++ b/src/extremum.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,66 +18,66 @@ * along with this program. If not, see . */ -#include "ortp/utils.h" +#include + #include "ortp/logging.h" +#include "ortp/utils.h" -void ortp_extremum_reset(OrtpExtremum *obj){ - obj->current_extremum=0; - obj->extremum_time=(uint64_t)-1; - obj->last_stable=0; +void ortp_extremum_reset(OrtpExtremum *obj) { + obj->current_extremum = 0; + obj->extremum_time = (uint64_t)-1; + obj->last_stable = 0; } -void ortp_extremum_init(OrtpExtremum *obj, int period){ +void ortp_extremum_init(OrtpExtremum *obj, int period) { ortp_extremum_reset(obj); - obj->period=period; + obj->period = period; } - -static bool_t extremum_check_init(OrtpExtremum *obj, uint64_t curtime, float value, const char *kind){ - if (obj->extremum_time!=(uint64_t)-1){ - if (((int)(curtime-obj->extremum_time))>obj->period){ - obj->last_stable=obj->current_extremum; +static bool_t extremum_check_init(OrtpExtremum *obj, uint64_t curtime, float value, BCTBX_UNUSED(const char *kind)) { + if (obj->extremum_time != (uint64_t)-1) { + if (((int)(curtime - obj->extremum_time)) > obj->period) { + obj->last_stable = obj->current_extremum; /*last extremum is too old, drop it and replace it with current value*/ - obj->current_extremum=value; - obj->extremum_time=curtime; + obj->current_extremum = value; + obj->extremum_time = curtime; return TRUE; } - }else { - obj->last_stable=value; - obj->current_extremum=value; - obj->extremum_time=curtime; + } else { + obj->last_stable = value; + obj->current_extremum = value; + obj->extremum_time = curtime; return TRUE; } return FALSE; } -bool_t ortp_extremum_record_min(OrtpExtremum *obj, uint64_t curtime, float value){ - bool_t ret = extremum_check_init(obj,curtime,value,"min"); - if (valuecurrent_extremum){ - obj->last_stable=obj->current_extremum; - obj->current_extremum=value; - obj->extremum_time=curtime; +bool_t ortp_extremum_record_min(OrtpExtremum *obj, uint64_t curtime, float value) { + bool_t ret = extremum_check_init(obj, curtime, value, "min"); + if (value < obj->current_extremum) { + obj->last_stable = obj->current_extremum; + obj->current_extremum = value; + obj->extremum_time = curtime; return TRUE; } return ret; } -bool_t ortp_extremum_record_max(OrtpExtremum *obj, uint64_t curtime, float value){ - bool_t ret = extremum_check_init(obj,curtime,value,"max"); - if (value>obj->current_extremum){ - obj->last_stable=obj->current_extremum; - obj->current_extremum=value; - obj->extremum_time=curtime; +bool_t ortp_extremum_record_max(OrtpExtremum *obj, uint64_t curtime, float value) { + bool_t ret = extremum_check_init(obj, curtime, value, "max"); + if (value > obj->current_extremum) { + obj->last_stable = obj->current_extremum; + obj->current_extremum = value; + obj->extremum_time = curtime; ret = TRUE; } return ret; } -float ortp_extremum_get_current(OrtpExtremum *obj){ +float ortp_extremum_get_current(OrtpExtremum *obj) { return obj->current_extremum; } -float ortp_extremum_get_previous(OrtpExtremum *obj){ +float ortp_extremum_get_previous(OrtpExtremum *obj) { return obj->last_stable; } - diff --git a/src/fecstream.cc b/src/fecstream.cc index 3b9e978c..66f0fdaf 100644 --- a/src/fecstream.cc +++ b/src/fecstream.cc @@ -44,7 +44,7 @@ extern "C" fec_stats *fec_stream_get_stats(FecStream *fec_stream) { return ((FecStreamCxx *)fec_stream)->getStats(); } FecStreamCxx::FecStreamCxx(struct _RtpSession *source, struct _RtpSession *fec, FecParameters *fecParams) - : mEncoder(fecParams), mCluster(source) { + : mEncoder(fecParams), mCluster(source) { parameters = fecParams; mSourceSession = source; @@ -55,14 +55,14 @@ FecStreamCxx::FecStreamCxx(struct _RtpSession *source, struct _RtpSession *fec, memset(&mStats, 0, sizeof(fec_stats)); } void FecStreamCxx::init() { - RtpTransport * transport = NULL; - RtpBundle * bundle = (RtpBundle *) mSourceSession->bundle; - RtpSession * session = rtp_bundle_get_primary_session(bundle); + RtpTransport *transport = NULL; + RtpBundle *bundle = (RtpBundle *)mSourceSession->bundle; + RtpSession *session = rtp_bundle_get_primary_session(bundle); rtp_session_get_transports(session, &transport, NULL); - + mModifier = ortp_new0(RtpTransportModifier, 1); mModifier->level = RtpTransportModifierLevelForwardErrorCorrection; - mModifier->data = this; + mModifier->data = this; mModifier->t_process_on_send = FecStreamCxx::processOnSend; mModifier->t_process_on_receive = FecStreamCxx::processOnRecieve; mModifier->t_process_on_schedule = NULL; @@ -71,27 +71,27 @@ void FecStreamCxx::init() { mCluster.setModifier(mModifier); mEncoder.init(mFecSession, mSourceSession); } -int FecStreamCxx::processOnSend(struct _RtpTransportModifier *m, mblk_t *packet){ +int FecStreamCxx::processOnSend(struct _RtpTransportModifier *m, mblk_t *packet) { - FecStreamCxx * fecStream = (FecStreamCxx *) m->data; - RtpSession * sourceSession = fecStream->getSourceSession(); + FecStreamCxx *fecStream = (FecStreamCxx *)m->data; + RtpSession *sourceSession = fecStream->getSourceSession(); uint32_t ssrc = rtp_get_ssrc(packet); - if(ssrc == rtp_session_get_send_ssrc(sourceSession)){ + if (ssrc == rtp_session_get_send_ssrc(sourceSession)) { fecStream->onNewSourcePacketSent(packet); } return (int)msgdsize(packet); } -int FecStreamCxx::processOnRecieve(struct _RtpTransportModifier *m,mblk_t *packet){ +int FecStreamCxx::processOnRecieve(struct _RtpTransportModifier *m, mblk_t *packet) { - FecStreamCxx * fecStream = (FecStreamCxx *) m->data; - RtpSession * sourceSession = fecStream->getSourceSession(); + FecStreamCxx *fecStream = (FecStreamCxx *)m->data; + RtpSession *sourceSession = fecStream->getSourceSession(); uint32_t ssrc = rtp_get_ssrc(packet); - if(ssrc == rtp_session_get_recv_ssrc(sourceSession)){ + if (ssrc == rtp_session_get_recv_ssrc(sourceSession)) { fecStream->onNewSourcePacketRecieved(packet); } return (int)msgdsize(packet); } -void ortp::modifierFree(struct _RtpTransportModifier *m){ +void ortp::modifierFree(struct _RtpTransportModifier *m) { ortp_free(m); } void FecStreamCxx::onNewSourcePacketSent(mblk_t *packet) { @@ -101,14 +101,12 @@ void FecStreamCxx::onNewSourcePacketSent(mblk_t *packet) { msgpullup(packet, -1); // To fix : mediastream tool sends two packets with seqnum = 0. The first one is degenerated so we dont take it. - if (rtp_get_version(packet) != 2) - return; + if (rtp_get_version(packet) != 2) return; std::shared_ptr source(new FecSourcePacket(packet)); if (mEncoder.isFull()) { mEncoder.reset(seqnum); - } mEncoder.add(*source); @@ -119,7 +117,7 @@ void FecStreamCxx::onNewSourcePacketSent(mblk_t *packet) { rtp_set_seqnumber(rowRepair, rtp_session_get_seq_number(mFecSession)); // ortp_message("row repair sended [%u] | %u", timestamp, rtp_get_seqnumber(rowRepair)); rtp_session_sendm_with_ts(mFecSession, rowRepair, timestamp); - + mStats.row_repair_sended++; } if (parameters->D > 1 && mEncoder.isColFull()) { @@ -138,22 +136,19 @@ void FecStreamCxx::onNewSourcePacketRecieved(mblk_t *packet) { uint16_t seqnum; msgpullup(packet, -1); - if (rtp_get_version(packet) != 2) - return; + if (rtp_get_version(packet) != 2) return; seqnum = rtp_get_seqnumber(packet); std::shared_ptr source(new FecSourcePacket(packet)); mCluster.add(seqnum, source); } -void FecStreamCxx::recieveRepairPacket(uint32_t timestamp){ +void FecStreamCxx::recieveRepairPacket(uint32_t timestamp) { - mblk_t * repair_packet = rtp_session_recvm_with_ts(mFecSession, timestamp); - - if (repair_packet == NULL) - return; - if (mCluster.repairPacketsTooOld(*parameters)) - mCluster.clearRepairPackets(); + mblk_t *repair_packet = rtp_session_recvm_with_ts(mFecSession, timestamp); + + if (repair_packet == NULL) return; + if (mCluster.repairPacketsTooOld(*parameters)) mCluster.clearRepairPackets(); std::shared_ptr repair(new FecRepairPacket(repair_packet)); mCluster.add(repair); @@ -162,7 +157,7 @@ void FecStreamCxx::printStats() { double initialLossRate = (double)mStats.packets_lost / (double)mSourceSession->stats.packet_recv; double residualLossRate = - ((double)(mStats.packets_lost - mStats.packets_recovered) / (double)mSourceSession->stats.packet_recv); + ((double)(mStats.packets_lost - mStats.packets_recovered) / (double)mSourceSession->stats.packet_recv); double recoveringRate = (double)mStats.packets_recovered / (double)mStats.packets_lost; ortp_log(ORTP_MESSAGE, "==========================================================="); @@ -185,22 +180,21 @@ mblk_t *FecStreamCxx::findMissingPacket(uint16_t seqnum) { mCluster.repair2D(); auto packet = mCluster.getSourcePacket(seqnum); mStats.packets_lost++; - if (packet != nullptr) - { - mblk_t * mp = packet->getPacketCopy(); - RtpTransport * transport = NULL; - RtpBundle * bundle = (RtpBundle *) mSourceSession->bundle; + if (packet != nullptr) { + mblk_t *mp = packet->getPacketCopy(); + RtpTransport *transport = NULL; + RtpBundle *bundle = (RtpBundle *)mSourceSession->bundle; RtpSession *session = rtp_bundle_get_primary_session(bundle); rtp_session_get_transports(session, &transport, NULL); - if(meta_rtp_transport_apply_all_except_one_on_recieve(transport, mModifier, mp) >= 0){ - ortp_message("Source packet reconstructed : SeqNum = %d;" ,(int)rtp_get_seqnumber(mp)); + if (meta_rtp_transport_apply_all_except_one_on_recieve(transport, mModifier, mp) >= 0) { + ortp_message("Source packet reconstructed : SeqNum = %d;", (int)rtp_get_seqnumber(mp)); mStats.packets_recovered++; } return mp; } else { return nullptr; - } + } } FecParameters *fec_params_new(uint8_t L, uint8_t D, uint32_t repairWindow) { FecParameters *fecParams = (FecParameters *)ortp_malloc0(sizeof(FecParameters)); @@ -217,7 +211,7 @@ Bitstring::Bitstring(const mblk_t *packet) { size_t payload_size = msgdsize(packet) - RTP_FIXED_HEADER_SIZE; mBuffer[0] = - rtp_get_version(packet) << 6 | rtp_get_padbit(packet) << 5 | rtp_get_extbit(packet) << 4 | rtp_get_cc(packet); + rtp_get_version(packet) << 6 | rtp_get_padbit(packet) << 5 | rtp_get_extbit(packet) << 4 | rtp_get_cc(packet); mBuffer[1] = rtp_get_markbit(packet) << 7 | rtp_get_payload_type(packet); setTimestamp((uint32_t)rtp_get_timestamp(packet)); setLength((uint16_t)payload_size); @@ -305,12 +299,15 @@ mblk_t *FecSourcePacket::transfer() { } return nullptr; } -FecRepairPacket::FecRepairPacket(struct _RtpSession *fecSession, struct _RtpSession *sourceSession, uint16_t seqnumBase, uint8_t L, uint8_t D) { +FecRepairPacket::FecRepairPacket( + struct _RtpSession *fecSession, struct _RtpSession *sourceSession, uint16_t seqnumBase, uint8_t L, uint8_t D) { mPacket = NULL; this->mSeqnumBase = seqnumBase; this->mL = L; this->mD = D; - mPacket = rtp_session_create_repair_packet_header(fecSession,sourceSession, 8*sizeof(uint8_t) + sizeof(uint32_t)); // allocate extra size for initBitString, SeqNumBase, L and D + mPacket = rtp_session_create_repair_packet_header( + fecSession, sourceSession, + 8 * sizeof(uint8_t) + sizeof(uint32_t)); // allocate extra size for initBitString, SeqNumBase, L and D // initBitstring memset(mPacket->b_wptr, 0, 8 * sizeof(uint8_t)); @@ -347,7 +344,6 @@ size_t FecRepairPacket::parametersStart(uint8_t **start) const { size_t bitstringSize = bitstringStart(start); *start += bitstringSize; return rtp_get_cc(mPacket) * sizeof(uint32_t); - } size_t FecRepairPacket::repairPayloadStart(uint8_t **start) const { size_t parametersSize = parametersStart(start); @@ -456,8 +452,7 @@ void FecEncoder::initRowRepairPackets(uint16_t seqnumBase) { } } void FecEncoder::initColRepairPackets(uint16_t seqnumBase) { - if (mRows <= 1) - return; + if (mRows <= 1) return; uint16_t seqnum = seqnumBase; int L = mColumns; int D = mRows; @@ -476,8 +471,7 @@ void FecEncoder::resetRowRepairPackets(uint16_t seqnumBase) { } } void FecEncoder::resetColRepairPackets(uint16_t seqnumBase) { - if (mRows <= 1) - return; + if (mRows <= 1) return; uint16_t seqnum = seqnumBase; for (size_t i = 0; i < mColRepair.size(); i++) { mColRepair[i]->reset(seqnum); @@ -537,10 +531,8 @@ std::map> const &RecieveCluster::getS std::shared_ptr RecieveCluster::getSourcePacket(uint16_t seqnum) { auto it = mSource.find(seqnum); - if (it != mSource.end()) - return it->second; - else - return nullptr; + if (it != mSource.end()) return it->second; + else return nullptr; } bool RecieveCluster::repairPacketsTooOld(FecParameters const ¶meters) { @@ -602,8 +594,7 @@ int RecieveCluster::repairOne(FecRepairPacket const &repairPacket) { recovery->setSsrc(repairPacket.getProtectedSsrc()); for (int i = 0; (unsigned long)i < seqnumList.size(); i++) { - if (seqnumList[i] == seqnumToRepair) - continue; + if (seqnumList[i] == seqnumToRepair) continue; std::shared_ptr sourceP = getSourcePacket(seqnumList[i]); recovery->addPayload(*sourceP); } @@ -634,8 +625,7 @@ int RecieveCluster::repair2D() { if (num_recovered_so_far > num_recovered_until_this_iteration) { num_recovered_until_this_iteration = num_recovered_so_far; - } else - break; + } else break; } while (1); return num_recovered_until_this_iteration; diff --git a/src/fecstream.h b/src/fecstream.h index b41c41dd..92dd7f19 100644 --- a/src/fecstream.h +++ b/src/fecstream.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -29,38 +29,38 @@ namespace ortp { #ifdef _WIN32 - // Disable C4251 triggered by need to export all stl template classes - #pragma warning(disable: 4251) +// Disable C4251 triggered by need to export all stl template classes +#pragma warning(disable : 4251) #endif // ifdef _WIN32 class ORTP_PUBLIC Bitstring { - private: +private: uint8_t mBuffer[8]; - public: +public: Bitstring(); Bitstring(const mblk_t *packet); void add(Bitstring const &other); void reset(); void write(mblk_t *packet); uint16_t getHeader() const { - return *(uint16_t *) &mBuffer[0]; + return *(uint16_t *)&mBuffer[0]; }; uint32_t getTimestamp() const { - return *(uint32_t *) &mBuffer[2]; + return *(uint32_t *)&mBuffer[2]; }; uint16_t getLength() const { - return *(uint16_t *)&mBuffer[6]; - }; + return *(uint16_t *)&mBuffer[6]; + }; void setHeader(uint16_t *h) { *(uint16_t *)&mBuffer[0] = *(uint16_t *)h; }; void setLength(uint16_t l) { - *(uint16_t *) &mBuffer[6] = (uint16_t) l; + *(uint16_t *)&mBuffer[6] = (uint16_t)l; }; void setTimestamp(uint32_t t) { - *(uint32_t *) &mBuffer[2] = t; + *(uint32_t *)&mBuffer[2] = t; }; bool equals(Bitstring const &other) { return (memcmp(&mBuffer[0], &other.mBuffer[0], 8) == 0); @@ -70,11 +70,11 @@ class ORTP_PUBLIC Bitstring { class ORTP_PUBLIC FecSourcePacket { - private: +private: mblk_t *mPacket; Bitstring mBitstring; - public: +public: FecSourcePacket(struct _RtpSession *session, const Bitstring &bs); FecSourcePacket(struct _RtpSession *session); FecSourcePacket(const mblk_t *incoming); @@ -99,10 +99,10 @@ class ORTP_PUBLIC FecSourcePacket { return mBitstring; } mblk_t *transfer(); - void setSsrc(uint32_t ssrc){ - rtp_set_ssrc(mPacket,ssrc); + void setSsrc(uint32_t ssrc) { + rtp_set_ssrc(mPacket, ssrc); }; - void setSequenceNumber(uint16_t seqnum){ + void setSequenceNumber(uint16_t seqnum) { rtp_set_seqnumber(mPacket, seqnum); }; ~FecSourcePacket() { @@ -113,19 +113,20 @@ class ORTP_PUBLIC FecSourcePacket { }; class ORTP_PUBLIC FecRepairPacket { - private: +private: mblk_t *mPacket; uint8_t mL; uint8_t mD; uint16_t mSeqnumBase; - public: +public: FecRepairPacket(); FecRepairPacket(const mblk_t *repairPacket); FecRepairPacket(const FecRepairPacket &other) = delete; FecRepairPacket &operator=(const FecRepairPacket &other) = delete; - FecRepairPacket(struct _RtpSession *fecSession, struct _RtpSession *sourceSession, uint16_t seqnumBase, uint8_t L, uint8_t D); + FecRepairPacket( + struct _RtpSession *fecSession, struct _RtpSession *sourceSession, uint16_t seqnumBase, uint8_t L, uint8_t D); void addBitstring(Bitstring const &bitstring); size_t bitstringStart(uint8_t **start) const; Bitstring extractBitstring() const; @@ -162,8 +163,7 @@ class ORTP_PUBLIC FecRepairPacket { return mPacket; }; mblk_t *getCopy() { - if (mPacket) - return copymsg(mPacket); + if (mPacket) return copymsg(mPacket); return nullptr; } ~FecRepairPacket() { @@ -175,7 +175,7 @@ class ORTP_PUBLIC FecRepairPacket { class ORTP_PUBLIC FecEncoder { - private: +private: std::vector> mRowRepair; std::vector> mColRepair; RtpSession *mFecSession; @@ -190,9 +190,7 @@ class ORTP_PUBLIC FecEncoder { void initColRepairPackets(uint16_t seqnumBase); void resetColRepairPackets(uint16_t seqnumBase); - public: - - +public: FecEncoder(){}; FecEncoder(FecParameters *parameters); void init(struct _RtpSession *fecSession, struct _RtpSession *sourceSession); @@ -241,19 +239,16 @@ class ORTP_PUBLIC FecEncoder { class ORTP_PUBLIC RecieveCluster { - private: - +private: uint32_t mRepairWindow = 200000; RtpSession *mSession; - RtpTransportModifier * mModifier; + RtpTransportModifier *mModifier; std::map> mSource; std::vector> mRowRepair; std::vector> mColRepair; void addRepair(FecSourcePacket &source, FecRepairPacket const &repair); - - public: - +public: RecieveCluster(struct _RtpSession *session) { this->mSession = session; }; @@ -271,7 +266,7 @@ class ORTP_PUBLIC RecieveCluster { int repairOne(FecRepairPacket const &repairPacket); int repair1D(bool interleaved); int repair2D(); - void setModifier(struct _RtpTransportModifier * modifier){ + void setModifier(struct _RtpTransportModifier *modifier) { this->mModifier = modifier; }; uint32_t getRepairWindow() { @@ -283,7 +278,7 @@ class ORTP_PUBLIC RecieveCluster { class ORTP_PUBLIC FecStreamCxx { - private: +private: FecParameters *parameters; RtpSession *mSourceSession; RtpSession *mFecSession; @@ -292,19 +287,19 @@ class ORTP_PUBLIC FecStreamCxx { fec_stats mStats; RtpTransportModifier *mModifier; - public: +public: FecStreamCxx(struct _RtpSession *source, struct _RtpSession *fec, FecParameters *fecParams); void init(); - static int processOnSend(struct _RtpTransportModifier *m,mblk_t *packet); - static int processOnRecieve(struct _RtpTransportModifier *m,mblk_t *packet); + static int processOnSend(struct _RtpTransportModifier *m, mblk_t *packet); + static int processOnRecieve(struct _RtpTransportModifier *m, mblk_t *packet); void onNewSourcePacketSent(mblk_t *packet); void onNewSourcePacketRecieved(mblk_t *packet); void recieveRepairPacket(uint32_t timestamp); mblk_t *findMissingPacket(uint16_t seqnum); - RtpSession *getFecSession() const{ + RtpSession *getFecSession() const { return mFecSession; }; - RtpSession *getSourceSession() const{ + RtpSession *getSourceSession() const { return mSourceSession; }; fec_stats *getStats() { @@ -314,7 +309,6 @@ class ORTP_PUBLIC FecStreamCxx { ~FecStreamCxx(){}; }; - void modifierFree(struct _RtpTransportModifier *m); } // namespace ortp #endif diff --git a/src/jitterctl.c b/src/jitterctl.c index a630c9e3..bb0b1b55 100644 --- a/src/jitterctl.c +++ b/src/jitterctl.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -27,11 +27,11 @@ #ifdef HAVE_CONFIG_H #include "ortp-config.h" #endif -#include "ortp/rtpsession.h" -#include "ortp/payloadtype.h" #include "ortp/ortp.h" -#include "utils.h" +#include "ortp/payloadtype.h" +#include "ortp/rtpsession.h" #include "rtpsession_priv.h" +#include "utils.h" #include #define JC_BETA .01 @@ -39,88 +39,84 @@ #include "jitterctl.h" -void jitter_control_init(JitterControl *ctl, PayloadType *payload){ - ctl->count=0; - ctl->clock_offset_ts=0; - ctl->prev_clock_offset_ts=0; - ctl->jitter=0; - ctl->inter_jitter=0; - ctl->cum_jitter_buffer_count=0; - ctl->cum_jitter_buffer_size=0; - ctl->corrective_slide=0; - - ctl->clock_rate=8000; - ctl->adapt_refresh_prev_ts=0; - - if (payload!=NULL){ - jitter_control_set_payload(ctl,payload); +void jitter_control_init(JitterControl *ctl, PayloadType *payload) { + ctl->count = 0; + ctl->clock_offset_ts = 0; + ctl->prev_clock_offset_ts = 0; + ctl->jitter = 0; + ctl->inter_jitter = 0; + ctl->cum_jitter_buffer_count = 0; + ctl->cum_jitter_buffer_size = 0; + ctl->corrective_slide = 0; + + ctl->clock_rate = 8000; + ctl->adapt_refresh_prev_ts = 0; + + if (payload != NULL) { + jitter_control_set_payload(ctl, payload); } } - -void jitter_control_enable_adaptive(JitterControl *ctl, bool_t val){ - ctl->params.adaptive=val; +void jitter_control_enable_adaptive(JitterControl *ctl, bool_t val) { + ctl->params.adaptive = val; } -void jitter_control_set_payload(JitterControl *ctl, PayloadType *pt){ - ctl->jitt_comp_ts = - (int) (((double) ctl->params.nom_size / 1000.0) * (pt->clock_rate)); +void jitter_control_set_payload(JitterControl *ctl, PayloadType *pt) { + ctl->jitt_comp_ts = (int)(((double)ctl->params.nom_size / 1000.0) * (pt->clock_rate)); /*make correction by not less than 10ms */ - ctl->corrective_step=(int) (0.01 * (float)pt->clock_rate); - ctl->adapt_jitt_comp_ts=ctl->jitt_comp_ts; - ctl->clock_rate=pt->clock_rate; + ctl->corrective_step = (int)(0.01 * (float)pt->clock_rate); + ctl->adapt_jitt_comp_ts = ctl->jitt_comp_ts; + ctl->clock_rate = pt->clock_rate; } - -void jitter_control_dump_stats(JitterControl *ctl){ +void jitter_control_dump_stats(JitterControl *ctl) { ortp_message("JitterControl:\n\tslide=%g,jitter=%g,adapt_jitt_comp_ts=%i,corrective_slide=%i, count=%i", - (double)ctl->clock_offset_ts,ctl->jitter, ctl->adapt_jitt_comp_ts, ctl->corrective_slide,ctl->count); + (double)ctl->clock_offset_ts, ctl->jitter, ctl->adapt_jitt_comp_ts, ctl->corrective_slide, ctl->count); } /*the goal of this method is to compute "corrective_slide": a timestamp unit'd value to be added to recv timestamp to make them reflect the instant they are delivered by the jitter buffer. */ -void jitter_control_update_corrective_slide(JitterControl *ctl){ +void jitter_control_update_corrective_slide(JitterControl *ctl) { int tmp; - tmp=(int)(ctl->clock_offset_ts-ctl->prev_clock_offset_ts); - if (tmp>ctl->corrective_step) { - ctl->corrective_slide+=ctl->corrective_step; - ctl->prev_clock_offset_ts=ctl->clock_offset_ts+ctl->corrective_step; - } - else if (tmp<-ctl->corrective_step) { - ctl->corrective_slide-=ctl->corrective_step; - ctl->prev_clock_offset_ts=ctl->clock_offset_ts-ctl->corrective_step; + tmp = (int)(ctl->clock_offset_ts - ctl->prev_clock_offset_ts); + if (tmp > ctl->corrective_step) { + ctl->corrective_slide += ctl->corrective_step; + ctl->prev_clock_offset_ts = ctl->clock_offset_ts + ctl->corrective_step; + } else if (tmp < -ctl->corrective_step) { + ctl->corrective_slide -= ctl->corrective_step; + ctl->prev_clock_offset_ts = ctl->clock_offset_ts - ctl->corrective_step; } } -void jitter_control_update_size(JitterControl *ctl, queue_t *q){ - mblk_t *newest=qlast(q); - mblk_t *oldest=qbegin(q); - uint32_t newest_ts,oldest_ts; - if (newest==NULL) return; - newest_ts=rtp_get_timestamp(newest); - oldest_ts=rtp_get_timestamp(oldest); +void jitter_control_update_size(JitterControl *ctl, queue_t *q) { + mblk_t *newest = qlast(q); + mblk_t *oldest = qbegin(q); + uint32_t newest_ts, oldest_ts; + if (newest == NULL) return; + newest_ts = rtp_get_timestamp(newest); + oldest_ts = rtp_get_timestamp(oldest); ctl->cum_jitter_buffer_count++; - ctl->cum_jitter_buffer_size+=(uint32_t)(newest_ts-oldest_ts); + ctl->cum_jitter_buffer_size += (uint32_t)(newest_ts - oldest_ts); } -float jitter_control_compute_mean_size(JitterControl *ctl){ - if (ctl->cum_jitter_buffer_count!=0){ - double tmp=((double)ctl->cum_jitter_buffer_size)/(double)ctl->cum_jitter_buffer_count; - ctl->cum_jitter_buffer_size=0; - ctl->cum_jitter_buffer_count=0; - ctl->jitter_buffer_mean_size = 1000.0f*(float)tmp/(float)ctl->clock_rate; +float jitter_control_compute_mean_size(JitterControl *ctl) { + if (ctl->cum_jitter_buffer_count != 0) { + double tmp = ((double)ctl->cum_jitter_buffer_size) / (double)ctl->cum_jitter_buffer_count; + ctl->cum_jitter_buffer_size = 0; + ctl->cum_jitter_buffer_count = 0; + ctl->jitter_buffer_mean_size = 1000.0f * (float)tmp / (float)ctl->clock_rate; return ctl->jitter_buffer_mean_size; } return 0; } -void rtp_session_init_jitter_buffer(RtpSession *session){ - PayloadType *payload=NULL; - - if (session->rcv.pt!=-1) { - payload = rtp_profile_get_payload (session->rcv.profile,session->rcv.pt); - }/*else not set yet */ - jitter_control_init(&session->rtp.jittctl,payload); +void rtp_session_init_jitter_buffer(RtpSession *session) { + PayloadType *payload = NULL; + + if (session->rcv.pt != -1) { + payload = rtp_profile_get_payload(session->rcv.profile, session->rcv.pt); + } /*else not set yet */ + jitter_control_init(&session->rtp.jittctl, payload); } /** @@ -130,129 +126,127 @@ void rtp_session_init_jitter_buffer(RtpSession *session){ * Sets the time interval for which packet are buffered instead of being delivered to the * application. **/ -void -rtp_session_set_jitter_compensation (RtpSession * session, int milisec) -{ +void rtp_session_set_jitter_compensation(RtpSession *session, int milisec) { session->rtp.jittctl.params.min_size = session->rtp.jittctl.params.nom_size = milisec; rtp_session_init_jitter_buffer(session); } -void rtp_session_enable_adaptive_jitter_compensation(RtpSession *session, bool_t val){ - jitter_control_enable_adaptive(&session->rtp.jittctl,val); +void rtp_session_enable_adaptive_jitter_compensation(RtpSession *session, bool_t val) { + jitter_control_enable_adaptive(&session->rtp.jittctl, val); } -bool_t rtp_session_adaptive_jitter_compensation_enabled(RtpSession *session){ +bool_t rtp_session_adaptive_jitter_compensation_enabled(RtpSession *session) { return session->rtp.jittctl.params.adaptive; } -void rtp_session_enable_jitter_buffer(RtpSession *session, bool_t enabled){ +void rtp_session_enable_jitter_buffer(RtpSession *session, bool_t enabled) { session->rtp.jittctl.params.enabled = enabled; - session->flags|=RTP_SESSION_RECV_SYNC; + session->flags |= RTP_SESSION_RECV_SYNC; } -bool_t rtp_session_jitter_buffer_enabled(const RtpSession *session){ +bool_t rtp_session_jitter_buffer_enabled(const RtpSession *session) { return session->rtp.jittctl.params.enabled; } -void rtp_session_set_jitter_buffer_params(RtpSession *session, const JBParameters *par){ +void rtp_session_set_jitter_buffer_params(RtpSession *session, const JBParameters *par) { if (par == &session->rtp.jittctl.params) return; - memcpy(&session->rtp.jittctl.params, par, sizeof (JBParameters)); - //rtp_session_init_jitter_buffer(session); + memcpy(&session->rtp.jittctl.params, par, sizeof(JBParameters)); + // rtp_session_init_jitter_buffer(session); session->rtp.jittctl.jb_size_updated = TRUE; } -void rtp_session_get_jitter_buffer_params(RtpSession *session, JBParameters *par){ +void rtp_session_get_jitter_buffer_params(RtpSession *session, JBParameters *par) { memcpy(par, &session->rtp.jittctl.params, sizeof(JBParameters)); } - /* The algorithm computes two values: - slide: an average of difference between the expected and the socket-received timestamp - jitter: an average of the absolute value of the difference between socket-received timestamp and slide. - slide is used to make clock-slide detection and correction. - jitter is added to the initial jitt_comp_time value. It compensates bursty packets arrival (packets - not arriving at regular interval ). + slide: an average of difference between the expected and the socket-received timestamp + jitter: an average of the absolute value of the difference between socket-received timestamp and slide. + slide is used to make clock-slide detection and correction. + jitter is added to the initial jitt_comp_time value. It compensates bursty packets arrival (packets + not arriving at regular interval ). */ -void jitter_control_new_packet(JitterControl *ctl, uint32_t packet_ts, uint32_t cur_str_ts){ - switch (ctl->params.buffer_algorithm){ +void jitter_control_new_packet(JitterControl *ctl, uint32_t packet_ts, uint32_t cur_str_ts) { + switch (ctl->params.buffer_algorithm) { case OrtpJitterBufferBasic: - jitter_control_new_packet_basic (ctl, packet_ts, cur_str_ts); - break; + jitter_control_new_packet_basic(ctl, packet_ts, cur_str_ts); + break; case OrtpJitterBufferRecursiveLeastSquare: - jitter_control_new_packet_rls (ctl, packet_ts, cur_str_ts); - break; + jitter_control_new_packet_rls(ctl, packet_ts, cur_str_ts); + break; default: ortp_fatal("No such new packet strategy: %d", ctl->params.buffer_algorithm); - break; + break; } ctl->count++; } -static void jitter_control_update_interarrival_jitter(JitterControl *ctl, int32_t diff){ +static void jitter_control_update_interarrival_jitter(JitterControl *ctl, int32_t diff) { /*compute interarrival jitter*/ int32_t delta; - delta=diff-ctl->olddiff; - ctl->inter_jitter=(float) (ctl->inter_jitter+ (( (float)abs(delta) - ctl->inter_jitter)*(1/16.0))); - ctl->olddiff=diff; + delta = diff - ctl->olddiff; + ctl->inter_jitter = (float)(ctl->inter_jitter + (((float)abs(delta) - ctl->inter_jitter) * (1 / 16.0))); + ctl->olddiff = diff; } -void jitter_control_new_packet_basic(JitterControl *ctl, uint32_t packet_ts, uint32_t cur_str_ts){ +void jitter_control_new_packet_basic(JitterControl *ctl, uint32_t packet_ts, uint32_t cur_str_ts) { int32_t diff = packet_ts - cur_str_ts; - double gap,slide; - - if (ctl->count==0){ - ctl->clock_offset_ts=ctl->prev_clock_offset_ts=diff; - slide=(double)diff; - ctl->olddiff=diff; - ctl->jitter=0; - }else{ - slide=((double)ctl->clock_offset_ts*(1-JC_BETA)) + ((double)diff*JC_BETA); + double gap, slide; + + if (ctl->count == 0) { + ctl->clock_offset_ts = ctl->prev_clock_offset_ts = diff; + slide = (double)diff; + ctl->olddiff = diff; + ctl->jitter = 0; + } else { + slide = ((double)ctl->clock_offset_ts * (1 - JC_BETA)) + ((double)diff * JC_BETA); } - gap=(double)diff - slide; - gap=gap<0 ? -gap : 0; /*compute only for late packets*/ - ctl->jitter=(float) ((ctl->jitter*(1-JC_GAMMA)) + (gap*JC_GAMMA)); + gap = (double)diff - slide; + gap = gap < 0 ? -gap : 0; /*compute only for late packets*/ + ctl->jitter = (float)((ctl->jitter * (1 - JC_GAMMA)) + (gap * JC_GAMMA)); jitter_control_update_interarrival_jitter(ctl, diff); - - if (ctl->params.adaptive){ - if (ctl->count%50==0) { - ctl->adapt_jitt_comp_ts=(int) MAX(ctl->jitt_comp_ts,2*ctl->jitter); - //jitter_control_dump_stats(ctl); + + if (ctl->params.adaptive) { + if (ctl->count % 50 == 0) { + ctl->adapt_jitt_comp_ts = (int)MAX(ctl->jitt_comp_ts, 2 * ctl->jitter); + // jitter_control_dump_stats(ctl); } - ctl->clock_offset_ts=(int32_t)slide; - }else { + ctl->clock_offset_ts = (int32_t)slide; + } else { /*ctl->slide and jitter size are not updated*/ } } -static bool_t time_for_log(JitterControl *ctl, uint32_t cur_str_ts){ +static bool_t time_for_log(JitterControl *ctl, uint32_t cur_str_ts) { int32_t elapsed = (int32_t)(cur_str_ts - ctl->last_log_ts); - if (elapsed >= 5*ctl->clock_rate){ + if (elapsed >= 5 * ctl->clock_rate) { ctl->last_log_ts = cur_str_ts; return TRUE; } return FALSE; } -static uint32_t jitter_control_local_ts_to_remote_ts_rls(JitterControl *ctl, uint32_t local_ts){ - return (uint32_t)( (int64_t)(ctl->capped_clock_ratio*(double)(local_ts - ctl->local_ts_start) + ctl->clock_offset_ts)); +static uint32_t jitter_control_local_ts_to_remote_ts_rls(JitterControl *ctl, uint32_t local_ts) { + return ( + uint32_t)((int64_t)(ctl->capped_clock_ratio * (double)(local_ts - ctl->local_ts_start) + ctl->clock_offset_ts)); } /**************************** RLS *********************************/ -void jitter_control_new_packet_rls(JitterControl *ctl, uint32_t packet_ts, uint32_t cur_str_ts){ +void jitter_control_new_packet_rls(JitterControl *ctl, uint32_t packet_ts, uint32_t cur_str_ts) { int32_t diff = packet_ts - cur_str_ts; int deviation; - - if (ctl->is_diverging){ + + if (ctl->is_diverging) { int32_t elapsed = (int32_t)(cur_str_ts - ctl->diverged_start_ts); - if (elapsed >= ctl->clock_rate){ + if (elapsed >= ctl->clock_rate) { ortp_error("Jitter buffer stays unconverged for one second, reset it."); ctl->count = 0; ctl->is_diverging = FALSE; } } - if (ctl->count==0){ + if (ctl->count == 0) { ctl->clock_offset_ts = ctl->prev_clock_offset_ts = (int32_t)packet_ts; /* * Offset compensation. In order to avoid managing the rollover of the uint32_t timestamp, the timestamps passed @@ -272,92 +266,91 @@ void jitter_control_new_packet_rls(JitterControl *ctl, uint32_t packet_ts, uint3 ortp_kalman_rls_init(&ctl->kalman_rls, 1.0, 0.0); ctl->capped_clock_ratio = ctl->kalman_rls.m; } - + /*Compute the deviation from the value predicted by the kalman filter*/ deviation = abs((int32_t)(packet_ts - jitter_control_local_ts_to_remote_ts_rls(ctl, cur_str_ts))); - + /*update the kalman filter*/ ortp_kalman_rls_record(&ctl->kalman_rls, cur_str_ts - ctl->local_ts_start, packet_ts - ctl->remote_ts_start); ctl->capped_clock_ratio = MAX(.5, MIN(ctl->kalman_rls.m, 2)); - - if (.5fkalman_rls.m && ctl->kalman_rls.m<2.f){ + + if (.5f < ctl->kalman_rls.m && ctl->kalman_rls.m < 2.f) { /*realistic clock ratio, the filter is well converged*/ ctl->clock_offset_ts = (int32_t)((int32_t)ctl->kalman_rls.b + ctl->remote_ts_start); - if (ctl->is_diverging){ + if (ctl->is_diverging) { ctl->is_diverging = FALSE; } - }else{ + } else { ctl->clock_offset_ts = diff; - if (!ctl->is_diverging){ + if (!ctl->is_diverging) { ctl->is_diverging = TRUE; ctl->diverged_start_ts = cur_str_ts; } } - + /*ortp_message("deviation=%g ms", 1000.0*deviation/(double)ctl->clock_rate);*/ - + jitter_control_update_interarrival_jitter(ctl, diff); cur_str_ts -= ctl->local_ts_start; - - if (ctl->params.adaptive || ctl->jb_size_updated){ + + if (ctl->params.adaptive || ctl->jb_size_updated) { bool_t max_updated = ortp_extremum_record_max(&ctl->max_ts_deviation, cur_str_ts, (float)deviation); - float max_deviation = MAX(ortp_extremum_get_previous(&ctl->max_ts_deviation), ortp_extremum_get_current(&ctl->max_ts_deviation)); - if (max_updated && max_deviation > ctl->adapt_jitt_comp_ts){ - ctl->adapt_jitt_comp_ts=(int)max_deviation; + float max_deviation = + MAX(ortp_extremum_get_previous(&ctl->max_ts_deviation), ortp_extremum_get_current(&ctl->max_ts_deviation)); + if (max_updated && max_deviation > ctl->adapt_jitt_comp_ts) { + ctl->adapt_jitt_comp_ts = (int)max_deviation; ctl->jb_size_updated = TRUE; - }else if (max_deviation < ctl->params.ramp_threshold/100.f*ctl->adapt_jitt_comp_ts){ + } else if (max_deviation < ctl->params.ramp_threshold / 100.f * ctl->adapt_jitt_comp_ts) { /*Jitter is decreasing. Make a smooth descent to avoid dropping lot of packets*/ - if ( (int32_t)(cur_str_ts - ctl->adapt_refresh_prev_ts) > ((ctl->params.ramp_refresh_ms*ctl->clock_rate)/1000)) { + if ((int32_t)(cur_str_ts - ctl->adapt_refresh_prev_ts) > + ((ctl->params.ramp_refresh_ms * ctl->clock_rate) / 1000)) { ctl->adapt_jitt_comp_ts -= (ctl->params.ramp_step_ms * ctl->clock_rate) / 1000; ctl->jb_size_updated = TRUE; } } - if (ctl->jb_size_updated){ + if (ctl->jb_size_updated) { int min_size_ts = (ctl->params.min_size * ctl->clock_rate) / 1000; int max_size_ts = (ctl->params.max_size * ctl->clock_rate) / 1000; - if (ctl->adapt_jitt_comp_ts < min_size_ts){ + if (ctl->adapt_jitt_comp_ts < min_size_ts) { ctl->adapt_jitt_comp_ts = min_size_ts; - }else if (ctl->adapt_jitt_comp_ts > max_size_ts){ + } else if (ctl->adapt_jitt_comp_ts > max_size_ts) { ctl->adapt_jitt_comp_ts = max_size_ts; } ctl->adapt_refresh_prev_ts = cur_str_ts; ctl->jb_size_updated = FALSE; } } - if (time_for_log(ctl, cur_str_ts)){ - ortp_message("jitter buffer %s: target-size: %f ms, effective-size: %f (min: %i nom: %i, max: %i)",ctl->jb_size_updated ? "updated" : "stable", - ((float)ctl->adapt_jitt_comp_ts/(float)ctl->clock_rate)*1000.0, - ctl->jitter_buffer_mean_size, - ctl->params.min_size, ctl->params.nom_size, ctl->params.max_size); + if (time_for_log(ctl, cur_str_ts)) { + ortp_message("jitter buffer %s: target-size: %f ms, effective-size: %f (min: %i nom: %i, max: %i)", + ctl->jb_size_updated ? "updated" : "stable", + ((float)ctl->adapt_jitt_comp_ts / (float)ctl->clock_rate) * 1000.0, ctl->jitter_buffer_mean_size, + ctl->params.min_size, ctl->params.nom_size, ctl->params.max_size); ortp_message("jitter buffer rls stats: count=%d, clockrate=%i" - ", offset=%g clock_ratio=%g" - ", capped_offset=%i capped_clock_ratio=%f" - ", max_ts_deviation=%f prev_max_ts_deviation=%f" - ", deviation=%i" - ", RLS VARIABLES: P[0][0]=%f, P[1][0]=%f, P[0][1]=%f, P[1][1]=%f" - , ctl->count, ctl->clock_rate - , ctl->kalman_rls.b, ctl->kalman_rls.m - , (int) ctl->clock_offset_ts, (float)ctl->capped_clock_ratio - , ortp_extremum_get_current(&ctl->max_ts_deviation), ortp_extremum_get_previous(&ctl->max_ts_deviation) - , deviation - , ctl->kalman_rls.P[0][0], ctl->kalman_rls.P[1][0], ctl->kalman_rls.P[0][1], ctl->kalman_rls.P[1][1]); + ", offset=%g clock_ratio=%g" + ", capped_offset=%i capped_clock_ratio=%f" + ", max_ts_deviation=%f prev_max_ts_deviation=%f" + ", deviation=%i" + ", RLS VARIABLES: P[0][0]=%f, P[1][0]=%f, P[0][1]=%f, P[1][1]=%f", + ctl->count, ctl->clock_rate, ctl->kalman_rls.b, ctl->kalman_rls.m, (int)ctl->clock_offset_ts, + (float)ctl->capped_clock_ratio, ortp_extremum_get_current(&ctl->max_ts_deviation), + ortp_extremum_get_previous(&ctl->max_ts_deviation), deviation, ctl->kalman_rls.P[0][0], + ctl->kalman_rls.P[1][0], ctl->kalman_rls.P[0][1], ctl->kalman_rls.P[1][1]); } } -uint32_t jitter_control_get_compensated_timestamp(JitterControl *obj , uint32_t user_ts){ +uint32_t jitter_control_get_compensated_timestamp(JitterControl *obj, uint32_t user_ts) { uint32_t ret = 0; - switch (obj->params.buffer_algorithm){ + switch (obj->params.buffer_algorithm) { case OrtpJitterBufferBasic: - ret = (uint32_t)( (int64_t)user_ts+obj->clock_offset_ts-(int64_t)obj->adapt_jitt_comp_ts); - break; + ret = (uint32_t)((int64_t)user_ts + obj->clock_offset_ts - (int64_t)obj->adapt_jitt_comp_ts); + break; case OrtpJitterBufferRecursiveLeastSquare: ret = jitter_control_local_ts_to_remote_ts_rls(obj, user_ts) - obj->adapt_jitt_comp_ts; - break; + break; default: ortp_fatal("No such new packet strategy: %d", obj->params.buffer_algorithm); - break; + break; } return ret; } - diff --git a/src/jitterctl.h b/src/jitterctl.h index 24555ca2..edffd420 100644 --- a/src/jitterctl.h +++ b/src/jitterctl.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -32,7 +32,9 @@ void jitter_control_init(JitterControl *ctl, PayloadType *pt); void jitter_control_enable_adaptive(JitterControl *ctl, bool_t val); -static ORTP_INLINE bool_t jitter_control_adaptive_enabled(JitterControl *ctl) { return ctl->params.adaptive; } +static ORTP_INLINE bool_t jitter_control_adaptive_enabled(JitterControl *ctl) { + return ctl->params.adaptive; +} void jitter_control_set_payload(JitterControl *ctl, PayloadType *pt); void jitter_control_update_corrective_slide(JitterControl *ctl); void jitter_control_update_size(JitterControl *ctl, queue_t *q); @@ -42,6 +44,6 @@ void jitter_control_new_packet(JitterControl *ctl, uint32_t packet_ts, uint32_t void jitter_control_new_packet_basic(JitterControl *ctl, uint32_t packet_ts, uint32_t cur_str_ts); void jitter_control_new_packet_rls(JitterControl *ctl, uint32_t packet_ts, uint32_t cur_str_ts); -uint32_t jitter_control_get_compensated_timestamp(JitterControl *obj , uint32_t user_ts); +uint32_t jitter_control_get_compensated_timestamp(JitterControl *obj, uint32_t user_ts); #endif diff --git a/src/kalmanrls.c b/src/kalmanrls.c index 205ad14f..e4c36733 100644 --- a/src/kalmanrls.c +++ b/src/kalmanrls.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -20,7 +20,6 @@ #include "ortp/utils.h" - void ortp_kalman_rls_init(OrtpKalmanRLS *rls, double m0, double b0) { memset(rls, 0, sizeof(OrtpKalmanRLS)); rls->lambda = 1.; @@ -48,13 +47,11 @@ void ortp_kalman_rls_record(OrtpKalmanRLS *rls, double xmes, double ymes) { **/ double diff = ymes - estim; - rls->m = rls->m + diff * (a*e+b*f); - rls->b = rls->b + diff * (c*e+d*f); + rls->m = rls->m + diff * (a * e + b * f); + rls->b = rls->b + diff * (c * e + d * f); - rls->P[0][0] = (a - (e*a+f*b)*(e*a+f*c) / deno) * 1.f / rls->lambda; - rls->P[1][0] = (b - (e*a+f*b)*(e*b+f*d) / deno) * 1.f / rls->lambda; - rls->P[0][1] = (c - (e*c+f*d)*(e*a+f*c) / deno) * 1.f / rls->lambda; - rls->P[1][1] = (d - (e*c+f*d)*(e*b+f*d) / deno) * 1.f / rls->lambda; + rls->P[0][0] = (a - (e * a + f * b) * (e * a + f * c) / deno) * 1.f / rls->lambda; + rls->P[1][0] = (b - (e * a + f * b) * (e * b + f * d) / deno) * 1.f / rls->lambda; + rls->P[0][1] = (c - (e * c + f * d) * (e * a + f * c) / deno) * 1.f / rls->lambda; + rls->P[1][1] = (d - (e * c + f * d) * (e * b + f * d) / deno) * 1.f / rls->lambda; } - - diff --git a/src/logging.c b/src/logging.c index 6a44f023..7ab033bb 100644 --- a/src/logging.c +++ b/src/logging.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,24 +18,20 @@ * along with this program. If not, see . */ -#include "ortp/utils.h" #include "ortp/logging.h" +#include "ortp/utils.h" - - -void ortp_set_log_handler(OrtpLogFunc func){ +void ortp_set_log_handler(OrtpLogFunc func) { bctbx_set_log_handler(func); } -OrtpLogFunc ortp_get_log_handler(void){ +OrtpLogFunc ortp_get_log_handler(void) { return NULL; } /** *@param file a FILE pointer where to output the ortp logs. * **/ -void ortp_set_log_file(FILE *file){ +void ortp_set_log_file(FILE *file) { bctbx_set_log_file(file); } - - diff --git a/src/nack.c b/src/nack.c index 756629c2..dd2b1fad 100644 --- a/src/nack.c +++ b/src/nack.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,6 +18,8 @@ * along with this program. If not, see . */ +#include + #include "ortp/logging.h" #include "ortp/nack.h" @@ -77,7 +79,7 @@ static void generic_nack_received(const OrtpEventData *evd, OrtpNackContext *ctx } static int ortp_nack_rtp_process_on_send(RtpTransportModifier *t, mblk_t *msg) { - OrtpNackContext *userData = (OrtpNackContext *) t->data; + OrtpNackContext *userData = (OrtpNackContext *)t->data; if (rtp_get_version(msg) == 2) { bctbx_mutex_lock(&userData->sent_packets_mutex); @@ -93,16 +95,17 @@ static int ortp_nack_rtp_process_on_send(RtpTransportModifier *t, mblk_t *msg) { // Stock the packet before sending it putq(&userData->sent_packets, dupmsg(msg)); - //ortp_message("OrtpNackContext [%p]: Stocking packet with pid=%hu (seq=%hu)", userData, rtp_get_seqnumber(msg), userData->session->rtp.snd_seq); + // ortp_message("OrtpNackContext [%p]: Stocking packet with pid=%hu (seq=%hu)", userData, + // rtp_get_seqnumber(msg), userData->session->rtp.snd_seq); bctbx_mutex_unlock(&userData->sent_packets_mutex); } - return (int) msgdsize(msg); + return (int)msgdsize(msg); } -static int ortp_nack_rtp_process_on_receive(RtpTransportModifier *t, mblk_t *msg) { - return (int) msgdsize(msg); +static int ortp_nack_rtp_process_on_receive(BCTBX_UNUSED(RtpTransportModifier *t), mblk_t *msg) { + return (int)msgdsize(msg); } static int ortp_nack_rtcp_process_on_send(RtpTransportModifier *t, mblk_t *msg) { @@ -111,11 +114,11 @@ static int ortp_nack_rtcp_process_on_send(RtpTransportModifier *t, mblk_t *msg) do { if (rtcp_is_RTPFB(pullmsg) && rtcp_RTPFB_get_type(pullmsg) == RTCP_RTPFB_NACK) { - OrtpNackContext *userData = (OrtpNackContext *) t->data; + OrtpNackContext *userData = (OrtpNackContext *)t->data; OrtpEvent *ev; OrtpEventData *evd; JBParameters jitter_params; - int rtt = (int) userData->session->rtt; + int rtt = (int)userData->session->rtt; if (rtt == 0) rtt = 200; @@ -135,7 +138,8 @@ static int ortp_nack_rtcp_process_on_send(RtpTransportModifier *t, mblk_t *msg) rtp_session_set_jitter_buffer_params(userData->session, &jitter_params); - ortp_message("OrtpNackContext [%p]: Sending NACK... increasing jitter min size to %dms", userData, jitter_params.min_size); + ortp_message("OrtpNackContext [%p]: Sending NACK... increasing jitter min size to %dms", userData, + jitter_params.min_size); // Send an event that the video jitter has been updated so that we can update the audio too ev = ortp_event_new(ORTP_EVENT_JITTER_UPDATE_FOR_NACK); @@ -153,22 +157,24 @@ static int ortp_nack_rtcp_process_on_send(RtpTransportModifier *t, mblk_t *msg) } while (rtcp_next_packet(pullmsg)); freemsg(pullmsg); - return (int) msgdsize(msg); + return (int)msgdsize(msg); } -static int ortp_nack_rtcp_process_on_receive(RtpTransportModifier *t, mblk_t *msg) { - return (int) msgdsize(msg); +static int ortp_nack_rtcp_process_on_receive(BCTBX_UNUSED(RtpTransportModifier *t), mblk_t *msg) { + return (int)msgdsize(msg); } -static void ortp_nack_transport_modifier_destroy(RtpTransportModifier *tp) { +static void ortp_nack_transport_modifier_destroy(RtpTransportModifier *tp) { ortp_free(tp); } -static void ortp_nack_transport_modifier_new(OrtpNackContext* ctx, RtpTransportModifier **rtpt, RtpTransportModifier **rtcpt ) { +static void +ortp_nack_transport_modifier_new(OrtpNackContext *ctx, RtpTransportModifier **rtpt, RtpTransportModifier **rtcpt) { if (rtpt) { *rtpt = ortp_new0(RtpTransportModifier, 1); (*rtpt)->level = ORTP_RTP_TRANSPORT_MODIFIER_DEFAULT_LEVEL; - (*rtpt)->data = ctx; /* back link to get access to the other fields of the OrtpNackContext from the RtpTransportModifier structure */ + (*rtpt)->data = ctx; /* back link to get access to the other fields of the OrtpNackContext from the + RtpTransportModifier structure */ (*rtpt)->t_process_on_send = ortp_nack_rtp_process_on_send; (*rtpt)->t_process_on_receive = ortp_nack_rtp_process_on_receive; (*rtpt)->t_destroy = ortp_nack_transport_modifier_destroy; @@ -177,7 +183,8 @@ static void ortp_nack_transport_modifier_new(OrtpNackContext* ctx, RtpTransportM if (rtcpt) { *rtcpt = ortp_new0(RtpTransportModifier, 1); (*rtpt)->level = ORTP_RTP_TRANSPORT_MODIFIER_DEFAULT_LEVEL; - (*rtcpt)->data = ctx; /* back link to get access to the other fields of the OrtpNackContext from the RtpTransportModifier structure */ + (*rtcpt)->data = ctx; /* back link to get access to the other fields of the OrtpNackContext from the + RtpTransportModifier structure */ (*rtcpt)->t_process_on_send = ortp_nack_rtcp_process_on_send; (*rtcpt)->t_process_on_receive = ortp_nack_rtcp_process_on_receive; (*rtcpt)->t_destroy = ortp_nack_transport_modifier_destroy; @@ -213,11 +220,8 @@ OrtpNackContext *ortp_nack_context_new(OrtpEvDispatcher *evt) { rtp_session_enable_avpf_feature(userData->session, ORTP_AVPF_FEATURE_IMMEDIATE_NACK, TRUE); - ortp_ev_dispatcher_connect(userData->ev_dispatcher - , ORTP_EVENT_RTCP_PACKET_RECEIVED - , RTCP_RTPFB - , (OrtpEvDispatcherCb)generic_nack_received - , userData); + ortp_ev_dispatcher_connect(userData->ev_dispatcher, ORTP_EVENT_RTCP_PACKET_RECEIVED, RTCP_RTPFB, + (OrtpEvDispatcherCb)generic_nack_received, userData); return ortp_nack_configure_context(userData); } @@ -225,10 +229,8 @@ OrtpNackContext *ortp_nack_context_new(OrtpEvDispatcher *evt) { void ortp_nack_context_destroy(OrtpNackContext *ctx) { RtpTransport *rtpt = NULL, *rtcpt = NULL; - ortp_ev_dispatcher_disconnect(ctx->ev_dispatcher - , ORTP_EVENT_RTCP_PACKET_RECEIVED - , RTCP_RTPFB - , (OrtpEvDispatcherCb)generic_nack_received); + ortp_ev_dispatcher_disconnect(ctx->ev_dispatcher, ORTP_EVENT_RTCP_PACKET_RECEIVED, RTCP_RTPFB, + (OrtpEvDispatcherCb)generic_nack_received); rtp_session_enable_avpf_feature(ctx->session, ORTP_AVPF_FEATURE_IMMEDIATE_NACK, FALSE); @@ -258,7 +260,9 @@ void ortp_nack_context_process_timer(OrtpNackContext *ctx) { OrtpEventData *evd; JBParameters jitter_params; - ortp_message("OrtpNackContext [%p]: No NACK sent in the last %d seconds, decreasing jitter min size to %dms...", ctx, DECREASE_JITTER_DELAY / 1000, ctx->min_jitter_before_nack); + ortp_message( + "OrtpNackContext [%p]: No NACK sent in the last %d seconds, decreasing jitter min size to %dms...", ctx, + DECREASE_JITTER_DELAY / 1000, ctx->min_jitter_before_nack); rtp_session_get_jitter_buffer_params(ctx->session, &jitter_params); jitter_params.min_size = ctx->min_jitter_before_nack; diff --git a/src/netsim.c b/src/netsim.c index 74c8c1cd..a7a19e57 100644 --- a/src/netsim.c +++ b/src/netsim.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -21,42 +21,42 @@ #include "ortp-config.h" #endif #include "ortp/ortp.h" -#include "utils.h" #include "ortp/rtpsession.h" #include "rtpsession_priv.h" +#include "utils.h" #include static void rtp_session_schedule_outbound_network_simulator(RtpSession *session, ortpTimeSpec *sleep_until); -static OrtpNetworkSimulatorCtx* simulator_ctx_new(void){ - OrtpNetworkSimulatorCtx *ctx=(OrtpNetworkSimulatorCtx*)ortp_malloc0(sizeof(OrtpNetworkSimulatorCtx)); +static OrtpNetworkSimulatorCtx *simulator_ctx_new(void) { + OrtpNetworkSimulatorCtx *ctx = (OrtpNetworkSimulatorCtx *)ortp_malloc0(sizeof(OrtpNetworkSimulatorCtx)); qinit(&ctx->latency_q); qinit(&ctx->q); qinit(&ctx->send_q); - ortp_mutex_init(&ctx->mutex,NULL); + ortp_mutex_init(&ctx->mutex, NULL); return ctx; } static void ortp_network_simulator_dump_stats(OrtpNetworkSimulatorCtx *sim) { - int drop_by_flush=sim->latency_q.q_mcount+sim->q.q_mcount; - if (sim->total_count>0){ + int drop_by_flush = sim->latency_q.q_mcount + sim->q.q_mcount; + if (sim->total_count > 0) { ortp_message("Network simulation: dump stats. Statistics are:" - "%d/%d(%.1f%%, param=%.1f) packets dropped by loss, " - "%d/%d(%.1f%%) packets dropped by congestion, " - "%d/%d(%.1f%%) packets flushed." - , sim->drop_by_loss, sim->total_count, sim->drop_by_loss*100.f/sim->total_count, sim->params.loss_rate - , sim->drop_by_congestion, sim->total_count, sim->drop_by_congestion*100.f/sim->total_count - , drop_by_flush, sim->total_count, drop_by_flush*100.f/sim->total_count - ); + "%d/%d(%.1f%%, param=%.1f) packets dropped by loss, " + "%d/%d(%.1f%%) packets dropped by congestion, " + "%d/%d(%.1f%%) packets flushed.", + sim->drop_by_loss, sim->total_count, sim->drop_by_loss * 100.f / sim->total_count, + sim->params.loss_rate, sim->drop_by_congestion, sim->total_count, + sim->drop_by_congestion * 100.f / sim->total_count, drop_by_flush, sim->total_count, + drop_by_flush * 100.f / sim->total_count); } } -void ortp_network_simulator_destroy(OrtpNetworkSimulatorCtx *sim){ +void ortp_network_simulator_destroy(OrtpNetworkSimulatorCtx *sim) { ortp_network_simulator_dump_stats(sim); - flushq(&sim->latency_q,0); - flushq(&sim->q,0); - flushq(&sim->send_q,0); - if (sim->thread_started){ - sim->thread_started=FALSE; + flushq(&sim->latency_q, 0); + flushq(&sim->q, 0); + flushq(&sim->send_q, 0); + if (sim->thread_started) { + sim->thread_started = FALSE; ortp_thread_join(sim->thread, NULL); } ortp_mutex_destroy(&sim->mutex); @@ -64,69 +64,72 @@ void ortp_network_simulator_destroy(OrtpNetworkSimulatorCtx *sim){ } #ifndef _WIN32 -static const char *sched_policy_to_string(int policy){ - switch(policy){ - case SCHED_OTHER: return "SCHED_OTHER"; - case SCHED_RR: return "SCHED_RR"; - case SCHED_FIFO: return "SCHED_FIFO"; +static const char *sched_policy_to_string(int policy) { + switch (policy) { + case SCHED_OTHER: + return "SCHED_OTHER"; + case SCHED_RR: + return "SCHED_RR"; + case SCHED_FIFO: + return "SCHED_FIFO"; } return "SCHED_INVALID"; } #endif -static void set_high_prio(void){ +static void set_high_prio(void) { #ifndef _WIN32 - const char *sched_pref=getenv("ORTP_SIMULATOR_SCHED_POLICY"); - int policy=SCHED_OTHER; + const char *sched_pref = getenv("ORTP_SIMULATOR_SCHED_POLICY"); + int policy = SCHED_OTHER; struct sched_param param; - int result=0; - char* env_prio_c=NULL; + int result = 0; + char *env_prio_c = NULL; int min_prio, max_prio, env_prio; - if (sched_pref && strcasecmp(sched_pref,"SCHED_RR")==0){ - policy=SCHED_RR; - }else if (sched_pref && strcasecmp(sched_pref,"SCHED_FIFO")==0){ - policy=SCHED_FIFO; + if (sched_pref && strcasecmp(sched_pref, "SCHED_RR") == 0) { + policy = SCHED_RR; + } else if (sched_pref && strcasecmp(sched_pref, "SCHED_FIFO") == 0) { + policy = SCHED_FIFO; } - memset(¶m,0,sizeof(param)); + memset(¶m, 0, sizeof(param)); min_prio = sched_get_priority_min(policy); max_prio = sched_get_priority_max(policy); env_prio_c = getenv("ORTP_SIMULATOR_SCHED_PRIO"); - env_prio = (env_prio_c == NULL)?max_prio:atoi(env_prio_c); + env_prio = (env_prio_c == NULL) ? max_prio : atoi(env_prio_c); env_prio = MAX(MIN(env_prio, max_prio), min_prio); - param.sched_priority=env_prio; - if((result=pthread_setschedparam(pthread_self(),policy, ¶m))) { - ortp_warning("Ortp simulator: set pthread_setschedparam failed: %s",strerror(result)); + param.sched_priority = env_prio; + if ((result = pthread_setschedparam(pthread_self(), policy, ¶m))) { + ortp_warning("Ortp simulator: set pthread_setschedparam failed: %s", strerror(result)); } else { ortp_message("ortp network simulator: sched policy set to %s and priority value (%i)", - sched_policy_to_string(policy), param.sched_priority); + sched_policy_to_string(policy), param.sched_priority); } #endif } -static void * outboud_simulator_thread(void *ctx){ - RtpSession *session=(RtpSession*)ctx; - OrtpNetworkSimulatorCtx *sim=session->net_sim_ctx; +static void *outboud_simulator_thread(void *ctx) { + RtpSession *session = (RtpSession *)ctx; + OrtpNetworkSimulatorCtx *sim = session->net_sim_ctx; ortpTimeSpec sleep_until; set_high_prio(); - while(sim->thread_started){ - sleep_until.tv_sec=0; - sleep_until.tv_nsec=0; + while (sim->thread_started) { + sleep_until.tv_sec = 0; + sleep_until.tv_nsec = 0; rtp_session_schedule_outbound_network_simulator(session, &sleep_until); - if (sleep_until.tv_sec!=0) ortp_sleep_until(&sleep_until); + if (sleep_until.tv_sec != 0) ortp_sleep_until(&sleep_until); else bctbx_sleep_ms(1); } return NULL; } -const char *ortp_network_simulator_mode_to_string(OrtpNetworkSimulatorMode mode){ - switch(mode){ +const char *ortp_network_simulator_mode_to_string(OrtpNetworkSimulatorMode mode) { + switch (mode) { case OrtpNetworkSimulatorInbound: return "Inbound"; case OrtpNetworkSimulatorOutbound: @@ -139,86 +142,83 @@ const char *ortp_network_simulator_mode_to_string(OrtpNetworkSimulatorMode mode) return "invalid"; } -OrtpNetworkSimulatorMode ortp_network_simulator_mode_from_string(const char *str){ - if (strcasecmp(str,"Inbound")==0) return OrtpNetworkSimulatorInbound; - if (strcasecmp(str,"Outbound")==0) return OrtpNetworkSimulatorOutbound; - if (strcasecmp(str,"OutboundControlled")==0) return OrtpNetworkSimulatorOutboundControlled; +OrtpNetworkSimulatorMode ortp_network_simulator_mode_from_string(const char *str) { + if (strcasecmp(str, "Inbound") == 0) return OrtpNetworkSimulatorInbound; + if (strcasecmp(str, "Outbound") == 0) return OrtpNetworkSimulatorOutbound; + if (strcasecmp(str, "OutboundControlled") == 0) return OrtpNetworkSimulatorOutboundControlled; return OrtpNetworkSimulatorInvalid; } -void rtp_session_enable_network_simulation(RtpSession *session, const OrtpNetworkSimulatorParams *params){ - OrtpNetworkSimulatorCtx *sim=session->net_sim_ctx; - if (params->enabled){ - if (sim==NULL) { - sim=simulator_ctx_new(); +void rtp_session_enable_network_simulation(RtpSession *session, const OrtpNetworkSimulatorParams *params) { + OrtpNetworkSimulatorCtx *sim = session->net_sim_ctx; + if (params->enabled) { + if (sim == NULL) { + sim = simulator_ctx_new(); } else { ortp_network_simulator_dump_stats(sim); } - sim->drop_by_congestion=sim->drop_by_loss=sim->total_count=0; - sim->params=*params; - if (sim->params.jitter_burst_density>0 && sim->params.jitter_strength>0 && sim->params.max_bandwidth==0){ - sim->params.max_bandwidth=1024000; - ortp_message("Network simulation: jitter requested but max_bandwidth is not set. Using default value of %f bits/s.", - sim->params.max_bandwidth); + sim->drop_by_congestion = sim->drop_by_loss = sim->total_count = 0; + sim->params = *params; + if (sim->params.jitter_burst_density > 0 && sim->params.jitter_strength > 0 && sim->params.max_bandwidth == 0) { + sim->params.max_bandwidth = 1024000; + ortp_message( + "Network simulation: jitter requested but max_bandwidth is not set. Using default value of %f bits/s.", + sim->params.max_bandwidth); } - if (sim->params.max_bandwidth && sim->params.max_buffer_size==0) { - sim->params.max_buffer_size=(int)sim->params.max_bandwidth; - ortp_message("Network simulation: Max buffer size not set for RTP session [%p], using [%i]",session,sim->params.max_buffer_size); + if (sim->params.max_bandwidth && sim->params.max_buffer_size == 0) { + sim->params.max_buffer_size = (int)sim->params.max_bandwidth; + ortp_message("Network simulation: Max buffer size not set for RTP session [%p], using [%i]", session, + sim->params.max_buffer_size); } - session->net_sim_ctx=sim; - if ((params->mode==OrtpNetworkSimulatorOutbound || params->mode==OrtpNetworkSimulatorOutboundControlled) && !sim->thread_started){ - sim->thread_started=TRUE; + session->net_sim_ctx = sim; + if ((params->mode == OrtpNetworkSimulatorOutbound || params->mode == OrtpNetworkSimulatorOutboundControlled) && + !sim->thread_started) { + sim->thread_started = TRUE; ortp_thread_create(&sim->thread, NULL, outboud_simulator_thread, session); } ortp_message("Network simulation: enabled with the following parameters:\n" - "\tlatency=%d\n" - "\tloss_rate=%.1f\n" - "\tconsecutive_loss_probability=%.1f\n" - "\tmax_bandwidth=%.1f\n" - "\tmax_buffer_size=%d\n" - "\tjitter_density=%.1f\n" - "\tjitter_strength=%.1f\n" - "\tmode=%s", - params->latency, - params->loss_rate, - params->consecutive_loss_probability, - params->max_bandwidth, - params->max_buffer_size, - params->jitter_burst_density, - params->jitter_strength, - ortp_network_simulator_mode_to_string(params->mode) - ); - }else{ - session->net_sim_ctx=NULL; + "\tlatency=%d\n" + "\tloss_rate=%.1f\n" + "\tconsecutive_loss_probability=%.1f\n" + "\tmax_bandwidth=%.1f\n" + "\tmax_buffer_size=%d\n" + "\tjitter_density=%.1f\n" + "\tjitter_strength=%.1f\n" + "\tmode=%s", + params->latency, params->loss_rate, params->consecutive_loss_probability, params->max_bandwidth, + params->max_buffer_size, params->jitter_burst_density, params->jitter_strength, + ortp_network_simulator_mode_to_string(params->mode)); + } else { + session->net_sim_ctx = NULL; ortp_message("rtp_session_enable_network_simulation:DISABLING NETWORK SIMULATION"); - if (sim!=NULL) ortp_network_simulator_destroy(sim); + if (sim != NULL) ortp_network_simulator_destroy(sim); } } -static int64_t elapsed_us(struct timeval *tv1, struct timeval *tv2){ - return ((tv2->tv_sec-tv1->tv_sec)*1000000LL)+((tv2->tv_usec-tv1->tv_usec)); +static int64_t elapsed_us(struct timeval *tv1, struct timeval *tv2) { + return ((tv2->tv_sec - tv1->tv_sec) * 1000000LL) + ((tv2->tv_usec - tv1->tv_usec)); } -static mblk_t * simulate_latency(RtpSession *session, mblk_t *input){ - OrtpNetworkSimulatorCtx *sim=session->net_sim_ctx; +static mblk_t *simulate_latency(RtpSession *session, mblk_t *input) { + OrtpNetworkSimulatorCtx *sim = session->net_sim_ctx; struct timeval current; - mblk_t *output=NULL; + mblk_t *output = NULL; uint32_t current_ts; - bctbx_gettimeofday(¤t,NULL); + bctbx_gettimeofday(¤t, NULL); /*since we must store expiration date in reserved2(32bits) only(reserved1 already used), we need to reduce time stamp to milliseconds only*/ - current_ts = 1000*current.tv_sec + current.tv_usec/1000; + current_ts = 1000 * current.tv_sec + current.tv_usec / 1000; /*queue the packet - store expiration timestamps in reserved fields*/ - if (input){ + if (input) { input->reserved2 = current_ts + sim->params.latency; - putq(&sim->latency_q,input); + putq(&sim->latency_q, input); } - if ((output=peekq(&sim->latency_q))!=NULL){ - if (TIME_IS_NEWER_THAN(current_ts, output->reserved2)){ - output->reserved2=0; + if ((output = peekq(&sim->latency_q)) != NULL) { + if (TIME_IS_NEWER_THAN(current_ts, output->reserved2)) { + output->reserved2 = 0; getq(&sim->latency_q); /*return the first dequeued packet*/ return output; @@ -228,117 +228,120 @@ static mblk_t * simulate_latency(RtpSession *session, mblk_t *input){ return NULL; } -static int simulate_jitter_by_bit_budget_reduction(OrtpNetworkSimulatorCtx *sim, int budget_increase){ - unsigned int r=bctbx_random()%1000; - float threshold,score; - int budget_adjust=0; - uint64_t now=bctbx_get_cur_time_ms(); +static int simulate_jitter_by_bit_budget_reduction(OrtpNetworkSimulatorCtx *sim, int budget_increase) { + unsigned int r = bctbx_random() % 1000; + float threshold, score; + int budget_adjust = 0; + uint64_t now = bctbx_get_cur_time_ms(); - if (sim->last_jitter_event==0){ - sim->last_jitter_event=bctbx_get_cur_time_ms(); + if (sim->last_jitter_event == 0) { + sim->last_jitter_event = bctbx_get_cur_time_ms(); } - if (sim->in_jitter_event){ - threshold=100; - score=(float)r; - }else{ - score=1000.0f*(float)r*(now-sim->last_jitter_event)*sim->params.jitter_burst_density*1e-6f; - threshold=500; + if (sim->in_jitter_event) { + threshold = 100; + score = (float)r; + } else { + score = 1000.0f * (float)r * (now - sim->last_jitter_event) * sim->params.jitter_burst_density * 1e-6f; + threshold = 500; } - if (score>(int)threshold){ - int64_t strength_rand=(int64_t)(sim->params.jitter_strength * (float)(bctbx_random()%1000)); - sim->in_jitter_event=TRUE; - budget_adjust=(int)-((int64_t)budget_increase*strength_rand/1000LL); - /*ortp_message("jitter in progress... bit_budget_adjustement=%i, bit_budget=%i",budget_adjust,sim->bit_budget);*/ - }else if (sim->in_jitter_event){ + if (score > (int)threshold) { + int64_t strength_rand = (int64_t)(sim->params.jitter_strength * (float)(bctbx_random() % 1000)); + sim->in_jitter_event = TRUE; + budget_adjust = (int)-((int64_t)budget_increase * strength_rand / 1000LL); + /*ortp_message("jitter in progress... bit_budget_adjustement=%i, + * bit_budget=%i",budget_adjust,sim->bit_budget);*/ + } else if (sim->in_jitter_event) { /*ortp_message("jitter ended.");*/ - sim->in_jitter_event=FALSE; - sim->last_jitter_event=bctbx_get_cur_time_ms(); + sim->in_jitter_event = FALSE; + sim->last_jitter_event = bctbx_get_cur_time_ms(); } return budget_adjust; } -static mblk_t *simulate_bandwidth_limit_and_jitter(RtpSession *session, mblk_t *input){ - OrtpNetworkSimulatorCtx *sim=session->net_sim_ctx; +static mblk_t *simulate_bandwidth_limit_and_jitter(RtpSession *session, mblk_t *input) { + OrtpNetworkSimulatorCtx *sim = session->net_sim_ctx; struct timeval current; int64_t elapsed; int bits; int budget_increase; - mblk_t *output=NULL; - int overhead=(session->rtp.gs.sockfamily==AF_INET6) ? IP6_UDP_OVERHEAD : IP_UDP_OVERHEAD; + mblk_t *output = NULL; + int overhead = (session->rtp.gs.sockfamily == AF_INET6) ? IP6_UDP_OVERHEAD : IP_UDP_OVERHEAD; - bctbx_gettimeofday(¤t,NULL); + bctbx_gettimeofday(¤t, NULL); - if (sim->last_check.tv_sec==0){ - sim->last_check=current; - sim->bit_budget=0; + if (sim->last_check.tv_sec == 0) { + sim->last_check = current; + sim->bit_budget = 0; } /*update the budget */ - elapsed=elapsed_us(&sim->last_check,¤t); - budget_increase=(int)((elapsed*(int64_t)sim->params.max_bandwidth)/1000000LL); - sim->bit_budget+=budget_increase; - sim->bit_budget+=simulate_jitter_by_bit_budget_reduction(sim,budget_increase); - sim->last_check=current; + elapsed = elapsed_us(&sim->last_check, ¤t); + budget_increase = (int)((elapsed * (int64_t)sim->params.max_bandwidth) / 1000000LL); + sim->bit_budget += budget_increase; + sim->bit_budget += simulate_jitter_by_bit_budget_reduction(sim, budget_increase); + sim->last_check = current; /* queue the packet for sending*/ - if (input){ - putq(&sim->q,input); - bits=((int)msgdsize(input)+overhead)*8; - sim->qsize+=bits; + if (input) { + putq(&sim->q, input); + bits = ((int)msgdsize(input) + overhead) * 8; + sim->qsize += bits; } /*flow control*/ - while (sim->qsize>=sim->params.max_buffer_size){ + while (sim->qsize >= sim->params.max_buffer_size) { // ortp_message("rtp_session_network_simulate(): discarding packets."); - output=getq(&sim->q); - if (output){ - bits=((int)msgdsize(output)+overhead)*8; - sim->qsize-=bits; + output = getq(&sim->q); + if (output) { + bits = ((int)msgdsize(output) + overhead) * 8; + sim->qsize -= bits; sim->drop_by_congestion++; freemsg(output); } } - output=NULL; + output = NULL; /*see if we can output a packet*/ - if (sim->bit_budget>=0){ - output=getq(&sim->q); - if (output){ - bits=((int)msgdsize(output)+overhead)*8; - sim->bit_budget-=bits; - sim->qsize-=bits; + if (sim->bit_budget >= 0) { + output = getq(&sim->q); + if (output) { + bits = ((int)msgdsize(output) + overhead) * 8; + sim->bit_budget -= bits; + sim->qsize -= bits; } } - if (output==NULL && input==NULL && sim->bit_budget>=0){ + if (output == NULL && input == NULL && sim->bit_budget >= 0) { /* unused budget is lost...*/ - sim->last_check.tv_sec=0; + sim->last_check.tv_sec = 0; } return output; } -static mblk_t *simulate_loss_rate(OrtpNetworkSimulatorCtx *net_sim_ctx, mblk_t *input){ +static mblk_t *simulate_loss_rate(OrtpNetworkSimulatorCtx *net_sim_ctx, mblk_t *input) { int rrate; - float loss_rate=net_sim_ctx->params.loss_rate*10.0f; + float loss_rate = net_sim_ctx->params.loss_rate * 10.0f; /*in order to simulate bursts of dropped packets, take into account a different probability after a loss occurred*/ - if (net_sim_ctx->consecutive_drops>0){ - loss_rate=net_sim_ctx->params.consecutive_loss_probability*1000.0f; + if (net_sim_ctx->consecutive_drops > 0) { + loss_rate = net_sim_ctx->params.consecutive_loss_probability * 1000.0f; } rrate = bctbx_random() % 1000; if (rrate >= loss_rate) { - if (net_sim_ctx->consecutive_drops){ + if (net_sim_ctx->consecutive_drops) { /*after a burst of lost packets*/ - net_sim_ctx->drops_to_ignore=net_sim_ctx->consecutive_drops - (int)(((float)net_sim_ctx->consecutive_drops*net_sim_ctx->params.loss_rate)/100.0f); - net_sim_ctx->consecutive_drops=0; + net_sim_ctx->drops_to_ignore = + net_sim_ctx->consecutive_drops - + (int)(((float)net_sim_ctx->consecutive_drops * net_sim_ctx->params.loss_rate) / 100.0f); + net_sim_ctx->consecutive_drops = 0; } return input; } - if (net_sim_ctx->drops_to_ignore>0){ + if (net_sim_ctx->drops_to_ignore > 0) { net_sim_ctx->drops_to_ignore--; return input; } - if (net_sim_ctx->params.consecutive_loss_probability>0){ + if (net_sim_ctx->params.consecutive_loss_probability > 0) { net_sim_ctx->consecutive_drops++; } net_sim_ctx->drop_by_loss++; @@ -346,20 +349,20 @@ static mblk_t *simulate_loss_rate(OrtpNetworkSimulatorCtx *net_sim_ctx, mblk_t * return NULL; } -mblk_t * rtp_session_network_simulate(RtpSession *session, mblk_t *input, bool_t *is_rtp_packet){ - OrtpNetworkSimulatorCtx *sim=session->net_sim_ctx; - mblk_t *om=NULL; +mblk_t *rtp_session_network_simulate(RtpSession *session, mblk_t *input, bool_t *is_rtp_packet) { + OrtpNetworkSimulatorCtx *sim = session->net_sim_ctx; + mblk_t *om = NULL; - om=input; + om = input; /*while packet is stored in network simulator queue, keep its type in reserved1 space*/ - if (om != NULL){ + if (om != NULL) { sim->total_count++; om->reserved1 = *is_rtp_packet; } - if (sim->params.latency>0){ - om=simulate_latency(session,om); + if (sim->params.latency > 0) { + om = simulate_latency(session, om); } if ((sim->params.loss_rate > 0) && (om != NULL)) { @@ -372,13 +375,13 @@ mblk_t * rtp_session_network_simulate(RtpSession *session, mblk_t *input, bool_t } } - if (sim->params.max_bandwidth>0){ - om=simulate_bandwidth_limit_and_jitter(session,om); + if (sim->params.max_bandwidth > 0) { + om = simulate_bandwidth_limit_and_jitter(session, om); } /*finally when releasing the packet from the simulator, reset the reserved1 space to default, since it will be used by mediastreamer later*/ - if (om != NULL){ + if (om != NULL) { *is_rtp_packet = om->reserved1; om->reserved1 = 0; } @@ -387,35 +390,35 @@ mblk_t * rtp_session_network_simulate(RtpSession *session, mblk_t *input, bool_t /*compares two ortpTimeSpec s1 and s2. * returns a negative value if s1 is earlier than s2, 0 if they are equal, a positive value if s1 is later than s2*/ -int ortp_timespec_compare(const ortpTimeSpec *s1, const ortpTimeSpec *s2){ +int ortp_timespec_compare(const ortpTimeSpec *s1, const ortpTimeSpec *s2) { int64_t secdiff = s1->tv_sec - s2->tv_sec; - if (secdiff == 0){ + if (secdiff == 0) { int64_t nsec_diff = s1->tv_nsec - s2->tv_nsec; - if (nsec_diff < 0){ + if (nsec_diff < 0) { return -1; - }else if (nsec_diff > 0){ + } else if (nsec_diff > 0) { return 1; - }else return 0; - }else if (secdiff < 0){ + } else return 0; + } else if (secdiff < 0) { return -1; - }else - return 1; + } else return 1; } -static mblk_t * rtp_session_netsim_find_next_packet_to_send(RtpSession *session){ +static mblk_t *rtp_session_netsim_find_next_packet_to_send(RtpSession *session) { mblk_t *om; - ortpTimeSpec min_packet_time = { 0, 0}; + ortpTimeSpec min_packet_time = {0, 0}; ortpTimeSpec packet_time; mblk_t *next_packet = NULL; - for(om = qbegin(&session->net_sim_ctx->send_q); !qend(&session->net_sim_ctx->send_q, om); om = qnext(&session->net_sim_ctx->send_q, om)){ - packet_time.tv_sec=om->timestamp.tv_sec; - packet_time.tv_nsec=om->timestamp.tv_usec*1000LL; - if (packet_time.tv_sec == 0 && packet_time.tv_nsec == 0){ + for (om = qbegin(&session->net_sim_ctx->send_q); !qend(&session->net_sim_ctx->send_q, om); + om = qnext(&session->net_sim_ctx->send_q, om)) { + packet_time.tv_sec = om->timestamp.tv_sec; + packet_time.tv_nsec = om->timestamp.tv_usec * 1000LL; + if (packet_time.tv_sec == 0 && packet_time.tv_nsec == 0) { /*this is a packet to drop*/ return om; } - if (min_packet_time.tv_sec == 0 || ortp_timespec_compare(&packet_time, &min_packet_time) < 0){ + if (min_packet_time.tv_sec == 0 || ortp_timespec_compare(&packet_time, &min_packet_time) < 0) { min_packet_time = packet_time; next_packet = om; } @@ -423,68 +426,70 @@ static mblk_t * rtp_session_netsim_find_next_packet_to_send(RtpSession *session) return next_packet; } -static void rtp_session_schedule_outbound_network_simulator(RtpSession *session, ortpTimeSpec *sleep_until){ +static void rtp_session_schedule_outbound_network_simulator(RtpSession *session, ortpTimeSpec *sleep_until) { mblk_t *om; - int count=0; + int count = 0; bool_t is_rtp_packet; - if (!session->net_sim_ctx) - return; + if (!session->net_sim_ctx) return; - if (!session->net_sim_ctx->params.enabled) - return; + if (!session->net_sim_ctx->params.enabled) return; - if (session->net_sim_ctx->params.mode==OrtpNetworkSimulatorOutbound){ - sleep_until->tv_sec=0; - sleep_until->tv_nsec=0; + if (session->net_sim_ctx->params.mode == OrtpNetworkSimulatorOutbound) { + sleep_until->tv_sec = 0; + sleep_until->tv_nsec = 0; ortp_mutex_lock(&session->net_sim_ctx->mutex); - while((om=getq(&session->net_sim_ctx->send_q))!=NULL){ + while ((om = getq(&session->net_sim_ctx->send_q)) != NULL) { count++; ortp_mutex_unlock(&session->net_sim_ctx->mutex); - is_rtp_packet=om->reserved1; /*it was set by rtp_session_sendto()*/ - om=rtp_session_network_simulate(session,om, &is_rtp_packet); - if (om){ - _ortp_sendto(rtp_session_get_socket(session, is_rtp_packet), om, 0, (struct sockaddr*)&om->net_addr, om->net_addrlen); + is_rtp_packet = om->reserved1; /*it was set by rtp_session_sendto()*/ + om = rtp_session_network_simulate(session, om, &is_rtp_packet); + if (om) { + _ortp_sendto(rtp_session_get_socket(session, is_rtp_packet), om, 0, (struct sockaddr *)&om->net_addr, + om->net_addrlen); freemsg(om); } ortp_mutex_lock(&session->net_sim_ctx->mutex); } ortp_mutex_unlock(&session->net_sim_ctx->mutex); - if (count==0){ + if (count == 0) { /*even if no packets were queued, we have to schedule the simulator*/ - is_rtp_packet=TRUE; - om=rtp_session_network_simulate(session,NULL, &is_rtp_packet); - if (om){ - _ortp_sendto(rtp_session_get_socket(session, is_rtp_packet), om, 0, (struct sockaddr*)&om->net_addr, om->net_addrlen); + is_rtp_packet = TRUE; + om = rtp_session_network_simulate(session, NULL, &is_rtp_packet); + if (om) { + _ortp_sendto(rtp_session_get_socket(session, is_rtp_packet), om, 0, (struct sockaddr *)&om->net_addr, + om->net_addrlen); freemsg(om); } } - }else if (session->net_sim_ctx->params.mode==OrtpNetworkSimulatorOutboundControlled){ - ortpTimeSpec current={0}; + } else if (session->net_sim_ctx->params.mode == OrtpNetworkSimulatorOutboundControlled) { + ortpTimeSpec current = {0}; ortpTimeSpec packet_time; - mblk_t *todrop=NULL; + mblk_t *todrop = NULL; ortp_mutex_lock(&session->net_sim_ctx->mutex); - while((om = rtp_session_netsim_find_next_packet_to_send(session)) != NULL){ - is_rtp_packet=om->reserved1; /*it was set by rtp_session_sendto()*/ + while ((om = rtp_session_netsim_find_next_packet_to_send(session)) != NULL) { + is_rtp_packet = om->reserved1; /*it was set by rtp_session_sendto()*/ ortp_mutex_unlock(&session->net_sim_ctx->mutex); if (todrop) { freemsg(todrop); /*free the last message while the mutex is not held*/ todrop = NULL; } - _ortp_get_cur_time(¤t,TRUE); - packet_time.tv_sec=om->timestamp.tv_sec; - packet_time.tv_nsec=om->timestamp.tv_usec*1000LL; - if (is_rtp_packet && om->timestamp.tv_sec==0 && om->timestamp.tv_usec==0){ - todrop = om; /*simulate a packet loss, only RTP packets can be dropped. Timestamp is not set for RTCP packets*/ - }else if (ortp_timespec_compare(&packet_time, ¤t) <= 0){ + _ortp_get_cur_time(¤t, TRUE); + packet_time.tv_sec = om->timestamp.tv_sec; + packet_time.tv_nsec = om->timestamp.tv_usec * 1000LL; + if (is_rtp_packet && om->timestamp.tv_sec == 0 && om->timestamp.tv_usec == 0) { + todrop = om; /*simulate a packet loss, only RTP packets can be dropped. Timestamp is not set for RTCP + packets*/ + } else if (ortp_timespec_compare(&packet_time, ¤t) <= 0) { /*it is time to send this packet*/ - _ortp_sendto(is_rtp_packet ? session->rtp.gs.socket : session->rtcp.gs.socket, om, 0, (struct sockaddr*)&om->net_addr, om->net_addrlen); + _ortp_sendto(is_rtp_packet ? session->rtp.gs.socket : session->rtcp.gs.socket, om, 0, + (struct sockaddr *)&om->net_addr, om->net_addrlen); todrop = om; - }else { + } else { /*no packet is to be sent yet; set the time at which we want to be called*/ - *sleep_until=packet_time; + *sleep_until = packet_time; ortp_mutex_lock(&session->net_sim_ctx->mutex); break; } @@ -493,11 +498,11 @@ static void rtp_session_schedule_outbound_network_simulator(RtpSession *session, } ortp_mutex_unlock(&session->net_sim_ctx->mutex); if (todrop) freemsg(todrop); - if (sleep_until->tv_sec==0){ - _ortp_get_cur_time(¤t,TRUE); + if (sleep_until->tv_sec == 0) { + _ortp_get_cur_time(¤t, TRUE); /*no pending packet in the queue yet, schedule a wake up not too far*/ - sleep_until->tv_sec=current.tv_sec; - sleep_until->tv_nsec=current.tv_nsec+1000000LL; /*in 1 ms*/ + sleep_until->tv_sec = current.tv_sec; + sleep_until->tv_nsec = current.tv_nsec + 1000000LL; /*in 1 ms*/ } } } diff --git a/src/ortp.c b/src/ortp.c index aea5be91..60a6bac1 100644 --- a/src/ortp.c +++ b/src/ortp.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,61 +18,55 @@ * along with this program. If not, see . */ - #ifdef HAVE_CONFIG_H #include "ortp-config.h" #endif #include "ortp/ortp.h" +#include "scheduler.h" #include "utils.h" #include -#include "scheduler.h" rtp_stats_t ortp_global_stats; #ifdef ENABLE_MEMCHECK -int ortp_allocations=0; +int ortp_allocations = 0; #endif RtpScheduler *__ortp_scheduler; - - extern void av_profile_init(RtpProfile *profile); -static void init_random_number_generator(void){ +static void init_random_number_generator(void) { #ifndef _WIN32 struct timeval t; - bctbx_gettimeofday(&t,NULL); - srandom(t.tv_usec+t.tv_sec); + bctbx_gettimeofday(&t, NULL); + srandom(t.tv_usec + t.tv_sec); #endif /*on windows we're using rand_s, which doesn't require initialization*/ } - #ifdef _WIN32 -static bool_t win32_init_sockets(void){ +static bool_t win32_init_sockets(void) { WORD wVersionRequested; WSADATA wsaData; int i; - wVersionRequested = MAKEWORD(2,0); - if( (i = WSAStartup(wVersionRequested, &wsaData))!=0) - { - ortp_error("Unable to initialize windows socket api, reason: %d (%s)",i,getWinSocketError(i)); + wVersionRequested = MAKEWORD(2, 0); + if ((i = WSAStartup(wVersionRequested, &wsaData)) != 0) { + ortp_error("Unable to initialize windows socket api, reason: %d (%s)", i, getWinSocketError(i)); return FALSE; } return TRUE; } #endif -static int ortp_initialized=0; +static int ortp_initialized = 0; /** * Initialize the oRTP library. You should call this function first before using * oRTP API. -**/ -void ortp_init() -{ + **/ +void ortp_init() { if (ortp_initialized++) return; #ifdef _WIN32 @@ -89,114 +83,108 @@ void ortp_init() #endif } - /** * Initialize the oRTP scheduler. You only have to do that if you intend to use the * scheduled mode of the RtpSession in your application. * -**/ -void ortp_scheduler_init() -{ - static bool_t initialized=FALSE; + **/ +void ortp_scheduler_init() { + static bool_t initialized = FALSE; if (initialized) return; - initialized=TRUE; + initialized = TRUE; #ifdef __hpux /* on hpux, we must block sigalrm on the main process, because signal delivery is ?random?, well, sometimes the SIGALRM goes to both the main thread and the scheduler thread */ sigset_t set; sigemptyset(&set); - sigaddset(&set,SIGALRM); - sigprocmask(SIG_BLOCK,&set,NULL); + sigaddset(&set, SIGALRM); + sigprocmask(SIG_BLOCK, &set, NULL); #endif /* __hpux */ - __ortp_scheduler=rtp_scheduler_new(); + __ortp_scheduler = rtp_scheduler_new(); rtp_scheduler_start(__ortp_scheduler); } - /** * Gracefully uninitialize the library, including shutdowning the scheduler if it was started. * -**/ -void ortp_exit() -{ - if (ortp_initialized==0) { + **/ +void ortp_exit() { + if (ortp_initialized == 0) { ortp_warning("ortp_exit() called without prior call to ortp_init(), ignored."); return; } ortp_initialized--; - if (ortp_initialized==0){ - if (__ortp_scheduler!=NULL) - { + if (ortp_initialized == 0) { + if (__ortp_scheduler != NULL) { rtp_scheduler_destroy(__ortp_scheduler); - __ortp_scheduler=NULL; + __ortp_scheduler = NULL; } } } -RtpScheduler * ortp_get_scheduler() -{ - if (__ortp_scheduler==NULL) ortp_error("Cannot use the scheduled mode: the scheduler is not " - "started. Call ortp_scheduler_init() at the begginning of the application."); +RtpScheduler *ortp_get_scheduler() { + if (__ortp_scheduler == NULL) + ortp_error("Cannot use the scheduled mode: the scheduler is not " + "started. Call ortp_scheduler_init() at the begginning of the application."); return __ortp_scheduler; } - /** * Display global statistics (cumulative for all RtpSession) -**/ -void ortp_global_stats_display() -{ - rtp_stats_display(&ortp_global_stats,"Global statistics"); + **/ +void ortp_global_stats_display() { + rtp_stats_display(&ortp_global_stats, "Global statistics"); #ifdef ENABLE_MEMCHECK - printf("Unfreed allocations: %i\n",ortp_allocations); + printf("Unfreed allocations: %i\n", ortp_allocations); #endif } /** * Print RTP statistics. -**/ + **/ void rtp_stats_display(const rtp_stats_t *stats, const char *header) { ortp_log(ORTP_MESSAGE, "==========================================================="); ortp_log(ORTP_MESSAGE, "%s", header); ortp_log(ORTP_MESSAGE, "-----------------------------------------------------------"); - ortp_log(ORTP_MESSAGE, "sent %10"PRId64" packets", stats->packet_sent); - ortp_log(ORTP_MESSAGE, " %10"PRId64" duplicated packets", stats->packet_dup_sent); - ortp_log(ORTP_MESSAGE, " %10"PRId64" bytes ", stats->sent); - ortp_log(ORTP_MESSAGE, "received %10"PRId64" packets", stats->packet_recv); - ortp_log(ORTP_MESSAGE, " %10"PRId64" duplicated packets", stats->packet_dup_recv); - ortp_log(ORTP_MESSAGE, " %10"PRId64" bytes ", stats->hw_recv); - ortp_log(ORTP_MESSAGE, "incoming delivered to the app %10"PRId64" bytes ", stats->recv); - ortp_log(ORTP_MESSAGE, "incoming cumulative lost %10"PRId64" packets", stats->cum_packet_loss); - ortp_log(ORTP_MESSAGE, "incoming received too late %10"PRId64" packets", stats->outoftime); - ortp_log(ORTP_MESSAGE, "incoming bad formatted %10"PRId64" packets", stats->bad); - ortp_log(ORTP_MESSAGE, "incoming discarded (queue overflow) %10"PRId64" packets", stats->discarded); - ortp_log(ORTP_MESSAGE, "sent rtcp %10"PRId64" packets", stats->sent_rtcp_packets); - ortp_log(ORTP_MESSAGE, "received rtcp %10"PRId64" packets", stats->recv_rtcp_packets); + ortp_log(ORTP_MESSAGE, "sent %10" PRId64 " packets", stats->packet_sent); + ortp_log(ORTP_MESSAGE, " %10" PRId64 " duplicated packets", + stats->packet_dup_sent); + ortp_log(ORTP_MESSAGE, " %10" PRId64 " bytes ", stats->sent); + ortp_log(ORTP_MESSAGE, "received %10" PRId64 " packets", stats->packet_recv); + ortp_log(ORTP_MESSAGE, " %10" PRId64 " duplicated packets", + stats->packet_dup_recv); + ortp_log(ORTP_MESSAGE, " %10" PRId64 " bytes ", stats->hw_recv); + ortp_log(ORTP_MESSAGE, "incoming delivered to the app %10" PRId64 " bytes ", stats->recv); + ortp_log(ORTP_MESSAGE, "incoming cumulative lost %10" PRId64 " packets", stats->cum_packet_loss); + ortp_log(ORTP_MESSAGE, "incoming received too late %10" PRId64 " packets", stats->outoftime); + ortp_log(ORTP_MESSAGE, "incoming bad formatted %10" PRId64 " packets", stats->bad); + ortp_log(ORTP_MESSAGE, "incoming discarded (queue overflow) %10" PRId64 " packets", stats->discarded); + ortp_log(ORTP_MESSAGE, "sent rtcp %10" PRId64 " packets", stats->sent_rtcp_packets); + ortp_log(ORTP_MESSAGE, "received rtcp %10" PRId64 " packets", stats->recv_rtcp_packets); ortp_log(ORTP_MESSAGE, "==========================================================="); } -void ortp_global_stats_reset(){ - memset(&ortp_global_stats,0,sizeof(rtp_stats_t)); +void ortp_global_stats_reset() { + memset(&ortp_global_stats, 0, sizeof(rtp_stats_t)); } -rtp_stats_t *ortp_get_global_stats(){ +rtp_stats_t *ortp_get_global_stats() { return &ortp_global_stats; } -void rtp_stats_reset(rtp_stats_t *stats){ - memset((void*)stats,0,sizeof(rtp_stats_t)); +void rtp_stats_reset(rtp_stats_t *stats) { + memset((void *)stats, 0, sizeof(rtp_stats_t)); } - /** * This function give the opportunity to programs to check if the libortp they link to * has the minimum version number they need. * * Returns: true if ortp has a version number greater or equal than the required one. -**/ -bool_t ortp_min_version_required(int major, int minor, int micro){ - return ((major*1000000) + (minor*1000) + micro) <= - ((ORTP_MAJOR_VERSION*1000000) + (ORTP_MINOR_VERSION*1000) + ORTP_MICRO_VERSION); + **/ +bool_t ortp_min_version_required(int major, int minor, int micro) { + return ((major * 1000000) + (minor * 1000) + micro) <= + ((ORTP_MAJOR_VERSION * 1000000) + (ORTP_MINOR_VERSION * 1000) + ORTP_MICRO_VERSION); } diff --git a/src/payloadtype.c b/src/payloadtype.c index e84056db..0d2f5eef 100644 --- a/src/payloadtype.c +++ b/src/payloadtype.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -27,45 +27,38 @@ #include "ortp/str_utils.h" #include - -char *payload_type_get_rtpmap(PayloadType *pt) -{ - int len=(int)strlen(pt->mime_type)+15; - char *rtpmap=(char *) ortp_malloc(len); - if (pt->channels>0) - snprintf(rtpmap,len,"%s/%i/%i",pt->mime_type,pt->clock_rate,pt->channels); - else - snprintf(rtpmap,len,"%s/%i",pt->mime_type,pt->clock_rate); +char *payload_type_get_rtpmap(PayloadType *pt) { + int len = (int)strlen(pt->mime_type) + 15; + char *rtpmap = (char *)ortp_malloc(len); + if (pt->channels > 0) snprintf(rtpmap, len, "%s/%i/%i", pt->mime_type, pt->clock_rate, pt->channels); + else snprintf(rtpmap, len, "%s/%i", pt->mime_type, pt->clock_rate); return rtpmap; } -PayloadType *payload_type_new() -{ - PayloadType *newpayload=(PayloadType *)ortp_new0(PayloadType,1); - newpayload->flags|=PAYLOAD_TYPE_ALLOCATED; +PayloadType *payload_type_new() { + PayloadType *newpayload = (PayloadType *)ortp_new0(PayloadType, 1); + newpayload->flags |= PAYLOAD_TYPE_ALLOCATED; return newpayload; } - -PayloadType *payload_type_clone(const PayloadType *payload) -{ - PayloadType *newpayload=(PayloadType *)ortp_new0(PayloadType,1); - memcpy(newpayload,payload,sizeof(PayloadType)); - newpayload->mime_type=ortp_strdup(payload->mime_type); - if (payload->recv_fmtp!=NULL) { - newpayload->recv_fmtp=ortp_strdup(payload->recv_fmtp); +PayloadType *payload_type_clone(const PayloadType *payload) { + PayloadType *newpayload = (PayloadType *)ortp_new0(PayloadType, 1); + memcpy(newpayload, payload, sizeof(PayloadType)); + newpayload->mime_type = ortp_strdup(payload->mime_type); + if (payload->recv_fmtp != NULL) { + newpayload->recv_fmtp = ortp_strdup(payload->recv_fmtp); } - if (payload->send_fmtp!=NULL){ - newpayload->send_fmtp=ortp_strdup(payload->send_fmtp); + if (payload->send_fmtp != NULL) { + newpayload->send_fmtp = ortp_strdup(payload->send_fmtp); } - newpayload->flags|=PAYLOAD_TYPE_ALLOCATED; + newpayload->flags |= PAYLOAD_TYPE_ALLOCATED; return newpayload; } -static bool_t canWrite(PayloadType *pt){ +static bool_t canWrite(PayloadType *pt) { if (!(pt->flags & PAYLOAD_TYPE_ALLOCATED)) { ortp_error("Cannot change parameters of statically defined payload types: make your" - " own copy using payload_type_clone() first."); + " own copy using payload_type_clone() first."); return FALSE; } return TRUE; @@ -75,12 +68,12 @@ static bool_t canWrite(PayloadType *pt){ * Sets a recv parameters (fmtp) for the PayloadType. * This method is provided for applications using RTP with SDP, but * actually the ftmp information is not used for RTP processing. -**/ -void payload_type_set_recv_fmtp(PayloadType *pt, const char *fmtp){ - if (canWrite(pt)){ - if (pt->recv_fmtp!=NULL) ortp_free(pt->recv_fmtp); - if (fmtp!=NULL) pt->recv_fmtp=ortp_strdup(fmtp); - else pt->recv_fmtp=NULL; + **/ +void payload_type_set_recv_fmtp(PayloadType *pt, const char *fmtp) { + if (canWrite(pt)) { + if (pt->recv_fmtp != NULL) ortp_free(pt->recv_fmtp); + if (fmtp != NULL) pt->recv_fmtp = ortp_strdup(fmtp); + else pt->recv_fmtp = NULL; } } @@ -88,37 +81,33 @@ void payload_type_set_recv_fmtp(PayloadType *pt, const char *fmtp){ * Sets a send parameters (fmtp) for the PayloadType. * This method is provided for applications using RTP with SDP, but * actually the ftmp information is not used for RTP processing. -**/ -void payload_type_set_send_fmtp(PayloadType *pt, const char *fmtp){ - if (canWrite(pt)){ - if (pt->send_fmtp!=NULL) ortp_free(pt->send_fmtp); - if (fmtp!=NULL) pt->send_fmtp=ortp_strdup(fmtp); - else pt->send_fmtp=NULL; + **/ +void payload_type_set_send_fmtp(PayloadType *pt, const char *fmtp) { + if (canWrite(pt)) { + if (pt->send_fmtp != NULL) ortp_free(pt->send_fmtp); + if (fmtp != NULL) pt->send_fmtp = ortp_strdup(fmtp); + else pt->send_fmtp = NULL; } } - - -void payload_type_append_recv_fmtp(PayloadType *pt, const char *fmtp){ - if (canWrite(pt)){ - if (pt->recv_fmtp==NULL) - pt->recv_fmtp=ortp_strdup(fmtp); - else{ - char *tmp=ortp_strdup_printf("%s;%s",pt->recv_fmtp,fmtp); +void payload_type_append_recv_fmtp(PayloadType *pt, const char *fmtp) { + if (canWrite(pt)) { + if (pt->recv_fmtp == NULL) pt->recv_fmtp = ortp_strdup(fmtp); + else { + char *tmp = ortp_strdup_printf("%s;%s", pt->recv_fmtp, fmtp); ortp_free(pt->recv_fmtp); - pt->recv_fmtp=tmp; + pt->recv_fmtp = tmp; } } } -void payload_type_append_send_fmtp(PayloadType *pt, const char *fmtp){ - if (canWrite(pt)){ - if (pt->send_fmtp==NULL) - pt->send_fmtp=ortp_strdup(fmtp); - else{ - char *tmp=ortp_strdup_printf("%s;%s",pt->send_fmtp,fmtp); +void payload_type_append_send_fmtp(PayloadType *pt, const char *fmtp) { + if (canWrite(pt)) { + if (pt->send_fmtp == NULL) pt->send_fmtp = ortp_strdup(fmtp); + else { + char *tmp = ortp_strdup_printf("%s;%s", pt->send_fmtp, fmtp); ortp_free(pt->send_fmtp); - pt->send_fmtp=tmp; + pt->send_fmtp = tmp; } } } @@ -134,52 +123,49 @@ bool_t payload_type_is_vbr(const PayloadType *pt) { return !!(pt->flags & PAYLOAD_TYPE_IS_VBR); } - /** * Frees a PayloadType. -**/ -void payload_type_destroy(PayloadType *pt) -{ + **/ +void payload_type_destroy(PayloadType *pt) { if (pt->mime_type) ortp_free(pt->mime_type); if (pt->recv_fmtp) ortp_free(pt->recv_fmtp); if (pt->send_fmtp) ortp_free(pt->send_fmtp); ortp_free(pt); } - -static const char *find_param_occurence_of(const char *fmtp, const char *param){ - const char *pos=fmtp; +static const char *find_param_occurence_of(const char *fmtp, const char *param) { + const char *pos = fmtp; int param_len = (int)strlen(param); - do{ - pos=strstr(pos,param); - if (pos){ + do { + pos = strstr(pos, param); + if (pos) { /*check that the occurence found is not a subword of a parameter name*/ - if (pos==fmtp){ + if (pos == fmtp) { if (pos[param_len] == '=') break; /* found it */ - }else if ((pos[-1]==';' || pos[-1]==' ') && pos[param_len] == '='){ + } else if ((pos[-1] == ';' || pos[-1] == ' ') && pos[param_len] == '=') { break; /* found it */ } - pos+=strlen(param); + pos += strlen(param); } - }while (pos!=NULL); + } while (pos != NULL); return pos; } -static const char *find_last_param_occurence_of(const char *fmtp, const char *param){ - const char *pos=fmtp; - const char *lastpos=NULL; - do{ - pos=find_param_occurence_of(pos,param); +static const char *find_last_param_occurence_of(const char *fmtp, const char *param) { + const char *pos = fmtp; + const char *lastpos = NULL; + do { + pos = find_param_occurence_of(pos, param); if (pos) { - lastpos=pos; - pos+=strlen(param); + lastpos = pos; + pos += strlen(param); } - }while(pos!=NULL); + } while (pos != NULL); return lastpos; } /** * Parses a fmtp string such as "profile=0;level=10", finds the value matching - * parameter param_name, and writes it into result. + * parameter param_name, and writes it into result. * If a parameter name is found multiple times, only the value of the last occurence is returned. * Despite fmtp strings are not used anywhere within oRTP, this function can * be useful for people using RTP streams described from SDP. @@ -188,19 +174,19 @@ static const char *find_last_param_occurence_of(const char *fmtp, const char *pa * @param result the value given for the parameter (if found) * @param result_len the size allocated to hold the result string * @return TRUE if the parameter was found, else FALSE. -**/ -bool_t fmtp_get_value(const char *fmtp, const char *param_name, char *result, size_t result_len){ - const char *pos=find_last_param_occurence_of(fmtp,param_name); + **/ +bool_t fmtp_get_value(const char *fmtp, const char *param_name, char *result, size_t result_len) { + const char *pos = find_last_param_occurence_of(fmtp, param_name); memset(result, '\0', result_len); - if (pos){ - const char *equal=strchr(pos,'='); - if (equal){ + if (pos) { + const char *equal = strchr(pos, '='); + if (equal) { int copied; - const char *end=strchr(equal+1,';'); - if (end==NULL) end=fmtp+strlen(fmtp); /*assuming this is the last param */ - copied=MIN((int)(result_len-1),(int)(end-(equal+1))); - strncpy(result,equal+1,copied); - result[copied]='\0'; + const char *end = strchr(equal + 1, ';'); + if (end == NULL) end = fmtp + strlen(fmtp); /*assuming this is the last param */ + copied = MIN((int)(result_len - 1), (int)(end - (equal + 1))); + strncpy(result, equal + 1, copied); + result[copied] = '\0'; return TRUE; } } diff --git a/src/port.c b/src/port.c index 6d4d4d83..91a768cc 100644 --- a/src/port.c +++ b/src/port.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,7 +18,6 @@ * along with this program. If not, see . */ - #ifdef HAVE_CONFIG_H #include "ortp-config.h" #endif @@ -26,10 +25,10 @@ #include "ortp/port.h" #include "ortp/str_utils.h" #include "utils.h" -#include #include +#include -#if defined(_WIN32) && !defined(_WIN32_WCE) +#if defined(_WIN32) && !defined(_WIN32_WCE) #include #endif @@ -37,66 +36,61 @@ #include #endif -static void *ortp_libc_malloc(size_t sz){ +static void *ortp_libc_malloc(size_t sz) { return malloc(sz); } #define ortp_libc_realloc bctbx_libc_realloc -static void *ortp_libc_realloc(void *ptr, size_t sz){ - return realloc(ptr,sz); +static void *ortp_libc_realloc(void *ptr, size_t sz) { + return realloc(ptr, sz); } -static void ortp_libc_free(void*ptr){ +static void ortp_libc_free(void *ptr) { free(ptr); } -static bool_t allocator_used=FALSE; +static bool_t allocator_used = FALSE; -static OrtpMemoryFunctions ortp_allocator={ - ortp_libc_malloc, - ortp_libc_realloc, - ortp_libc_free -}; +static OrtpMemoryFunctions ortp_allocator = {ortp_libc_malloc, ortp_libc_realloc, ortp_libc_free}; -void ortp_set_memory_functions(OrtpMemoryFunctions *functions){ - if (allocator_used){ +void ortp_set_memory_functions(OrtpMemoryFunctions *functions) { + if (allocator_used) { ortp_fatal("ortp_set_memory_functions() must be called before " - "first use of ortp_malloc or ortp_realloc"); + "first use of ortp_malloc or ortp_realloc"); return; } - ortp_allocator=*functions; + ortp_allocator = *functions; } -void* ortp_malloc(size_t sz){ - allocator_used=TRUE; +void *ortp_malloc(size_t sz) { + allocator_used = TRUE; return ortp_allocator.malloc_fun(sz); } -void* ortp_realloc(void *ptr, size_t sz){ - allocator_used=TRUE; - return ortp_allocator.realloc_fun(ptr,sz); +void *ortp_realloc(void *ptr, size_t sz) { + allocator_used = TRUE; + return ortp_allocator.realloc_fun(ptr, sz); } -void ortp_free(void* ptr){ +void ortp_free(void *ptr) { ortp_allocator.free_fun(ptr); } -void * ortp_malloc0(size_t size){ - void *ptr=ortp_malloc(size); - memset(ptr,0,size); +void *ortp_malloc0(size_t size) { + void *ptr = ortp_malloc(size); + memset(ptr, 0, size); return ptr; } -char * ortp_strdup(const char *tmp){ +char *ortp_strdup(const char *tmp) { size_t sz; char *ret; - if (tmp==NULL) - return NULL; - sz=strlen(tmp)+1; - ret=(char*)ortp_malloc(sz); - strcpy(ret,tmp); - ret[sz-1]='\0'; + if (tmp == NULL) return NULL; + sz = strlen(tmp) + 1; + ret = (char *)ortp_malloc(sz); + strcpy(ret, tmp); + ret[sz - 1] = '\0'; return ret; } @@ -105,12 +99,12 @@ char * ortp_strdup(const char *tmp){ * ioctlsocket on Win32. * int retrun the result of the system method */ -int set_non_blocking_socket (ortp_socket_t sock){ -#if !defined(_WIN32) && !defined(_WIN32_WCE) - return fcntl (sock, F_SETFL, fcntl(sock,F_GETFL) | O_NONBLOCK); +int set_non_blocking_socket(ortp_socket_t sock) { +#if !defined(_WIN32) && !defined(_WIN32_WCE) + return fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) | O_NONBLOCK); #else unsigned long nonBlock = 1; - return ioctlsocket(sock, FIONBIO , &nonBlock); + return ioctlsocket(sock, FIONBIO, &nonBlock); #endif } @@ -119,67 +113,63 @@ int set_non_blocking_socket (ortp_socket_t sock){ * ioctlsocket on Win32. * int retrun the result of the system method */ -int set_blocking_socket (ortp_socket_t sock){ -#if !defined(_WIN32) && !defined(_WIN32_WCE) - return fcntl (sock, F_SETFL, fcntl(sock, F_GETFL) & ~O_NONBLOCK); +int set_blocking_socket(ortp_socket_t sock) { +#if !defined(_WIN32) && !defined(_WIN32_WCE) + return fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) & ~O_NONBLOCK); #else unsigned long nonBlock = 0; - return ioctlsocket(sock, FIONBIO , &nonBlock); + return ioctlsocket(sock, FIONBIO, &nonBlock); #endif } - /* * this method is an utility method that calls close() on UNIX or * closesocket on Win32. * int retrun the result of the system method */ -int close_socket(ortp_socket_t sock){ -#if !defined(_WIN32) && !defined(_WIN32_WCE) - return close (sock); +int close_socket(ortp_socket_t sock) { +#if !defined(_WIN32) && !defined(_WIN32_WCE) + return close(sock); #else return closesocket(sock); #endif } -#if !defined(_WIN32) && !defined(_WIN32_WCE) - /* Use UNIX inet_aton method */ +#if !defined(_WIN32) && !defined(_WIN32_WCE) +/* Use UNIX inet_aton method */ #else - int inet_aton (const char * cp, struct in_addr * addr) - { - int retval; +int inet_aton(const char *cp, struct in_addr *addr) { + int retval; - retval = inet_pton (AF_INET, cp, addr); + retval = inet_pton(AF_INET, cp, addr); - return retval == 1 ? 1 : 0; - } + return retval == 1 ? 1 : 0; +} #endif -char *ortp_strndup(const char *str,int n){ - int min=MIN((int)strlen(str),n)+1; - char *ret=(char*)ortp_malloc(min); - strncpy(ret,str,min); - ret[min-1]='\0'; +char *ortp_strndup(const char *str, int n) { + int min = MIN((int)strlen(str), n) + 1; + char *ret = (char *)ortp_malloc(min); + strncpy(ret, str, min); + ret[min - 1] = '\0'; return ret; } -#if !defined(_WIN32) && !defined(_WIN32_WCE) -int __ortp_thread_join(ortp_thread_t thread, void **ptr){ - int err=pthread_join(thread,ptr); - if (err!=0) { - ortp_error("pthread_join error: %s",strerror(err)); +#if !defined(_WIN32) && !defined(_WIN32_WCE) +int __ortp_thread_join(ortp_thread_t thread, void **ptr) { + int err = pthread_join(thread, ptr); + if (err != 0) { + ortp_error("pthread_join error: %s", strerror(err)); } return err; } -int __ortp_thread_create(ortp_thread_t *thread, pthread_attr_t *attr, void * (*routine)(void*), void *arg){ +int __ortp_thread_create(ortp_thread_t *thread, pthread_attr_t *attr, void *(*routine)(void *), void *arg) { pthread_attr_t my_attr; pthread_attr_init(&my_attr); - if (attr) - my_attr = *attr; + if (attr) my_attr = *attr; #ifdef ORTP_DEFAULT_THREAD_STACK_SIZE - if (ORTP_DEFAULT_THREAD_STACK_SIZE!=0) - pthread_attr_setstacksize(&my_attr, ORTP_DEFAULT_THREAD_STACK_SIZE); + if (ORTP_DEFAULT_THREAD_STACK_SIZE != 0) pthread_attr_setstacksize(&my_attr, ORTP_DEFAULT_THREAD_STACK_SIZE); #endif return pthread_create(thread, &my_attr, routine, arg); } @@ -189,20 +179,18 @@ unsigned long __ortp_thread_self(void) { } #endif -#if defined(_WIN32) || defined(_WIN32_WCE) +#if defined(_WIN32) || defined(_WIN32_WCE) -int WIN_mutex_init(ortp_mutex_t *mutex, void *attr) -{ +int WIN_mutex_init(ortp_mutex_t *mutex, void *attr) { #ifdef ORTP_WINDOWS_DESKTOP - *mutex=CreateMutex(NULL, FALSE, NULL); + *mutex = CreateMutex(NULL, FALSE, NULL); #else InitializeSRWLock(mutex); #endif return 0; } -int WIN_mutex_lock(ortp_mutex_t * hMutex) -{ +int WIN_mutex_lock(ortp_mutex_t *hMutex) { #ifdef ORTP_WINDOWS_DESKTOP WaitForSingleObject(*hMutex, INFINITE); /* == WAIT_TIMEOUT; */ #else @@ -211,8 +199,7 @@ int WIN_mutex_lock(ortp_mutex_t * hMutex) return 0; } -int WIN_mutex_unlock(ortp_mutex_t * hMutex) -{ +int WIN_mutex_unlock(ortp_mutex_t *hMutex) { #ifdef ORTP_WINDOWS_DESKTOP ReleaseMutex(*hMutex); #else @@ -221,44 +208,40 @@ int WIN_mutex_unlock(ortp_mutex_t * hMutex) return 0; } -int WIN_mutex_destroy(ortp_mutex_t * hMutex) -{ +int WIN_mutex_destroy(ortp_mutex_t *hMutex) { #ifdef ORTP_WINDOWS_DESKTOP CloseHandle(*hMutex); #endif return 0; } -typedef struct thread_param{ - void * (*func)(void *); - void * arg; -}thread_param_t; +typedef struct thread_param { + void *(*func)(void *); + void *arg; +} thread_param_t; -static unsigned WINAPI thread_starter(void *data){ - thread_param_t *params=(thread_param_t*)data; +static unsigned WINAPI thread_starter(void *data) { + thread_param_t *params = (thread_param_t *)data; params->func(params->arg); ortp_free(data); return 0; } #if defined _WIN32_WCE -# define _beginthreadex CreateThread -# define _endthreadex ExitThread +#define _beginthreadex CreateThread +#define _endthreadex ExitThread #endif -int WIN_thread_create(ortp_thread_t *th, void *attr, void * (*func)(void *), void *data) -{ - thread_param_t *params=ortp_new(thread_param_t,1); - params->func=func; - params->arg=data; - *th=(HANDLE)_beginthreadex( NULL, 0, thread_starter, params, 0, NULL); +int WIN_thread_create(ortp_thread_t *th, void *attr, void *(*func)(void *), void *data) { + thread_param_t *params = ortp_new(thread_param_t, 1); + params->func = func; + params->arg = data; + *th = (HANDLE)_beginthreadex(NULL, 0, thread_starter, params, 0, NULL); return 0; } -int WIN_thread_join(ortp_thread_t thread_h, void **unused) -{ - if (thread_h!=NULL) - { +int WIN_thread_join(ortp_thread_t thread_h, void **unused) { + if (thread_h != NULL) { WaitForSingleObjectEx(thread_h, INFINITE, FALSE); CloseHandle(thread_h); } @@ -269,20 +252,18 @@ unsigned long WIN_thread_self(void) { return (unsigned long)GetCurrentThreadId(); } -int WIN_cond_init(ortp_cond_t *cond, void *attr) -{ +int WIN_cond_init(ortp_cond_t *cond, void *attr) { #ifdef ORTP_WINDOWS_DESKTOP - *cond=CreateEvent(NULL, FALSE, FALSE, NULL); + *cond = CreateEvent(NULL, FALSE, FALSE, NULL); #else InitializeConditionVariable(cond); #endif return 0; } -int WIN_cond_wait(ortp_cond_t* hCond, ortp_mutex_t * hMutex) -{ +int WIN_cond_wait(ortp_cond_t *hCond, ortp_mutex_t *hMutex) { #ifdef ORTP_WINDOWS_DESKTOP - //gulp: this is not very atomic ! bug here ? + // gulp: this is not very atomic ! bug here ? WIN_mutex_unlock(hMutex); WaitForSingleObject(*hCond, INFINITE); WIN_mutex_lock(hMutex); @@ -292,8 +273,7 @@ int WIN_cond_wait(ortp_cond_t* hCond, ortp_mutex_t * hMutex) return 0; } -int WIN_cond_signal(ortp_cond_t * hCond) -{ +int WIN_cond_signal(ortp_cond_t *hCond) { #ifdef ORTP_WINDOWS_DESKTOP SetEvent(*hCond); #else @@ -302,14 +282,12 @@ int WIN_cond_signal(ortp_cond_t * hCond) return 0; } -int WIN_cond_broadcast(ortp_cond_t * hCond) -{ +int WIN_cond_broadcast(ortp_cond_t *hCond) { WIN_cond_signal(hCond); return 0; } -int WIN_cond_destroy(ortp_cond_t * hCond) -{ +int WIN_cond_destroy(ortp_cond_t *hCond) { #ifdef ORTP_WINDOWS_DESKTOP CloseHandle(*hCond); #endif @@ -319,74 +297,68 @@ int WIN_cond_destroy(ortp_cond_t * hCond) #if defined(_WIN32_WCE) #include -const char * ortp_strerror(DWORD value) { +const char *ortp_strerror(DWORD value) { static TCHAR msgBuf[256]; - FormatMessage( - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - value, - 0, // Default language - (LPTSTR) &msgBuf, - 0, - NULL - ); + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, value, + 0, // Default language + (LPTSTR)&msgBuf, 0, NULL); return (const char *)msgBuf; } -int -gettimeofday (struct timeval *tv, void *tz) -{ - DWORD timemillis = GetTickCount(); - tv->tv_sec = timemillis/1000; - tv->tv_usec = (timemillis - (tv->tv_sec*1000)) * 1000; - return 0; +int gettimeofday(struct timeval *tv, void *tz) { + DWORD timemillis = GetTickCount(); + tv->tv_sec = timemillis / 1000; + tv->tv_usec = (timemillis - (tv->tv_sec * 1000)) * 1000; + return 0; } #else -int ortp_gettimeofday (struct timeval *tv, void* tz) -{ - union - { +int ortp_gettimeofday(struct timeval *tv, void *tz) { + union { __int64 ns100; /*time since 1 Jan 1601 in 100ns units */ FILETIME fileTime; } now; - GetSystemTimeAsFileTime (&now.fileTime); - tv->tv_usec = (long) ((now.ns100 / 10LL) % 1000000LL); - tv->tv_sec = (long) ((now.ns100 - 116444736000000000LL) / 10000000LL); + GetSystemTimeAsFileTime(&now.fileTime); + tv->tv_usec = (long)((now.ns100 / 10LL) % 1000000LL); + tv->tv_sec = (long)((now.ns100 - 116444736000000000LL) / 10000000LL); return (0); } #endif -const char *getWinSocketError(int error) -{ +const char *getWinSocketError(int error) { static char buf[80]; - switch (error) - { - case WSANOTINITIALISED: return "Windows sockets not initialized : call WSAStartup"; - case WSAEADDRINUSE: return "Local Address already in use"; - case WSAEADDRNOTAVAIL: return "The specified address is not a valid address for this machine"; - case WSAEINVAL: return "The socket is already bound to an address."; - case WSAENOBUFS: return "Not enough buffers available, too many connections."; - case WSAENOTSOCK: return "The descriptor is not a socket."; - case WSAECONNRESET: return "Connection reset by peer"; - - default : + switch (error) { + case WSANOTINITIALISED: + return "Windows sockets not initialized : call WSAStartup"; + case WSAEADDRINUSE: + return "Local Address already in use"; + case WSAEADDRNOTAVAIL: + return "The specified address is not a valid address for this machine"; + case WSAEINVAL: + return "The socket is already bound to an address."; + case WSAENOBUFS: + return "Not enough buffers available, too many connections."; + case WSAENOTSOCK: + return "The descriptor is not a socket."; + case WSAECONNRESET: + return "Connection reset by peer"; + + default: sprintf(buf, "Error code : %d", error); return buf; - break; + break; } return buf; } #ifdef _WORKAROUND_MINGW32_BUGS -char * WSAAPI gai_strerror(int errnum){ - return (char*)getWinSocketError(errnum); +char *WSAAPI gai_strerror(int errnum) { + return (char *)getWinSocketError(errnum); } #endif @@ -394,10 +366,10 @@ char * WSAAPI gai_strerror(int errnum){ #ifndef _WIN32 -#include #include -#include +#include #include +#include /* portable named pipes */ @@ -409,23 +381,26 @@ char * WSAAPI gai_strerror(int errnum){ #endif - #ifdef __MACH__ -#include #include +#include #endif -void _ortp_get_cur_time(ortpTimeSpec *ret, bool_t realtime){ +#ifndef _MSC_VER +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-parameter" +#endif // _MSC_VER +void _ortp_get_cur_time(ortpTimeSpec *ret, bool_t realtime) { #if defined(_WIN32_WCE) || defined(_WIN32) -#if defined( ORTP_WINDOWS_DESKTOP ) && !defined(ENABLE_MICROSOFT_STORE_APP) && !defined(ORTP_WINDOWS_UWP) +#if defined(ORTP_WINDOWS_DESKTOP) && !defined(ENABLE_MICROSOFT_STORE_APP) && !defined(ORTP_WINDOWS_UWP) DWORD timemillis; -# if defined(_WIN32_WCE) - timemillis=GetTickCount(); -# else - timemillis=timeGetTime(); -# endif - ret->tv_sec=timemillis/1000; - ret->tv_nsec=(timemillis%1000)*1000000LL; +#if defined(_WIN32_WCE) + timemillis = GetTickCount(); +#else + timemillis = timeGetTime(); +#endif + ret->tv_sec = timemillis / 1000; + ret->tv_nsec = (timemillis % 1000) * 1000000LL; #else ULONGLONG timemillis = GetTickCount64(); ret->tv_sec = timemillis / 1000; @@ -434,54 +409,57 @@ void _ortp_get_cur_time(ortpTimeSpec *ret, bool_t realtime){ #elif defined(__MACH__) && defined(__GNUC__) && (__GNUC__ >= 3) struct timeval tv; gettimeofday(&tv, NULL); - ret->tv_sec=tv.tv_sec; - ret->tv_nsec=tv.tv_usec*1000LL; + ret->tv_sec = tv.tv_sec; + ret->tv_nsec = tv.tv_usec * 1000LL; #elif defined(__MACH__) struct timeb time_val; - ftime (&time_val); + ftime(&time_val); ret->tv_sec = time_val.time; ret->tv_nsec = time_val.millitm * 1000000LL; #else struct timespec ts; - if (clock_gettime(realtime ? CLOCK_REALTIME : CLOCK_MONOTONIC,&ts)<0){ - ortp_fatal("clock_gettime() doesn't work: %s",strerror(errno)); + if (clock_gettime(realtime ? CLOCK_REALTIME : CLOCK_MONOTONIC, &ts) < 0) { + ortp_fatal("clock_gettime() doesn't work: %s", strerror(errno)); } - ret->tv_sec=ts.tv_sec; - ret->tv_nsec=ts.tv_nsec; + ret->tv_sec = ts.tv_sec; + ret->tv_nsec = ts.tv_nsec; #endif } +#ifndef _MSC_VER +#pragma GCC diagnostic pop +#endif // _MSC_VER -void ortp_get_cur_time(ortpTimeSpec *ret){ +void ortp_get_cur_time(ortpTimeSpec *ret) { _ortp_get_cur_time(ret, FALSE); } -void ortp_sleep_until(const ortpTimeSpec *ts){ +void ortp_sleep_until(const ortpTimeSpec *ts) { #ifdef __linux__ struct timespec rq; - rq.tv_sec=ts->tv_sec; - rq.tv_nsec=ts->tv_nsec; - while (clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &rq, NULL)==-1 && errno==EINTR){ + rq.tv_sec = ts->tv_sec; + rq.tv_nsec = ts->tv_nsec; + while (clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &rq, NULL) == -1 && errno == EINTR) { } #else ortpTimeSpec current; ortpTimeSpec diff; _ortp_get_cur_time(¤t, TRUE); - diff.tv_sec=ts->tv_sec-current.tv_sec; - diff.tv_nsec=ts->tv_nsec-current.tv_nsec; - if (diff.tv_nsec<0){ - diff.tv_nsec+=1000000000LL; - diff.tv_sec-=1; + diff.tv_sec = ts->tv_sec - current.tv_sec; + diff.tv_nsec = ts->tv_nsec - current.tv_nsec; + if (diff.tv_nsec < 0) { + diff.tv_nsec += 1000000000LL; + diff.tv_sec -= 1; } #ifdef _WIN32 - ortp_sleep_ms((int)((diff.tv_sec * 1000LL) + (diff.tv_nsec/1000000LL))); + ortp_sleep_ms((int)((diff.tv_sec * 1000LL) + (diff.tv_nsec / 1000000LL))); #else { - struct timespec dur,rem; - dur.tv_sec=diff.tv_sec; - dur.tv_nsec=diff.tv_nsec; - while (nanosleep(&dur,&rem)==-1 && errno==EINTR){ - dur=rem; + struct timespec dur, rem; + dur.tv_sec = diff.tv_sec; + dur.tv_nsec = diff.tv_nsec; + while (nanosleep(&dur, &rem) == -1 && errno == EINTR) { + dur = rem; }; } #endif @@ -489,19 +467,19 @@ void ortp_sleep_until(const ortpTimeSpec *ts){ } #if defined(_WIN32) && !defined(_MSC_VER) -char* strtok_r(char *str, const char *delim, char **nextp){ +char *strtok_r(char *str, const char *delim, char **nextp) { char *ret; - if (str == NULL){ + if (str == NULL) { str = *nextp; } str += strspn(str, delim); - if (*str == '\0'){ + if (*str == '\0') { return NULL; } ret = str; str += strcspn(str, delim); - if (*str){ + if (*str) { *str++ = '\0'; } *nextp = str; diff --git a/src/posixtimer.c b/src/posixtimer.c index 3b0c61e2..989e613e 100644 --- a/src/posixtimer.c +++ b/src/posixtimer.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -25,7 +25,7 @@ #include "ortp/ortp.h" #include "rtptimer.h" -#if !defined(_WIN32) && !defined(_WIN32_WCE) +#if !defined(_WIN32) && !defined(_WIN32_WCE) #ifdef __linux__ #include @@ -35,286 +35,233 @@ #include #include +static struct timeval orig, cur; +static uint32_t posix_timer_time = 0; /*in milisecond */ -static struct timeval orig,cur; -static uint32_t posix_timer_time=0; /*in milisecond */ - -void posix_timer_init(void) -{ - posix_timer.state=RTP_TIMER_RUNNING; - bctbx_gettimeofday(&orig,NULL); - posix_timer_time=0; +void posix_timer_init(void) { + posix_timer.state = RTP_TIMER_RUNNING; + bctbx_gettimeofday(&orig, NULL); + posix_timer_time = 0; } - - - -void posix_timer_do(void) -{ - int diff,time; +void posix_timer_do(void) { + int diff, time; struct timeval tv; - bctbx_gettimeofday(&cur,NULL); - time=((cur.tv_usec-orig.tv_usec)/1000 ) + ((cur.tv_sec-orig.tv_sec)*1000 ); - if ( (diff=time-posix_timer_time)>50){ - ortp_warning("Must catchup %i miliseconds.",diff); + bctbx_gettimeofday(&cur, NULL); + time = ((cur.tv_usec - orig.tv_usec) / 1000) + ((cur.tv_sec - orig.tv_sec) * 1000); + if ((diff = time - posix_timer_time) > 50) { + ortp_warning("Must catchup %i miliseconds.", diff); } - while((diff = posix_timer_time-time) > 0) - { - tv.tv_sec = diff/1000; - tv.tv_usec = (diff%1000)*1000; -#if defined(_WIN32) || defined(_WIN32_WCE) - /* this kind of select is not supported on windows */ - Sleep(tv.tv_usec/1000 + tv.tv_sec * 1000); + while ((diff = posix_timer_time - time) > 0) { + tv.tv_sec = diff / 1000; + tv.tv_usec = (diff % 1000) * 1000; +#if defined(_WIN32) || defined(_WIN32_WCE) + /* this kind of select is not supported on windows */ + Sleep(tv.tv_usec / 1000 + tv.tv_sec * 1000); #else - select(0,NULL,NULL,NULL,&tv); + select(0, NULL, NULL, NULL, &tv); #endif - bctbx_gettimeofday(&cur,NULL); - time=((cur.tv_usec-orig.tv_usec)/1000 ) + ((cur.tv_sec-orig.tv_sec)*1000 ); + bctbx_gettimeofday(&cur, NULL); + time = ((cur.tv_usec - orig.tv_usec) / 1000) + ((cur.tv_sec - orig.tv_sec) * 1000); } - posix_timer_time+=POSIXTIMER_INTERVAL/1000; - + posix_timer_time += POSIXTIMER_INTERVAL / 1000; } -void posix_timer_uninit(void) -{ - posix_timer.state=RTP_TIMER_STOPPED; +void posix_timer_uninit(void) { + posix_timer.state = RTP_TIMER_STOPPED; } -RtpTimer posix_timer={ 0, - posix_timer_init, - posix_timer_do, - posix_timer_uninit, - {0,POSIXTIMER_INTERVAL}}; - +RtpTimer posix_timer = {0, posix_timer_init, posix_timer_do, posix_timer_uninit, {0, POSIXTIMER_INTERVAL}}; #else //_WIN32 - #if defined(ENABLE_MICROSOFT_STORE_APP) || defined(ORTP_WINDOWS_UWP) -#include #include - +#include PTP_TIMER timerId; -HANDLE TimeEvent; -int late_ticks; - +HANDLE TimeEvent; +int late_ticks; static DWORD posix_timer_time; static DWORD offset_time; -#define TIME_INTERVAL 50 -#define TIME_RESOLUTION 10 -#define TIME_TIMEOUT 100 +#define TIME_INTERVAL 50 +#define TIME_RESOLUTION 10 +#define TIME_TIMEOUT 100 static PTP_TIMER g_timerId = NULL; static PTP_CLEANUP_GROUP g_cleanupgroup = NULL; static PTP_POOL g_pool = NULL; - -VOID CALLBACK timerCb(PTP_CALLBACK_INSTANCE Instance,PVOID Context,PTP_TIMER Timer) -{ - if(Timer == g_timerId) { - SetEvent(TimeEvent); - posix_timer_time += TIME_INTERVAL; - } -} - - -void win_timer_init(void) -{ - BOOL bRet = FALSE; - PTP_WORK work = NULL; - FILETIME FileDueTime; - TP_CALLBACK_ENVIRON CallBackEnviron; - - InitializeThreadpoolEnvironment(&CallBackEnviron); - g_pool = CreateThreadpool(NULL); // Create a custom, dedicated thread pool. - if (NULL == g_pool) { - ortp_warning("CreateThreadpool failed. LastError: %u\n", GetLastError()); - return; - } - SetThreadpoolThreadMaximum(g_pool, 1); // The thread pool is made persistent simply by setting - bRet = SetThreadpoolThreadMinimum(g_pool, 1); // both the minimum and maximum threads to 1. - if (FALSE == bRet) { - ortp_warning("SetThreadpoolThreadMinimum failed. LastError: %u\n", GetLastError()); - return; - } - g_cleanupgroup = CreateThreadpoolCleanupGroup(); // Create a cleanup group for this thread pool. - if (NULL == g_cleanupgroup) { - ortp_warning("CreateThreadpoolCleanupGroup failed. LastError: %u\n", GetLastError()); - return; - } - SetThreadpoolCallbackPool(&CallBackEnviron, g_pool); // Associate the callback environment with our thread pool. - // Associate the cleanup group with our thread pool. Objects created with the same callback environment as the cleanup group become members of the cleanup group. - SetThreadpoolCallbackCleanupGroup(&CallBackEnviron, g_cleanupgroup, NULL); - g_timerId = CreateThreadpoolTimer(timerCb, NULL, &CallBackEnviron); // Create a timer with the same callback environment. - if (NULL == g_timerId) { - ortp_warning("CreateThreadpoolTimer failed. LastError: %u\n", GetLastError()); - return; - } - - SYSTEMTIME thesystemtime; - GetSystemTime(&thesystemtime); - thesystemtime.wYear++; - SystemTimeToFileTime(&thesystemtime,&FileDueTime); - //ULARGE_INTEGER ulDueTime; - //ulDueTime.QuadPart = (ULONGLONG)604800 * 10 * 1000 * 1000; - //FileDueTime.dwHighDateTime = ulDueTime.HighPart; - //FileDueTime.dwLowDateTime = ulDueTime.LowPart; - SetThreadpoolTimer(timerId, &FileDueTime, TIME_INTERVAL, 0); - TimeEvent = CreateEvent(NULL,FALSE,FALSE,NULL); - late_ticks = 0; - offset_time = GetTickCount(); - posix_timer_time=0; +VOID CALLBACK timerCb(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_TIMER Timer) { + if (Timer == g_timerId) { + SetEvent(TimeEvent); + posix_timer_time += TIME_INTERVAL; + } } +void win_timer_init(void) { + BOOL bRet = FALSE; + PTP_WORK work = NULL; + FILETIME FileDueTime; + TP_CALLBACK_ENVIRON CallBackEnviron; -void win_timer_do(void){ - if(g_timerId) { - DWORD diff; - // If timer have expired while we where out of this method - // Try to run after lost time. - if (late_ticks > 0) - { - late_ticks--; - posix_timer_time+=TIME_INTERVAL; + InitializeThreadpoolEnvironment(&CallBackEnviron); + g_pool = CreateThreadpool(NULL); // Create a custom, dedicated thread pool. + if (NULL == g_pool) { + ortp_warning("CreateThreadpool failed. LastError: %u\n", GetLastError()); return; } - diff = GetTickCount() - posix_timer_time - offset_time; - if( diff>TIME_INTERVAL && (diff<(1<<31))) - { - late_ticks = diff/TIME_INTERVAL; - ortp_warning("we must catchup %i ticks.",late_ticks); + SetThreadpoolThreadMaximum(g_pool, 1); // The thread pool is made persistent simply by setting + bRet = SetThreadpoolThreadMinimum(g_pool, 1); // both the minimum and maximum threads to 1. + if (FALSE == bRet) { + ortp_warning("SetThreadpoolThreadMinimum failed. LastError: %u\n", GetLastError()); return; } - WaitForSingleObject(TimeEvent,TIME_TIMEOUT); - return; - } + g_cleanupgroup = CreateThreadpoolCleanupGroup(); // Create a cleanup group for this thread pool. + if (NULL == g_cleanupgroup) { + ortp_warning("CreateThreadpoolCleanupGroup failed. LastError: %u\n", GetLastError()); + return; + } + SetThreadpoolCallbackPool(&CallBackEnviron, g_pool); // Associate the callback environment with our thread pool. + // Associate the cleanup group with our thread pool. Objects created with the same callback environment as the + // cleanup group become members of the cleanup group. + SetThreadpoolCallbackCleanupGroup(&CallBackEnviron, g_cleanupgroup, NULL); + g_timerId = + CreateThreadpoolTimer(timerCb, NULL, &CallBackEnviron); // Create a timer with the same callback environment. + if (NULL == g_timerId) { + ortp_warning("CreateThreadpoolTimer failed. LastError: %u\n", GetLastError()); + return; + } + + SYSTEMTIME thesystemtime; + GetSystemTime(&thesystemtime); + thesystemtime.wYear++; + SystemTimeToFileTime(&thesystemtime, &FileDueTime); + // ULARGE_INTEGER ulDueTime; + // ulDueTime.QuadPart = (ULONGLONG)604800 * 10 * 1000 * 1000; + // FileDueTime.dwHighDateTime = ulDueTime.HighPart; + // FileDueTime.dwLowDateTime = ulDueTime.LowPart; + SetThreadpoolTimer(timerId, &FileDueTime, TIME_INTERVAL, 0); + TimeEvent = CreateEvent(NULL, FALSE, FALSE, NULL); + late_ticks = 0; + offset_time = GetTickCount(); + posix_timer_time = 0; } +void win_timer_do(void) { + if (g_timerId) { + DWORD diff; + // If timer have expired while we where out of this method + // Try to run after lost time. + if (late_ticks > 0) { + late_ticks--; + posix_timer_time += TIME_INTERVAL; + return; + } + diff = GetTickCount() - posix_timer_time - offset_time; + if (diff > TIME_INTERVAL && (diff < (1 << 31))) { + late_ticks = diff / TIME_INTERVAL; + ortp_warning("we must catchup %i ticks.", late_ticks); + return; + } + WaitForSingleObject(TimeEvent, TIME_TIMEOUT); + return; + } +} -void win_timer_close(void) -{ - if( g_timerId != NULL) { - SetThreadpoolTimer(g_timerId, NULL, 0, 0); - CloseThreadpoolTimer(g_timerId); - g_timerId = NULL; - } - if(g_cleanupgroup != NULL ){ // Clean up the cleanup group members. - CloseThreadpoolCleanupGroupMembers(g_cleanupgroup, FALSE, NULL); - CloseThreadpoolCleanupGroup(g_cleanupgroup); - g_cleanupgroup = NULL; - } - if(g_pool!=NULL ){ // Clean up the pool. - CloseThreadpool(g_pool); - g_pool = NULL; - } +void win_timer_close(void) { + if (g_timerId != NULL) { + SetThreadpoolTimer(g_timerId, NULL, 0, 0); + CloseThreadpoolTimer(g_timerId); + g_timerId = NULL; + } + if (g_cleanupgroup != NULL) { // Clean up the cleanup group members. + CloseThreadpoolCleanupGroupMembers(g_cleanupgroup, FALSE, NULL); + CloseThreadpoolCleanupGroup(g_cleanupgroup); + g_cleanupgroup = NULL; + } + if (g_pool != NULL) { // Clean up the pool. + CloseThreadpool(g_pool); + g_pool = NULL; + } } RtpTimer toto; -RtpTimer posix_timer={ 0, - win_timer_init, - win_timer_do, - win_timer_close, - {0,TIME_INTERVAL * 1000}}; +RtpTimer posix_timer = {0, win_timer_init, win_timer_do, win_timer_close, {0, TIME_INTERVAL * 1000}}; #elif defined ORTP_WINDOWS_DESKTOP - -#include #include - +#include MMRESULT timerId; -HANDLE TimeEvent; -int late_ticks; - +HANDLE TimeEvent; +int late_ticks; static DWORD posix_timer_time; static DWORD offset_time; +#define TIME_INTERVAL 50 +#define TIME_RESOLUTION 10 +#define TIME_TIMEOUT 100 -#define TIME_INTERVAL 50 -#define TIME_RESOLUTION 10 -#define TIME_TIMEOUT 100 - - - -void CALLBACK timerCb(UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2) -{ - // Check timerId - if (timerId == uID) - { - SetEvent(TimeEvent); - posix_timer_time += TIME_INTERVAL; - } +void CALLBACK timerCb(UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2) { + // Check timerId + if (timerId == uID) { + SetEvent(TimeEvent); + posix_timer_time += TIME_INTERVAL; + } } - -void win_timer_init(void) -{ +void win_timer_init(void) { timerId = timeSetEvent(TIME_INTERVAL, 10, timerCb, (DWORD)0, (UINT)(TIME_PERIODIC | TIME_CALLBACK_FUNCTION)); - TimeEvent = CreateEvent(NULL,FALSE,FALSE,NULL); + TimeEvent = CreateEvent(NULL, FALSE, FALSE, NULL); - late_ticks = 0; + late_ticks = 0; - offset_time = GetTickCount(); - posix_timer_time=0; + offset_time = GetTickCount(); + posix_timer_time = 0; } +void win_timer_do(void) { + DWORD diff; -void win_timer_do(void) -{ - DWORD diff; - - // If timer have expired while we where out of this method - // Try to run after lost time. - if (late_ticks > 0) - { - late_ticks--; - posix_timer_time+=TIME_INTERVAL; - return; - } - + // If timer have expired while we where out of this method + // Try to run after lost time. + if (late_ticks > 0) { + late_ticks--; + posix_timer_time += TIME_INTERVAL; + return; + } - diff = GetTickCount() - posix_timer_time - offset_time; - if( diff>TIME_INTERVAL && (diff<(1<<31))) - { - late_ticks = diff/TIME_INTERVAL; - ortp_warning("we must catchup %i ticks.",late_ticks); - return; - } + diff = GetTickCount() - posix_timer_time - offset_time; + if (diff > TIME_INTERVAL && (diff < (1 << 31))) { + late_ticks = diff / TIME_INTERVAL; + ortp_warning("we must catchup %i ticks.", late_ticks); + return; + } - WaitForSingleObject(TimeEvent,TIME_TIMEOUT); - return; + WaitForSingleObject(TimeEvent, TIME_TIMEOUT); + return; } - -void win_timer_close(void) -{ +void win_timer_close(void) { timeKillEvent(timerId); } RtpTimer toto; -RtpTimer posix_timer={ 0, - win_timer_init, - win_timer_do, - win_timer_close, - {0,TIME_INTERVAL * 1000}}; +RtpTimer posix_timer = {0, win_timer_init, win_timer_do, win_timer_close, {0, TIME_INTERVAL * 1000}}; #elif defined(ORTP_WINDOWS_PHONE) #include "winrttimer.h" -RtpTimer posix_timer={ 0, - winrt_timer_init, - winrt_timer_do, - winrt_timer_close, - {0, TIME_INTERVAL * 1000}}; +RtpTimer posix_timer = {0, winrt_timer_init, winrt_timer_do, winrt_timer_close, {0, TIME_INTERVAL * 1000}}; #endif diff --git a/src/rtcp.c b/src/rtcp.c index 4e18e2cd..f988e2b9 100644 --- a/src/rtcp.c +++ b/src/rtcp.c @@ -1,7 +1,7 @@ /* - * Copyright (c) 2010-2022 Belledonne Communications SARL. + * Copyright (c) 2004-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -25,19 +25,21 @@ * Copyright 2004 Simon Morlat * Email simon dot morlat at linphone dot org ****************************************************************************/ + +#include + #ifdef HAVE_CONFIG_H #include "ortp-config.h" #endif +#include "jitterctl.h" #include "ortp/ortp.h" -#include "ortp/rtpsession.h" #include "ortp/rtcp.h" -#include "utils.h" +#include "ortp/rtpsession.h" #include "rtpsession_priv.h" -#include "jitterctl.h" - -#define rtcp_bye_set_ssrc(b,pos,ssrc) (b)->ssrc[pos]=htonl(ssrc) -#define rtcp_bye_get_ssrc(b,pos) ntohl((b)->ssrc[pos]) +#include "utils.h" +#define rtcp_bye_set_ssrc(b, pos, ssrc) (b)->ssrc[pos] = htonl(ssrc) +#define rtcp_bye_get_ssrc(b, pos) ntohl((b)->ssrc[pos]) static mblk_t *rtcp_create_simple_bye_packet(uint32_t ssrc, const char *reason) { int packet_size; @@ -47,70 +49,75 @@ static mblk_t *rtcp_create_simple_bye_packet(uint32_t ssrc, const char *reason) rtcp_bye_t *rtcp; packet_size = RTCP_BYE_HEADER_SIZE; - if (reason!=NULL) { - strsize=(int)MIN(strlen(reason),RTCP_BYE_REASON_MAX_STRING_SIZE); + if (reason != NULL) { + strsize = (int)MIN(strlen(reason), RTCP_BYE_REASON_MAX_STRING_SIZE); if (strsize > 0) { strpadding = 3 - (strsize % 4); packet_size += 1 + strsize + strpadding; } } - mp = allocb(packet_size, 0); + mp = allocb(packet_size, 0); - rtcp = (rtcp_bye_t*)mp->b_rptr; - rtcp_common_header_init(&rtcp->ch,NULL,RTCP_BYE,1,packet_size); + rtcp = (rtcp_bye_t *)mp->b_rptr; + rtcp_common_header_init(&rtcp->ch, NULL, RTCP_BYE, 1, packet_size); rtcp->ssrc[0] = htonl(ssrc); mp->b_wptr += RTCP_BYE_HEADER_SIZE; /* append the reason if any*/ - if (reason!=NULL) { + if (reason != NULL) { const char pad[] = {0, 0, 0}; unsigned char strsize_octet = (unsigned char)strsize; - appendb(mp, (const char*)&strsize_octet, 1, FALSE); - appendb(mp, reason,strsize, FALSE); - appendb(mp, pad,strpadding, FALSE); + appendb(mp, (const char *)&strsize_octet, 1, FALSE); + appendb(mp, reason, strsize, FALSE); + appendb(mp, pad, strpadding, FALSE); } return mp; } -static mblk_t *sdes_chunk_new(uint32_t ssrc){ - mblk_t *m=allocb(RTCP_SDES_CHUNK_DEFAULT_SIZE,0); - sdes_chunk_t *sc=(sdes_chunk_t*)m->b_rptr; - sc->csrc=htonl(ssrc); - m->b_wptr+=sizeof(sc->csrc); +static mblk_t *sdes_chunk_new(uint32_t ssrc) { + mblk_t *m = allocb(RTCP_SDES_CHUNK_DEFAULT_SIZE, 0); + sdes_chunk_t *sc = (sdes_chunk_t *)m->b_rptr; + sc->csrc = htonl(ssrc); + m->b_wptr += sizeof(sc->csrc); return m; } -static mblk_t * sdes_chunk_append_item(mblk_t *m, rtcp_sdes_type_t sdes_type, const char *content) { - if ( content ) - { +static mblk_t *sdes_chunk_append_item(mblk_t *m, rtcp_sdes_type_t sdes_type, const char *content) { + if (content) { sdes_item_t si; - si.item_type=sdes_type; - si.len=(uint8_t) MIN(strlen(content),RTCP_SDES_MAX_STRING_SIZE); - m=appendb(m,(char*)&si,RTCP_SDES_ITEM_HEADER_SIZE,FALSE); - m=appendb(m,content,si.len,FALSE); + si.item_type = sdes_type; + si.len = (uint8_t)MIN(strlen(content), RTCP_SDES_MAX_STRING_SIZE); + m = appendb(m, (char *)&si, RTCP_SDES_ITEM_HEADER_SIZE, FALSE); + m = appendb(m, content, si.len, FALSE); } return m; } -static void sdes_chunk_set_ssrc(mblk_t *m, uint32_t ssrc){ - sdes_chunk_t *sc=(sdes_chunk_t*)m->b_rptr; - sc->csrc=htonl(ssrc); +static void sdes_chunk_set_ssrc(mblk_t *m, uint32_t ssrc) { + sdes_chunk_t *sc = (sdes_chunk_t *)m->b_rptr; + sc->csrc = htonl(ssrc); } -static mblk_t * sdes_chunk_pad(mblk_t *m){ - return appendb(m,"",1,TRUE); +static mblk_t *sdes_chunk_pad(mblk_t *m) { + return appendb(m, "", 1, TRUE); } -static mblk_t * sdes_chunk_set_minimal_items(mblk_t *m, const char *cname) { +static mblk_t *sdes_chunk_set_minimal_items(mblk_t *m, const char *cname) { if (cname == NULL) { cname = "Unknown"; } return sdes_chunk_append_item(m, RTCP_SDES_CNAME, cname); } -static mblk_t * sdes_chunk_set_full_items(mblk_t *m, const char *cname, - const char *name, const char *email, const char *phone, const char *loc, - const char *tool, const char *note, const char *mid) { +static mblk_t *sdes_chunk_set_full_items(mblk_t *m, + const char *cname, + const char *name, + const char *email, + const char *phone, + const char *loc, + const char *tool, + const char *note, + const char *mid) { m = sdes_chunk_set_minimal_items(m, cname); m = sdes_chunk_append_item(m, RTCP_SDES_NAME, name); m = sdes_chunk_append_item(m, RTCP_SDES_EMAIL, email); @@ -126,14 +133,19 @@ static mblk_t * sdes_chunk_set_full_items(mblk_t *m, const char *cname, /** * Set session's SDES item for automatic sending of RTCP compound packets. * If some items are not specified, use NULL. -**/ -void rtp_session_set_source_description(RtpSession *session, const char *cname, - const char *name, const char *email, const char *phone, const char *loc, - const char *tool, const char *note) { - const char* mid = NULL; + **/ +void rtp_session_set_source_description(RtpSession *session, + const char *cname, + const char *name, + const char *email, + const char *phone, + const char *loc, + const char *tool, + const char *note) { + const char *mid = NULL; mblk_t *m; mblk_t *chunk = sdes_chunk_new(session->snd.ssrc); - if (strlen(cname)>255) { + if (strlen(cname) > 255) { /* * rfc3550, * 6.5 SDES: Source Description RTCP Packet @@ -141,7 +153,7 @@ void rtp_session_set_source_description(RtpSession *session, const char *cname, * Note that the text can be no longer than 255 octets, * * */ - ortp_warning("Cname [%s] too long for session [%p]",cname,session); + ortp_warning("Cname [%s] too long for session [%p]", cname, session); } /* Add mid to chunck if there is a bundle */ @@ -150,22 +162,26 @@ void rtp_session_set_source_description(RtpSession *session, const char *cname, } sdes_chunk_set_full_items(chunk, cname, name, email, phone, loc, tool, note, mid); - if (session->full_sdes != NULL) - freemsg(session->full_sdes); + if (session->full_sdes != NULL) freemsg(session->full_sdes); session->full_sdes = chunk; chunk = sdes_chunk_new(session->snd.ssrc); m = sdes_chunk_set_minimal_items(chunk, cname); m = sdes_chunk_append_item(m, RTCP_SDES_MID, mid); m = sdes_chunk_pad(m); - if (session->minimal_sdes != NULL) - freemsg(session->minimal_sdes); + if (session->minimal_sdes != NULL) freemsg(session->minimal_sdes); session->minimal_sdes = chunk; } -void rtp_session_add_contributing_source(RtpSession *session, uint32_t csrc, - const char *cname, const char *name, const char *email, const char *phone, - const char *loc, const char *tool, const char *note) { - const char* mid = NULL; +void rtp_session_add_contributing_source(RtpSession *session, + uint32_t csrc, + const char *cname, + const char *name, + const char *email, + const char *phone, + const char *loc, + const char *tool, + const char *note) { + const char *mid = NULL; mblk_t *chunk = sdes_chunk_new(csrc); /* Add mid to chunck if there is a bundle */ @@ -178,33 +194,34 @@ void rtp_session_add_contributing_source(RtpSession *session, uint32_t csrc, } void rtp_session_remove_contributing_source(RtpSession *session, uint32_t ssrc) { - queue_t *q=&session->contributing_sources; + queue_t *q = &session->contributing_sources; mblk_t *tmp; - for (tmp=qbegin(q); !qend(q,tmp); tmp=qnext(q,tmp)){ - uint32_t csrc=sdes_chunk_get_ssrc(tmp); - if (csrc==ssrc) { - remq(q,tmp); + for (tmp = qbegin(q); !qend(q, tmp); tmp = qnext(q, tmp)) { + uint32_t csrc = sdes_chunk_get_ssrc(tmp); + if (csrc == ssrc) { + remq(q, tmp); break; } } - tmp=rtcp_create_simple_bye_packet(ssrc, NULL); - rtp_session_rtcp_send(session,tmp); + tmp = rtcp_create_simple_bye_packet(ssrc, NULL); + rtp_session_rtcp_send(session, tmp); } void rtp_session_clear_contributing_sources(RtpSession *session) { - queue_t *q=&session->contributing_sources; + queue_t *q = &session->contributing_sources; flushq(q, 0); } -void rtcp_common_header_init(rtcp_common_header_t *ch, RtpSession *s,int type, int rc, size_t bytes_len){ - rtcp_common_header_set_version(ch,2); - rtcp_common_header_set_padbit(ch,0); - rtcp_common_header_set_packet_type(ch,type); - rtcp_common_header_set_rc(ch,rc); /* as we don't yet support multi source receiving */ - rtcp_common_header_set_length(ch,(unsigned short)((bytes_len/4)-1)); +void rtcp_common_header_init( + rtcp_common_header_t *ch, BCTBX_UNUSED(RtpSession *s), int type, int rc, size_t bytes_len) { + rtcp_common_header_set_version(ch, 2); + rtcp_common_header_set_padbit(ch, 0); + rtcp_common_header_set_packet_type(ch, type); + rtcp_common_header_set_rc(ch, rc); /* as we don't yet support multi source receiving */ + rtcp_common_header_set_length(ch, (unsigned short)((bytes_len / 4) - 1)); } -mblk_t* rtp_session_create_rtcp_sdes_packet(RtpSession *session, bool_t full) { +mblk_t *rtp_session_create_rtcp_sdes_packet(RtpSession *session, bool_t full) { mblk_t *mp = allocb(sizeof(rtcp_common_header_t), 0); rtcp_common_header_t *rtcp; mblk_t *tmp; @@ -234,180 +251,177 @@ mblk_t* rtp_session_create_rtcp_sdes_packet(RtpSession *session, bool_t full) { return mp; } -static void sender_info_init(sender_info_t *info, RtpSession *session){ +static void sender_info_init(sender_info_t *info, RtpSession *session) { struct timeval tv; uint64_t ntp; - bctbx_gettimeofday(&tv,NULL); - ntp=ortp_timeval_to_ntp(&tv); - info->ntp_timestamp_msw=htonl(ntp >>32); - info->ntp_timestamp_lsw=htonl(ntp & 0xFFFFFFFF); - info->rtp_timestamp=htonl(session->rtp.snd_last_ts); - info->senders_packet_count=(uint32_t) htonl((u_long) session->stats.packet_sent); - info->senders_octet_count=(uint32_t) htonl((u_long) session->rtp.sent_payload_bytes); - session->rtp.last_rtcp_packet_count=(uint32_t)session->stats.packet_sent; -} - -static void report_block_init(report_block_t *b, RtpSession *session){ - int packet_loss=0; - int loss_fraction=0; - RtpStream *stream=&session->rtp; - uint32_t delay_snc_last_sr=0; + bctbx_gettimeofday(&tv, NULL); + ntp = ortp_timeval_to_ntp(&tv); + info->ntp_timestamp_msw = htonl(ntp >> 32); + info->ntp_timestamp_lsw = htonl(ntp & 0xFFFFFFFF); + info->rtp_timestamp = htonl(session->rtp.snd_last_ts); + info->senders_packet_count = (uint32_t)htonl((u_long)session->stats.packet_sent); + info->senders_octet_count = (uint32_t)htonl((u_long)session->rtp.sent_payload_bytes); + session->rtp.last_rtcp_packet_count = (uint32_t)session->stats.packet_sent; +} + +static void report_block_init(report_block_t *b, RtpSession *session) { + int packet_loss = 0; + int loss_fraction = 0; + RtpStream *stream = &session->rtp; + uint32_t delay_snc_last_sr = 0; /* compute the statistics */ - if (stream->hwrcv_since_last_SR!=0){ - uint32_t expected_packets=(uint32_t)(stream->hwrcv_extseq - stream->hwrcv_seq_at_last_SR); + if (stream->hwrcv_since_last_SR != 0) { + uint32_t expected_packets = (uint32_t)(stream->hwrcv_extseq - stream->hwrcv_seq_at_last_SR); - if ( session->flags & RTCP_OVERRIDE_LOST_PACKETS ) { + if (session->flags & RTCP_OVERRIDE_LOST_PACKETS) { /* If the test mode is enabled, replace the lost packet field with the test vector value set by rtp_session_rtcp_set_lost_packet_value() */ packet_loss = session->lost_packets_test_vector; /* The test value is the definite cumulative one, no need to increment it each time a packet is sent */ session->stats.cum_packet_loss = packet_loss; - }else { + } else { /* Normal mode */ packet_loss = (int)(expected_packets - stream->hwrcv_since_last_SR); session->stats.cum_packet_loss += packet_loss; } - if (expected_packets>0 && packet_loss > 0){/*prevent division by zero and negative loss fraction*/ - loss_fraction=(int)( 256 * packet_loss) / expected_packets; + if (expected_packets > 0 && packet_loss > 0) { /*prevent division by zero and negative loss fraction*/ + loss_fraction = (int)(256 * packet_loss) / expected_packets; /*make sure this fits into 8 bit unsigned*/ - if (loss_fraction>255) loss_fraction=255; - else if (loss_fraction<0) loss_fraction=0; - }else{ - loss_fraction=0; + if (loss_fraction > 255) loss_fraction = 255; + else if (loss_fraction < 0) loss_fraction = 0; + } else { + loss_fraction = 0; } } ortp_debug("report_block_init[%p]:\n" - "\texpected_packets=%d=%u-%u\n" - "\thwrcv_since_last_SR=%u\n" - "\tpacket_loss=%d\n" - "\tcum_packet_loss=%lld\n" - "\tloss_fraction=%f%%\n" - , session - , stream->hwrcv_extseq - stream->hwrcv_seq_at_last_SR, stream->hwrcv_extseq, stream->hwrcv_seq_at_last_SR - , stream->hwrcv_since_last_SR - , packet_loss - , (long long)session->stats.cum_packet_loss - , loss_fraction/2.56 - ); + "\texpected_packets=%d=%u-%u\n" + "\thwrcv_since_last_SR=%u\n" + "\tpacket_loss=%d\n" + "\tcum_packet_loss=%lld\n" + "\tloss_fraction=%f%%\n", + session, stream->hwrcv_extseq - stream->hwrcv_seq_at_last_SR, stream->hwrcv_extseq, + stream->hwrcv_seq_at_last_SR, stream->hwrcv_since_last_SR, packet_loss, + (long long)session->stats.cum_packet_loss, loss_fraction / 2.56); /* reset them */ - stream->hwrcv_since_last_SR=0; - stream->hwrcv_seq_at_last_SR=stream->hwrcv_extseq; + stream->hwrcv_since_last_SR = 0; + stream->hwrcv_seq_at_last_SR = stream->hwrcv_extseq; - if (stream->last_rcv_SR_time.tv_sec!=0){ + if (stream->last_rcv_SR_time.tv_sec != 0) { struct timeval now; double delay; - bctbx_gettimeofday(&now,NULL); - delay= (now.tv_sec-stream->last_rcv_SR_time.tv_sec)+ ((now.tv_usec-stream->last_rcv_SR_time.tv_usec)*1e-6); - delay= (delay*65536); - delay_snc_last_sr=(uint32_t) delay; + bctbx_gettimeofday(&now, NULL); + delay = + (now.tv_sec - stream->last_rcv_SR_time.tv_sec) + ((now.tv_usec - stream->last_rcv_SR_time.tv_usec) * 1e-6); + delay = (delay * 65536); + delay_snc_last_sr = (uint32_t)delay; } - b->ssrc=htonl(session->rcv.ssrc); - + b->ssrc = htonl(session->rcv.ssrc); report_block_set_cum_packet_lost(b, session->stats.cum_packet_loss); report_block_set_fraction_lost(b, loss_fraction); - if ( session->flags & RTCP_OVERRIDE_JITTER ) { - /* If the test mode is enabled, replace the interarrival jitter field with the test vector value set by rtp_session_rtcp_set_jitter_value() */ - b->interarrival_jitter = htonl( session->interarrival_jitter_test_vector ); - } - else { + if (session->flags & RTCP_OVERRIDE_JITTER) { + /* If the test mode is enabled, replace the interarrival jitter field with the test vector value set by + * rtp_session_rtcp_set_jitter_value() */ + b->interarrival_jitter = htonl(session->interarrival_jitter_test_vector); + } else { /* Normal mode */ - b->interarrival_jitter = htonl( (uint32_t) stream->jittctl.inter_jitter ); + b->interarrival_jitter = htonl((uint32_t)stream->jittctl.inter_jitter); } - b->ext_high_seq_num_rec=htonl(stream->hwrcv_extseq); - b->delay_snc_last_sr=htonl(delay_snc_last_sr); - if ( session->flags & RTCP_OVERRIDE_DELAY ) { - /* If the test mode is enabled, modifies the returned ts (LSR) so it matches the value of the delay test value */ + b->ext_high_seq_num_rec = htonl(stream->hwrcv_extseq); + b->delay_snc_last_sr = htonl(delay_snc_last_sr); + if (session->flags & RTCP_OVERRIDE_DELAY) { + /* If the test mode is enabled, modifies the returned ts (LSR) so it matches the value of the delay test value + */ /* refer to the rtp_session_rtcp_set_delay_value() documentation for further explanations */ - double new_ts = ( (double)stream->last_rcv_SR_time.tv_sec + (double)stream->last_rcv_SR_time.tv_usec * 1e-6 ) - ( (double)session->delay_test_vector / 1000.0 ); + double new_ts = ((double)stream->last_rcv_SR_time.tv_sec + (double)stream->last_rcv_SR_time.tv_usec * 1e-6) - + ((double)session->delay_test_vector / 1000.0); uint32_t new_ts2; /* Converting the time format in RFC3550 (par. 4) format */ new_ts += 2208988800.0; /* 2208988800 is the number of seconds from 1900 to 1970 (January 1, Oh TU) */ new_ts = 65536.0 * new_ts; /* This non-elegant way of coding fits with the gcc and the icc compilers */ - new_ts2 = (uint32_t)( (uint64_t)new_ts & 0xffffffff ); - b->lsr = htonl( new_ts2 ); - } - else { + new_ts2 = (uint32_t)((uint64_t)new_ts & 0xffffffff); + b->lsr = htonl(new_ts2); + } else { /* Normal mode */ - b->lsr = htonl( stream->last_rcv_SR_ts ); + b->lsr = htonl(stream->last_rcv_SR_ts); } } -static void extended_statistics( RtpSession *session, report_block_t * rb ) { +static void extended_statistics(RtpSession *session, BCTBX_UNUSED(report_block_t *rb)) { /* the jitter raw value is kept in stream clock units */ uint32_t jitter = (uint32_t)session->rtp.jittctl.inter_jitter; - session->stats.sent_rtcp_packets ++; + session->stats.sent_rtcp_packets++; session->rtp.jitter_stats.sum_jitter += jitter; - session->rtp.jitter_stats.jitter=jitter; + session->rtp.jitter_stats.jitter = jitter; /* stores the biggest jitter for that session and its date (in millisecond) since Epoch */ - if ( jitter > session->rtp.jitter_stats.max_jitter ) { + if (jitter > session->rtp.jitter_stats.max_jitter) { struct timeval now; - session->rtp.jitter_stats.max_jitter = jitter ; + session->rtp.jitter_stats.max_jitter = jitter; - bctbx_gettimeofday( &now, NULL ); - session->rtp.jitter_stats.max_jitter_ts = ( now.tv_sec * 1000LL ) + ( now.tv_usec / 1000LL ); + bctbx_gettimeofday(&now, NULL); + session->rtp.jitter_stats.max_jitter_ts = (now.tv_sec * 1000LL) + (now.tv_usec / 1000LL); } /* compute mean jitter buffer size */ - session->rtp.jitter_stats.jitter_buffer_size_ms=jitter_control_compute_mean_size(&session->rtp.jittctl); + session->rtp.jitter_stats.jitter_buffer_size_ms = jitter_control_compute_mean_size(&session->rtp.jittctl); } -static size_t rtcp_sr_init(RtpSession *session, uint8_t *buf, size_t size){ - rtcp_sr_t *sr=(rtcp_sr_t*)buf; - int rr=(session->stats.packet_recv>0); - size_t sr_size=sizeof(rtcp_sr_t)-sizeof(report_block_t)+(rr*sizeof(report_block_t)); - if (sizech,session,RTCP_SR,rr,sr_size); - sr->ssrc=htonl(session->snd.ssrc); - sender_info_init(&sr->si,session); +static size_t rtcp_sr_init(RtpSession *session, uint8_t *buf, size_t size) { + rtcp_sr_t *sr = (rtcp_sr_t *)buf; + int rr = (session->stats.packet_recv > 0); + size_t sr_size = sizeof(rtcp_sr_t) - sizeof(report_block_t) + (rr * sizeof(report_block_t)); + if (size < sr_size) return 0; + rtcp_common_header_init(&sr->ch, session, RTCP_SR, rr, sr_size); + sr->ssrc = htonl(session->snd.ssrc); + sender_info_init(&sr->si, session); /*only include a report block if packets were received*/ if (rr) { - report_block_init( &sr->rb[0], session ); - extended_statistics( session, &sr->rb[0] ); + report_block_init(&sr->rb[0], session); + extended_statistics(session, &sr->rb[0]); } return sr_size; } -static size_t rtcp_rr_init(RtpSession *session, uint8_t *buf, size_t size){ - rtcp_rr_t *rr=(rtcp_rr_t*)buf; - if (sizech,session,RTCP_RR,1,sizeof(rtcp_rr_t)); - rr->ssrc=htonl(session->snd.ssrc); - report_block_init(&rr->rb[0],session); - extended_statistics( session, &rr->rb[0] ); +static size_t rtcp_rr_init(RtpSession *session, uint8_t *buf, size_t size) { + rtcp_rr_t *rr = (rtcp_rr_t *)buf; + if (size < sizeof(rtcp_rr_t)) return 0; + rtcp_common_header_init(&rr->ch, session, RTCP_RR, 1, sizeof(rtcp_rr_t)); + rr->ssrc = htonl(session->snd.ssrc); + report_block_init(&rr->rb[0], session); + extended_statistics(session, &rr->rb[0]); return sizeof(rtcp_rr_t); } -static size_t rtcp_app_init(RtpSession *session, uint8_t *buf, uint8_t subtype, const char *name, size_t size){ - rtcp_app_t *app=(rtcp_app_t*)buf; - if (sizech,session,RTCP_APP,subtype,size); - app->ssrc=htonl(session->snd.ssrc); +static size_t rtcp_app_init(RtpSession *session, uint8_t *buf, uint8_t subtype, const char *name, size_t size) { + rtcp_app_t *app = (rtcp_app_t *)buf; + if (size < sizeof(rtcp_app_t)) return 0; + rtcp_common_header_init(&app->ch, session, RTCP_APP, subtype, size); + app->ssrc = htonl(session->snd.ssrc); memset(app->name, 0, sizeof(app->name)); memcpy(app->name, name, sizeof(app->name)); return sizeof(rtcp_app_t); } -static mblk_t * make_rr(RtpSession *session) { +static mblk_t *make_rr(RtpSession *session) { mblk_t *cm = allocb(sizeof(rtcp_sr_t), 0); cm->b_wptr += rtcp_rr_init(session, cm->b_wptr, sizeof(rtcp_rr_t)); return cm; } -static mblk_t * make_sr(RtpSession *session) { +static mblk_t *make_sr(RtpSession *session) { mblk_t *cm = allocb(sizeof(rtcp_sr_t), 0); cm->b_wptr += rtcp_sr_init(session, cm->b_wptr, sizeof(rtcp_sr_t)); return cm; } -static mblk_t * append_sdes(RtpSession *session, mblk_t *m, bool_t full) { +static mblk_t *append_sdes(RtpSession *session, mblk_t *m, bool_t full) { mblk_t *sdes = NULL; if ((full == TRUE) && (session->full_sdes != NULL)) { @@ -418,15 +432,15 @@ static mblk_t * append_sdes(RtpSession *session, mblk_t *m, bool_t full) { return concatb(m, sdes); } -static void notify_sent_rtcp(RtpSession *session, mblk_t *rtcp){ - if (session->eventqs!=NULL){ +static void notify_sent_rtcp(RtpSession *session, mblk_t *rtcp) { + if (session->eventqs != NULL) { OrtpEvent *ev; OrtpEventData *evd; - ev=ortp_event_new(ORTP_EVENT_RTCP_PACKET_EMITTED); - evd=ortp_event_get_data(ev); - evd->packet=dupmsg(rtcp); - msgpullup(evd->packet,-1); - rtp_session_dispatch_event(session,ev); + ev = ortp_event_new(ORTP_EVENT_RTCP_PACKET_EMITTED); + evd = ortp_event_get_data(ev); + evd->packet = dupmsg(rtcp); + msgpullup(evd->packet, -1); + rtp_session_dispatch_event(session, ev); } } @@ -453,10 +467,8 @@ static void append_fb_packets(RtpSession *session, mblk_t *m) { } /* Repeat TMMBR packets until they are acknowledged with a TMMBN unless a TMMBN is being sent. */ - if (rtp_session_avpf_feature_enabled(session, ORTP_AVPF_FEATURE_TMMBR) - && (session->rtcp.tmmbr_info.sent != NULL) - && (session->rtcp.send_algo.tmmbr_scheduled != TRUE) - && (session->rtcp.send_algo.tmmbn_scheduled != TRUE)) { + if (rtp_session_avpf_feature_enabled(session, ORTP_AVPF_FEATURE_TMMBR) && (session->rtcp.tmmbr_info.sent != NULL) && + (session->rtcp.send_algo.tmmbr_scheduled != TRUE) && (session->rtcp.send_algo.tmmbn_scheduled != TRUE)) { concatb(m, copymsg(session->rtcp.tmmbr_info.sent)); } @@ -465,7 +477,7 @@ static void append_fb_packets(RtpSession *session, mblk_t *m) { } static void rtp_session_create_and_send_rtcp_packet(RtpSession *session, bool_t full) { - mblk_t *m=NULL; + mblk_t *m = NULL; bool_t is_sr = FALSE; if (session->rtp.last_rtcp_packet_count < session->stats.packet_sent) { @@ -487,7 +499,7 @@ static void rtp_session_create_and_send_rtcp_packet(RtpSession *session, bool_t } /* Send the compound packet */ notify_sent_rtcp(session, m); - ortp_message("Sending RTCP %s compound message on session [%p].",(is_sr ? "SR" : "RR"), session); + ortp_message("Sending RTCP %s compound message on session [%p].", (is_sr ? "SR" : "RR"), session); rtp_session_rtcp_send(session, m); } } @@ -637,144 +649,155 @@ void rtp_session_rtcp_process_send(RtpSession *session) { rtp_session_run_rtcp_send_scheduler(session); } -void rtp_session_rtcp_process_recv(RtpSession *session){ +void rtp_session_rtcp_process_recv(RtpSession *session) { rtp_session_run_rtcp_send_scheduler(session); } -void rtp_session_send_rtcp_APP(RtpSession *session, uint8_t subtype, const char *name, const uint8_t *data, int datalen){ - mblk_t *h=allocb(sizeof(rtcp_app_t),0); +void rtp_session_send_rtcp_APP( + RtpSession *session, uint8_t subtype, const char *name, const uint8_t *data, int datalen) { + mblk_t *h = allocb(sizeof(rtcp_app_t), 0); mblk_t *d; - h->b_wptr+=rtcp_app_init(session,h->b_wptr,subtype,name,datalen+sizeof(rtcp_app_t)); - d=esballoc((uint8_t*)data,datalen,0,NULL); - d->b_wptr+=datalen; - h->b_cont=d; - rtp_session_rtcp_send(session,h); + h->b_wptr += rtcp_app_init(session, h->b_wptr, subtype, name, datalen + sizeof(rtcp_app_t)); + d = esballoc((uint8_t *)data, datalen, 0, NULL); + d->b_wptr += datalen; + h->b_cont = d; + rtp_session_rtcp_send(session, h); } /** * Sends a RTCP bye packet. *@param session RtpSession *@param reason the reason phrase. -**/ + **/ int rtp_session_bye(RtpSession *session, const char *reason) { - mblk_t *cm; - mblk_t *sdes = NULL; - mblk_t *bye = NULL; - int ret; - - /* Make a BYE packet (will be on the end of the compund packet). */ - bye = rtcp_create_simple_bye_packet(session->snd.ssrc, reason); - - /* SR or RR is determined by the fact whether stream was sent*/ - if (session->stats.packet_sent>0) - { - cm = allocb(sizeof(rtcp_sr_t), 0); - cm->b_wptr += rtcp_sr_init(session,cm->b_wptr, sizeof(rtcp_sr_t)); - /* make a SDES packet */ - sdes = rtp_session_create_rtcp_sdes_packet(session, TRUE); - /* link them */ - concatb(concatb(cm, sdes), bye); - } else if (session->stats.packet_recv>0){ - /* make a RR packet */ - cm = allocb(sizeof(rtcp_rr_t), 0); - cm->b_wptr += rtcp_rr_init(session, cm->b_wptr, sizeof(rtcp_rr_t)); - /* link them */ - cm->b_cont = bye; - }else cm=bye; - - /* Send compound packet. */ - ret = rtp_session_rtcp_send(session, cm); - - return ret; -} - -OrtpLossRateEstimator * ortp_loss_rate_estimator_new(int min_packet_count_interval, uint64_t min_time_ms_interval, RtpSession *session){ - OrtpLossRateEstimator *obj=ortp_malloc(sizeof(OrtpLossRateEstimator)); - ortp_loss_rate_estimator_init(obj,min_packet_count_interval, min_time_ms_interval, session); - return obj; + mblk_t *cm; + mblk_t *sdes = NULL; + mblk_t *bye = NULL; + int ret; + + /* Make a BYE packet (will be on the end of the compund packet). */ + bye = rtcp_create_simple_bye_packet(session->snd.ssrc, reason); + + /* SR or RR is determined by the fact whether stream was sent*/ + if (session->stats.packet_sent > 0) { + cm = allocb(sizeof(rtcp_sr_t), 0); + cm->b_wptr += rtcp_sr_init(session, cm->b_wptr, sizeof(rtcp_sr_t)); + /* make a SDES packet */ + sdes = rtp_session_create_rtcp_sdes_packet(session, TRUE); + /* link them */ + concatb(concatb(cm, sdes), bye); + } else if (session->stats.packet_recv > 0) { + /* make a RR packet */ + cm = allocb(sizeof(rtcp_rr_t), 0); + cm->b_wptr += rtcp_rr_init(session, cm->b_wptr, sizeof(rtcp_rr_t)); + /* link them */ + cm->b_cont = bye; + } else cm = bye; + + /* Send compound packet. */ + ret = rtp_session_rtcp_send(session, cm); + + return ret; } -void ortp_loss_rate_estimator_init(OrtpLossRateEstimator *obj, int min_packet_count_interval, uint64_t min_time_ms_interval, RtpSession *session){ - memset(obj,0,sizeof(*obj)); - obj->min_packet_count_interval=min_packet_count_interval; - obj->last_ext_seq=rtp_session_get_seq_number(session); - obj->last_cum_loss=rtp_session_get_cum_loss(session); - obj->last_packet_sent_count=session->stats.packet_sent; - obj->last_dup_packet_sent_count=session->stats.packet_dup_sent; - obj->min_time_ms_interval=min_time_ms_interval; - obj->last_estimate_time_ms=(uint64_t)-1; +OrtpLossRateEstimator * +ortp_loss_rate_estimator_new(int min_packet_count_interval, uint64_t min_time_ms_interval, RtpSession *session) { + OrtpLossRateEstimator *obj = ortp_malloc(sizeof(OrtpLossRateEstimator)); + ortp_loss_rate_estimator_init(obj, min_packet_count_interval, min_time_ms_interval, session); + return obj; } -bool_t ortp_loss_rate_estimator_process_report_block(OrtpLossRateEstimator *obj, const RtpSession *session, const report_block_t *rb){ - int32_t cum_loss=report_block_get_cum_packet_lost(rb); - int32_t extseq=report_block_get_high_ext_seq(rb); - //int32_t diff_unique_outgoing=(int32_t)(session->stats.packet_sent-obj->last_packet_sent_count); - //int32_t diff_total_outgoing=diff_unique_outgoing+(int32_t)(session->stats.packet_dup_sent-obj->last_dup_packet_sent_count); +void ortp_loss_rate_estimator_init(OrtpLossRateEstimator *obj, + int min_packet_count_interval, + uint64_t min_time_ms_interval, + RtpSession *session) { + memset(obj, 0, sizeof(*obj)); + obj->min_packet_count_interval = min_packet_count_interval; + obj->last_ext_seq = rtp_session_get_seq_number(session); + obj->last_cum_loss = rtp_session_get_cum_loss(session); + obj->last_packet_sent_count = session->stats.packet_sent; + obj->last_dup_packet_sent_count = session->stats.packet_dup_sent; + obj->min_time_ms_interval = min_time_ms_interval; + obj->last_estimate_time_ms = (uint64_t)-1; +} + +bool_t ortp_loss_rate_estimator_process_report_block(OrtpLossRateEstimator *obj, + const RtpSession *session, + const report_block_t *rb) { + int32_t cum_loss = report_block_get_cum_packet_lost(rb); + int32_t extseq = report_block_get_high_ext_seq(rb); + // int32_t diff_unique_outgoing=(int32_t)(session->stats.packet_sent-obj->last_packet_sent_count); + // int32_t + // diff_total_outgoing=diff_unique_outgoing+(int32_t)(session->stats.packet_dup_sent-obj->last_dup_packet_sent_count); int32_t diff; uint64_t curtime; - bool_t got_value=FALSE; + bool_t got_value = FALSE; - if (obj->last_ext_seq==-1 || obj->last_estimate_time_ms==(uint64_t)-1){ + if (obj->last_ext_seq == -1 || obj->last_estimate_time_ms == (uint64_t)-1) { /*first report cannot be considered, since we don't know the interval it covers*/ - obj->last_ext_seq=extseq; - obj->last_cum_loss=cum_loss; - obj->last_estimate_time_ms=bctbx_get_cur_time_ms(); + obj->last_ext_seq = extseq; + obj->last_cum_loss = cum_loss; + obj->last_estimate_time_ms = bctbx_get_cur_time_ms(); return FALSE; } - diff=extseq-obj->last_ext_seq; - curtime=bctbx_get_cur_time_ms(); - if (diff<0 || diff>obj->min_packet_count_interval * 100){ - if (extseq==0){ + diff = extseq - obj->last_ext_seq; + curtime = bctbx_get_cur_time_ms(); + if (diff < 0 || diff > obj->min_packet_count_interval * 100) { + if (extseq == 0) { /*when extseq reset to 0, it probably means that rtp_session_sync was called but since OrtplossRateEstimator is not reset, first RTCP packet received will be detected as discontinuity instead of init RTCP packet. Avoid logging in such case.*/ - ortp_message("ortp_loss_rate_estimator_process %p: Suspected RTP session restart, sequence numbering from %d to %d.", obj, obj->last_ext_seq, extseq); - }else{ - ortp_warning("ortp_loss_rate_estimator_process %p: Suspected discontinuity in sequence numbering from %d to %d.", obj, obj->last_ext_seq, extseq); + ortp_message( + "ortp_loss_rate_estimator_process %p: Suspected RTP session restart, sequence numbering from %d to %d.", + obj, obj->last_ext_seq, extseq); + } else { + ortp_warning( + "ortp_loss_rate_estimator_process %p: Suspected discontinuity in sequence numbering from %d to %d.", + obj, obj->last_ext_seq, extseq); } - obj->last_ext_seq=extseq; - obj->last_cum_loss=cum_loss; - obj->last_packet_sent_count=session->stats.packet_sent; - obj->last_dup_packet_sent_count=session->stats.packet_dup_sent; - }else if (diff>obj->min_packet_count_interval && curtime-obj->last_estimate_time_ms>=obj->min_time_ms_interval){ + obj->last_ext_seq = extseq; + obj->last_cum_loss = cum_loss; + obj->last_packet_sent_count = session->stats.packet_sent; + obj->last_dup_packet_sent_count = session->stats.packet_dup_sent; + } else if (diff > obj->min_packet_count_interval && + curtime - obj->last_estimate_time_ms >= obj->min_time_ms_interval) { /*we have sufficient interval*/ - int32_t new_losses=cum_loss-obj->last_cum_loss; + int32_t new_losses = cum_loss - obj->last_cum_loss; -#if 0 /*SM: the following code try to takes into account sent duplicates - however by doing this it creates a bias in the loss rate computation - that can sometimes result in a negative loss rate, even if there is no duplicate. - Since the rate control doesn't use duplicates anymore, there is no good reason to take this into account. - */ +#if 0 /*SM: the following code try to takes into account sent duplicates - however by doing this it creates a bias in \ + the loss rate computation that can sometimes result in a negative loss rate, even if there is no duplicate. \ + Since the rate control doesn't use duplicates anymore, there is no good reason to take this into account. \ + */ /*if we are using duplicates, they will not be visible in 'diff' variable. But since we are the emitter, we can retrieve the total count of packet we sent and use this value to compute the loss rate instead.*/ obj->loss_rate = 100.f * (1.f - MAX(0, (diff_unique_outgoing - new_losses) * 1.f / diff_total_outgoing)); #endif - obj->loss_rate = 100.f * (float) new_losses / (float)( extseq - obj->last_ext_seq); + obj->loss_rate = 100.f * (float)new_losses / (float)(extseq - obj->last_ext_seq); /*update last values with current*/ - got_value=TRUE; - obj->last_estimate_time_ms=curtime; + got_value = TRUE; + obj->last_estimate_time_ms = curtime; - if (obj->loss_rate>100.f){ + if (obj->loss_rate > 100.f) { obj->loss_rate = 100.f; ortp_error("ortp_loss_rate_estimator_process %p: Loss rate MUST NOT be greater than 100%%", obj); - }else if(obj->loss_rate < 0){ + } else if (obj->loss_rate < 0) { obj->loss_rate = 0; ortp_error("ortp_loss_rate_estimator_process %p: Loss rate MUST NOT be negative", obj); } - obj->last_ext_seq=extseq; - obj->last_cum_loss=cum_loss; - obj->last_packet_sent_count=session->stats.packet_sent; - obj->last_dup_packet_sent_count=session->stats.packet_dup_sent; + obj->last_ext_seq = extseq; + obj->last_cum_loss = cum_loss; + obj->last_packet_sent_count = session->stats.packet_sent; + obj->last_dup_packet_sent_count = session->stats.packet_dup_sent; } return got_value; - } -float ortp_loss_rate_estimator_get_value(OrtpLossRateEstimator *obj){ +float ortp_loss_rate_estimator_get_value(OrtpLossRateEstimator *obj) { return obj->loss_rate; } -void ortp_loss_rate_estimator_destroy(OrtpLossRateEstimator *obj){ +void ortp_loss_rate_estimator_destroy(OrtpLossRateEstimator *obj) { ortp_free(obj); } diff --git a/src/rtcp_fb.c b/src/rtcp_fb.c index ed484014..b0cf7627 100644 --- a/src/rtcp_fb.c +++ b/src/rtcp_fb.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,13 +18,11 @@ * along with this program. If not, see . */ - #include "ortp/ortp.h" -#include "ortp/rtpsession.h" #include "ortp/rtcp.h" +#include "ortp/rtpsession.h" #include "rtpsession_priv.h" - static void rtp_session_add_fb_packet_to_send(RtpSession *session, mblk_t *m) { if (session->rtcp.send_algo.fb_packets == NULL) { session->rtcp.send_algo.fb_packets = m; @@ -42,11 +40,9 @@ static void rtp_session_add_fb_packet_to_send(RtpSession *session, mblk_t *m) { static bool_t is_fb_packet_to_be_sent_immediately(RtpSession *session) { uint64_t t0; - if (rtp_session_has_fb_packets_to_send(session) == TRUE) - return FALSE; + if (rtp_session_has_fb_packets_to_send(session) == TRUE) return FALSE; t0 = bctbx_get_cur_time_ms(); - if (t0 > session->rtcp.send_algo.tn) - return FALSE; + if (t0 > session->rtcp.send_algo.tn) return FALSE; if (session->rtcp.send_algo.allow_early == FALSE) { if ((session->rtcp.send_algo.tn - t0) >= session->rtcp.send_algo.T_max_fb_delay) { /* Discard message as it is considered that it will not be useful to the sender @@ -59,9 +55,9 @@ static bool_t is_fb_packet_to_be_sent_immediately(RtpSession *session) { return TRUE; } -static mblk_t * make_rtcp_fb_pli(RtpSession *session) { +static mblk_t *make_rtcp_fb_pli(RtpSession *session) { int size = sizeof(rtcp_common_header_t) + sizeof(rtcp_fb_header_t); - mblk_t *h= allocb(size, 0); + mblk_t *h = allocb(size, 0); rtcp_common_header_t *ch; rtcp_fb_header_t *fbh; @@ -79,13 +75,13 @@ static mblk_t * make_rtcp_fb_pli(RtpSession *session) { return h; } -static mblk_t * make_rtcp_fb_fir(RtpSession *session) { +static mblk_t *make_rtcp_fb_fir(RtpSession *session) { int size = sizeof(rtcp_common_header_t) + sizeof(rtcp_fb_header_t) + sizeof(rtcp_fb_fir_fci_t); mblk_t *h = allocb(size, 0); rtcp_common_header_t *ch; rtcp_fb_header_t *fbh; rtcp_fb_fir_fci_t *fci1; - + /* Fill FIR */ ch = (rtcp_common_header_t *)h->b_wptr; h->b_wptr += sizeof(rtcp_common_header_t); @@ -93,7 +89,7 @@ static mblk_t * make_rtcp_fb_fir(RtpSession *session) { h->b_wptr += sizeof(rtcp_fb_header_t); fci1 = (rtcp_fb_fir_fci_t *)h->b_wptr; h->b_wptr += sizeof(rtcp_fb_fir_fci_t); - + /* * See https://datatracker.ietf.org/doc/rfc4585/ section 6.1 * SSRC of packet sender: 32 bits @@ -103,28 +99,28 @@ static mblk_t * make_rtcp_fb_fir(RtpSession *session) { * The synchronization source identifier of the media source that * this piece of feedback information is related to. */ - + fbh->packet_sender_ssrc = htonl(rtp_session_get_send_ssrc(session)); fbh->media_source_ssrc = htonl(rtp_session_get_recv_ssrc(session)); - + /* * https://www.rfc-editor.org/rfc/rfc5104.html#section-4.3.1.1 * SSRC (32 bits): The SSRC value of the media sender that is * requested to send a decoder refresh point. */ - + fci1->ssrc = htonl(rtp_session_get_recv_ssrc(session)); fci1->seq_nr = session->rtcp.rtcp_fb_fir_seq_nr; fci1->pad1 = 0; fci1->pad2 = 0; - + /* Fill common header */ rtcp_common_header_init(ch, session, RTCP_PSFB, RTCP_PSFB_FIR, msgdsize(h)); return h; } -static mblk_t * make_rtcp_fb_sli(RtpSession *session, uint16_t first, uint16_t number, uint8_t picture_id) { +static mblk_t *make_rtcp_fb_sli(RtpSession *session, uint16_t first, uint16_t number, uint8_t picture_id) { int size = sizeof(rtcp_common_header_t) + sizeof(rtcp_fb_header_t) + sizeof(rtcp_fb_sli_fci_t); mblk_t *h = allocb(size, 0); rtcp_common_header_t *ch; @@ -150,7 +146,7 @@ static mblk_t * make_rtcp_fb_sli(RtpSession *session, uint16_t first, uint16_t n return h; } -static mblk_t * make_rtcp_fb_rpsi(RtpSession *session, uint8_t *bit_string, uint16_t bit_string_len) { +static mblk_t *make_rtcp_fb_rpsi(RtpSession *session, uint8_t *bit_string, uint16_t bit_string_len) { uint16_t bit_string_len_in_bytes; int additional_bytes; int size; @@ -195,7 +191,7 @@ static mblk_t * make_rtcp_fb_rpsi(RtpSession *session, uint8_t *bit_string, uint return h; } -static mblk_t * make_rtcp_fb_generic_nack(RtpSession *session, uint16_t pid, uint16_t blp) { +static mblk_t *make_rtcp_fb_generic_nack(RtpSession *session, uint16_t pid, uint16_t blp) { int size = sizeof(rtcp_common_header_t) + sizeof(rtcp_fb_header_t) + sizeof(rtcp_fb_generic_nack_fci_t); mblk_t *h = allocb(size, 0); rtcp_common_header_t *ch; @@ -219,7 +215,7 @@ static mblk_t * make_rtcp_fb_generic_nack(RtpSession *session, uint16_t pid, uin return h; } -static mblk_t * make_rtcp_fb_tmmbr(RtpSession *session, uint64_t mxtbr, uint16_t measured_overhead) { +static mblk_t *make_rtcp_fb_tmmbr(RtpSession *session, uint64_t mxtbr, uint16_t measured_overhead) { int size = sizeof(rtcp_common_header_t) + sizeof(rtcp_fb_header_t) + sizeof(rtcp_fb_tmmbr_fci_t); mblk_t *h = allocb(size, 0); rtcp_common_header_t *ch; @@ -259,7 +255,7 @@ static mblk_t * make_rtcp_fb_tmmbr(RtpSession *session, uint64_t mxtbr, uint16_t return h; } -static mblk_t * make_rtcp_fb_tmmbn(RtpSession *session, uint32_t ssrc) { +static mblk_t *make_rtcp_fb_tmmbn(RtpSession *session, uint32_t ssrc) { int size = sizeof(rtcp_common_header_t) + sizeof(rtcp_fb_header_t) + sizeof(rtcp_fb_tmmbr_fci_t); mblk_t *h = allocb(size, 0); rtcp_common_header_t *ch; @@ -310,7 +306,8 @@ bool_t rtp_session_rtcp_rtpfb_scheduled(RtpSession *session, rtcp_rtpfb_type_t t void rtp_session_send_rtcp_fb_generic_nack(RtpSession *session, uint16_t pid, uint16_t blp) { mblk_t *m; - if ((rtp_session_avpf_enabled(session) == TRUE) && (rtp_session_avpf_feature_enabled(session, ORTP_AVPF_FEATURE_GENERIC_NACK) == TRUE)) { + if ((rtp_session_avpf_enabled(session) == TRUE) && + (rtp_session_avpf_feature_enabled(session, ORTP_AVPF_FEATURE_GENERIC_NACK) == TRUE)) { m = make_rtcp_fb_generic_nack(session, pid, blp); rtp_session_add_fb_packet_to_send(session, m); rtp_session_send_fb_rtcp_packet_and_reschedule(session); @@ -319,7 +316,8 @@ void rtp_session_send_rtcp_fb_generic_nack(RtpSession *session, uint16_t pid, ui void rtp_session_send_rtcp_fb_pli(RtpSession *session) { mblk_t *m; - if ((rtp_session_avpf_enabled(session) == TRUE) && (rtp_session_avpf_payload_type_feature_enabled(session, PAYLOAD_TYPE_AVPF_PLI) == TRUE)) { + if ((rtp_session_avpf_enabled(session) == TRUE) && + (rtp_session_avpf_payload_type_feature_enabled(session, PAYLOAD_TYPE_AVPF_PLI) == TRUE)) { bool_t can_send_immediately = FALSE; if (rtp_session_rtcp_psfb_scheduled(session, RTCP_PSFB_PLI) != TRUE) { m = make_rtcp_fb_pli(session); @@ -334,7 +332,8 @@ void rtp_session_send_rtcp_fb_pli(RtpSession *session) { void rtp_session_send_rtcp_fb_fir(RtpSession *session) { mblk_t *m; - if ((rtp_session_avpf_enabled(session) == TRUE) && (rtp_session_avpf_payload_type_feature_enabled(session, PAYLOAD_TYPE_AVPF_FIR) == TRUE)) { + if ((rtp_session_avpf_enabled(session) == TRUE) && + (rtp_session_avpf_payload_type_feature_enabled(session, PAYLOAD_TYPE_AVPF_FIR) == TRUE)) { bool_t can_send_immediately = FALSE; if (rtp_session_rtcp_psfb_scheduled(session, RTCP_PSFB_FIR) != TRUE) { m = make_rtcp_fb_fir(session); @@ -351,10 +350,11 @@ void rtp_session_send_rtcp_fb_sli(RtpSession *session, uint16_t first, uint16_t mblk_t *m; if (rtp_session_avpf_enabled(session) == TRUE) { /* Only send SLI if SLI and RPSI features have been enabled. SLI without RPSI is not really useful. */ - if ((rtp_session_avpf_payload_type_feature_enabled(session, PAYLOAD_TYPE_AVPF_SLI) == TRUE) - && (rtp_session_avpf_payload_type_feature_enabled(session, PAYLOAD_TYPE_AVPF_RPSI) == TRUE)) { - /* we check first if the packet can be sent immediately. is_fb_packet_to_be_sent_immediately() will return FALSE - * if there are queued feedback packets, which we are going to do in rtp_session_add_fb_packet_to_send() just after. + if ((rtp_session_avpf_payload_type_feature_enabled(session, PAYLOAD_TYPE_AVPF_SLI) == TRUE) && + (rtp_session_avpf_payload_type_feature_enabled(session, PAYLOAD_TYPE_AVPF_RPSI) == TRUE)) { + /* we check first if the packet can be sent immediately. is_fb_packet_to_be_sent_immediately() will return + * FALSE if there are queued feedback packets, which we are going to do in + * rtp_session_add_fb_packet_to_send() just after. */ bool_t can_send_immediately = is_fb_packet_to_be_sent_immediately(session); m = make_rtcp_fb_sli(session, first, number, picture_id); @@ -371,7 +371,8 @@ void rtp_session_send_rtcp_fb_sli(RtpSession *session, uint16_t first, uint16_t void rtp_session_send_rtcp_fb_rpsi(RtpSession *session, uint8_t *bit_string, uint16_t bit_string_len) { mblk_t *m; - if ((rtp_session_avpf_enabled(session) == TRUE) && (rtp_session_avpf_payload_type_feature_enabled(session, PAYLOAD_TYPE_AVPF_RPSI) == TRUE)) { + if ((rtp_session_avpf_enabled(session) == TRUE) && + (rtp_session_avpf_payload_type_feature_enabled(session, PAYLOAD_TYPE_AVPF_RPSI) == TRUE)) { bool_t can_send_immediately; m = make_rtcp_fb_rpsi(session, bit_string, bit_string_len); can_send_immediately = is_fb_packet_to_be_sent_immediately(session); @@ -384,8 +385,10 @@ void rtp_session_send_rtcp_fb_rpsi(RtpSession *session, uint8_t *bit_string, uin void rtp_session_send_rtcp_fb_tmmbr(RtpSession *session, uint64_t mxtbr) { mblk_t *m; - if ((rtp_session_avpf_enabled(session) == TRUE) && (rtp_session_avpf_feature_enabled(session, ORTP_AVPF_FEATURE_TMMBR) == TRUE)) { - if ((rtp_session_rtcp_rtpfb_scheduled(session, RTCP_RTPFB_TMMBR) != TRUE) && (rtp_session_get_recv_ssrc(session) != 0)) { + if ((rtp_session_avpf_enabled(session) == TRUE) && + (rtp_session_avpf_feature_enabled(session, ORTP_AVPF_FEATURE_TMMBR) == TRUE)) { + if ((rtp_session_rtcp_rtpfb_scheduled(session, RTCP_RTPFB_TMMBR) != TRUE) && + (rtp_session_get_recv_ssrc(session) != 0)) { uint16_t overhead = (session->rtp.gs.sockfamily == AF_INET6) ? IP6_UDP_OVERHEAD : IP_UDP_OVERHEAD; m = make_rtcp_fb_tmmbr(session, mxtbr, overhead); rtp_session_add_fb_packet_to_send(session, m); @@ -397,7 +400,8 @@ void rtp_session_send_rtcp_fb_tmmbr(RtpSession *session, uint64_t mxtbr) { void rtp_session_send_rtcp_fb_tmmbn(RtpSession *session, uint32_t ssrc) { mblk_t *m; - if ((rtp_session_avpf_enabled(session) == TRUE) && (rtp_session_avpf_feature_enabled(session, ORTP_AVPF_FEATURE_TMMBR) == TRUE)) { + if ((rtp_session_avpf_enabled(session) == TRUE) && + (rtp_session_avpf_feature_enabled(session, ORTP_AVPF_FEATURE_TMMBR) == TRUE)) { m = make_rtcp_fb_tmmbn(session, ssrc); if (m) { rtp_session_add_fb_packet_to_send(session, m); @@ -409,7 +413,7 @@ void rtp_session_send_rtcp_fb_tmmbn(RtpSession *session, uint32_t ssrc) { bool_t rtp_session_avpf_enabled(RtpSession *session) { PayloadType *pt = rtp_profile_get_payload(session->snd.profile, session->snd.pt); - if (!pt){ + if (!pt) { ortp_warning("rtp_session_avpf_enabled(): payload type not set, unreliable result returned."); } return pt && (payload_type_get_flags(pt) & PAYLOAD_TYPE_RTCP_FEEDBACK_ENABLED); @@ -441,7 +445,7 @@ uint16_t rtp_session_get_avpf_rr_interval(RtpSession *session) { PayloadType *pt = rtp_profile_get_payload(session->rcv.profile, session->rcv.pt); PayloadTypeAvpfParams params; if (!pt) return RTCP_DEFAULT_REPORT_INTERVAL; - params=payload_type_get_avpf_params(pt); + params = payload_type_get_avpf_params(pt); return (uint16_t)params.trr_interval; } diff --git a/src/rtcp_xr.c b/src/rtcp_xr.c index 762bcf18..d3f5e975 100644 --- a/src/rtcp_xr.c +++ b/src/rtcp_xr.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,18 +18,19 @@ * along with this program. If not, see . */ +#include + #ifdef HAVE_CONFIG_H #include "ortp-config.h" #endif #include #include "ortp/ortp.h" -#include "ortp/rtpsession.h" #include "ortp/rtcp.h" +#include "ortp/rtpsession.h" #include "rtpsession_priv.h" #include "utils.h" - static uint8_t calc_rate(double d1, double d2) { double rate = (d1 / d2) * 256; uint32_t int_rate = (uint32_t)rate; @@ -44,7 +45,7 @@ static int rtcp_xr_header_init(uint8_t *buf, RtpSession *session, int bytes_len) return sizeof(rtcp_xr_header_t); } -static int rtcp_xr_rcvr_rtt_init(uint8_t *buf, RtpSession *session) { +static int rtcp_xr_rcvr_rtt_init(uint8_t *buf, BCTBX_UNUSED(RtpSession *session)) { struct timeval tv; uint64_t ntp; rtcp_xr_rcvr_rtt_report_block_t *block = (rtcp_xr_rcvr_rtt_report_block_t *)buf; @@ -72,9 +73,10 @@ static int rtcp_xr_dlrr_init(uint8_t *buf, RtpSession *session) { struct timeval now; double delay; bctbx_gettimeofday(&now, NULL); - delay = ((now.tv_sec - session->rtcp_xr_stats.last_rcvr_rtt_time.tv_sec) - + ((now.tv_usec - session->rtcp_xr_stats.last_rcvr_rtt_time.tv_usec) * 1e-6)) * 65536; - dlrr = (uint32_t) delay; + delay = ((now.tv_sec - session->rtcp_xr_stats.last_rcvr_rtt_time.tv_sec) + + ((now.tv_usec - session->rtcp_xr_stats.last_rcvr_rtt_time.tv_usec) * 1e-6)) * + 65536; + dlrr = (uint32_t)delay; } block->content[0].dlrr = htonl(dlrr); return sizeof(rtcp_xr_dlrr_report_block_t); @@ -93,7 +95,8 @@ static int rtcp_xr_stat_summary_init(uint8_t *buf, RtpSession *session) { uint32_t no_duplicate_received = session->rtcp_xr_stats.rcv_since_last_stat_summary - dup_packets; expected_packets = last_rcv_seq - session->rtcp_xr_stats.rcv_seq_at_last_stat_summary; lost_packets = (expected_packets > session->rtcp_xr_stats.rcv_since_last_stat_summary) - ? (expected_packets - no_duplicate_received) : 0; + ? (expected_packets - no_duplicate_received) + : 0; } block->bh.bt = RTCP_XR_STAT_SUMMARY; @@ -104,28 +107,33 @@ static int rtcp_xr_stat_summary_init(uint8_t *buf, RtpSession *session) { block->end_seq = htons(last_rcv_seq + 1); block->lost_packets = htonl(lost_packets); block->dup_packets = htonl(dup_packets); - if ((flags & OrtpRtcpXrStatSummaryJitt) - && (session->rtcp_xr_stats.rcv_since_last_stat_summary > 0)) { + if ((flags & OrtpRtcpXrStatSummaryJitt) && (session->rtcp_xr_stats.rcv_since_last_stat_summary > 0)) { block->min_jitter = htonl(session->rtcp_xr_stats.min_jitter_since_last_stat_summary); block->max_jitter = htonl(session->rtcp_xr_stats.max_jitter_since_last_stat_summary); block->mean_jitter = htonl((session->rtcp_xr_stats.rcv_since_last_stat_summary > 1) - ? (uint32_t)session->rtcp_xr_stats.newm_jitter_since_last_stat_summary : 0); + ? (uint32_t)session->rtcp_xr_stats.newm_jitter_since_last_stat_summary + : 0); block->dev_jitter = htonl((session->rtcp_xr_stats.rcv_since_last_stat_summary > 2) - ? (uint32_t)sqrt(session->rtcp_xr_stats.news_jitter_since_last_stat_summary / (session->rtcp_xr_stats.rcv_since_last_stat_summary - 2)) : 0); + ? (uint32_t)sqrt(session->rtcp_xr_stats.news_jitter_since_last_stat_summary / + (session->rtcp_xr_stats.rcv_since_last_stat_summary - 2)) + : 0); } else { block->min_jitter = htonl(0); block->max_jitter = htonl(0); block->mean_jitter = htonl(0); block->dev_jitter = htonl(0); } - if ((flags & (OrtpRtcpXrStatSummaryTTL | OrtpRtcpXrStatSummaryHL)) - && (session->rtcp_xr_stats.rcv_since_last_stat_summary > 0)) { + if ((flags & (OrtpRtcpXrStatSummaryTTL | OrtpRtcpXrStatSummaryHL)) && + (session->rtcp_xr_stats.rcv_since_last_stat_summary > 0)) { block->min_ttl_or_hl = session->rtcp_xr_stats.min_ttl_or_hl_since_last_stat_summary; block->max_ttl_or_hl = session->rtcp_xr_stats.max_ttl_or_hl_since_last_stat_summary; block->mean_ttl_or_hl = (session->rtcp_xr_stats.rcv_since_last_stat_summary > 0) - ? (uint8_t)session->rtcp_xr_stats.newm_ttl_or_hl_since_last_stat_summary : 0; + ? (uint8_t)session->rtcp_xr_stats.newm_ttl_or_hl_since_last_stat_summary + : 0; block->dev_ttl_or_hl = (session->rtcp_xr_stats.rcv_since_last_stat_summary > 1) - ? (uint8_t)sqrt(session->rtcp_xr_stats.news_ttl_or_hl_since_last_stat_summary / (session->rtcp_xr_stats.rcv_since_last_stat_summary - 1)) : 0; + ? (uint8_t)sqrt(session->rtcp_xr_stats.news_ttl_or_hl_since_last_stat_summary / + (session->rtcp_xr_stats.rcv_since_last_stat_summary - 1)) + : 0; } else { block->min_ttl_or_hl = 0; block->max_ttl_or_hl = 0; @@ -212,12 +220,14 @@ static int rtcp_xr_voip_metrics_init(uint8_t *buf, RtpSession *session) { // TODO: fill end_system_delay block->end_system_delay = htons(0); if (session->rtcp.xr_media_callbacks.signal_level != NULL) { - block->signal_level = session->rtcp.xr_media_callbacks.signal_level(session->rtcp.xr_media_callbacks.userdata); + block->signal_level = + session->rtcp.xr_media_callbacks.signal_level(session->rtcp.xr_media_callbacks.userdata); } else { block->signal_level = ORTP_RTCP_XR_UNAVAILABLE_PARAMETER; } if (session->rtcp.xr_media_callbacks.noise_level != NULL) { - block->noise_level = session->rtcp.xr_media_callbacks.noise_level(session->rtcp.xr_media_callbacks.userdata); + block->noise_level = + session->rtcp.xr_media_callbacks.noise_level(session->rtcp.xr_media_callbacks.userdata); } else { block->noise_level = ORTP_RTCP_XR_UNAVAILABLE_PARAMETER; } @@ -260,8 +270,7 @@ static int rtcp_xr_voip_metrics_init(uint8_t *buf, RtpSession *session) { return sizeof(rtcp_xr_voip_metrics_report_block_t); } - -mblk_t * make_xr_rcvr_rtt(RtpSession *session) { +mblk_t *make_xr_rcvr_rtt(RtpSession *session) { int size = sizeof(rtcp_xr_header_t) + sizeof(rtcp_xr_rcvr_rtt_report_block_t); mblk_t *h = allocb(size, 0); h->b_wptr += rtcp_xr_header_init(h->b_wptr, session, size); @@ -269,7 +278,7 @@ mblk_t * make_xr_rcvr_rtt(RtpSession *session) { return h; } -mblk_t * make_xr_dlrr(RtpSession *session) { +mblk_t *make_xr_dlrr(RtpSession *session) { int size = sizeof(rtcp_xr_header_t) + sizeof(rtcp_xr_dlrr_report_block_t); mblk_t *h = allocb(size, 0); h->b_wptr += rtcp_xr_header_init(h->b_wptr, session, size); @@ -277,7 +286,7 @@ mblk_t * make_xr_dlrr(RtpSession *session) { return h; } -mblk_t * make_xr_stat_summary(RtpSession *session) { +mblk_t *make_xr_stat_summary(RtpSession *session) { int size = sizeof(rtcp_xr_header_t) + sizeof(rtcp_xr_stat_summary_report_block_t); mblk_t *h = allocb(size, 0); h->b_wptr += rtcp_xr_header_init(h->b_wptr, session, size); @@ -285,7 +294,7 @@ mblk_t * make_xr_stat_summary(RtpSession *session) { return h; } -mblk_t * make_xr_voip_metrics(RtpSession *session) { +mblk_t *make_xr_voip_metrics(RtpSession *session) { int size = sizeof(rtcp_xr_header_t) + sizeof(rtcp_xr_voip_metrics_report_block_t); mblk_t *h = allocb(size, 0); h->b_wptr += rtcp_xr_header_init(h->b_wptr, session, size); diff --git a/src/rtcpparse.c b/src/rtcpparse.c index 7680ef0c..e0784428 100644 --- a/src/rtcpparse.c +++ b/src/rtcpparse.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -21,51 +21,51 @@ #ifdef HAVE_CONFIG_H #include "ortp-config.h" #endif -#include "ortp/str_utils.h" #include "ortp/ortp.h" +#include "ortp/str_utils.h" #include "utils.h" size_t rtcp_get_size(const mblk_t *m) { - const rtcp_common_header_t *ch=rtcp_get_common_header(m); - if (ch==NULL) return 0; - return (1+rtcp_common_header_get_length(ch))*4; + const rtcp_common_header_t *ch = rtcp_get_common_header(m); + if (ch == NULL) return 0; + return (1 + rtcp_common_header_get_length(ch)) * 4; } /*in case of compound packet, set read pointer of m to the beginning of the next RTCP packet */ -bool_t rtcp_next_packet(mblk_t *m){ - size_t nextlen=rtcp_get_size(m); - if ((nextlen > 0) && (m->b_rptr + nextlen < m->b_wptr)){ - m->b_rptr+=nextlen; +bool_t rtcp_next_packet(mblk_t *m) { + size_t nextlen = rtcp_get_size(m); + if ((nextlen > 0) && (m->b_rptr + nextlen < m->b_wptr)) { + m->b_rptr += nextlen; return TRUE; } return FALSE; } -void rtcp_rewind(mblk_t *m){ - m->b_rptr=m->b_datap->db_base; +void rtcp_rewind(mblk_t *m) { + m->b_rptr = m->b_datap->db_base; } /* get common header; this function will also check the sanity of the packet*/ -const rtcp_common_header_t * rtcp_get_common_header(const mblk_t *m){ - size_t size=msgdsize(m); +const rtcp_common_header_t *rtcp_get_common_header(const mblk_t *m) { + size_t size = msgdsize(m); rtcp_common_header_t *ch; - if (sizeb_cont!=NULL){ + if (m->b_cont != NULL) { ortp_fatal("RTCP parser does not work on fragmented mblk_t. Use msgpullup() before to re-assemble the packet."); return NULL; } - ch=(rtcp_common_header_t*)m->b_rptr; + ch = (rtcp_common_header_t *)m->b_rptr; return ch; } -bool_t rtcp_is_SR(const mblk_t *m){ - const rtcp_common_header_t *ch=rtcp_get_common_header(m); - if (ch!=NULL && rtcp_common_header_get_packet_type(ch)==RTCP_SR){ - if (msgdsize(m)<(sizeof(rtcp_sr_t)-sizeof(report_block_t))){ +bool_t rtcp_is_SR(const mblk_t *m) { + const rtcp_common_header_t *ch = rtcp_get_common_header(m); + if (ch != NULL && rtcp_common_header_get_packet_type(ch) == RTCP_SR) { + if (msgdsize(m) < (sizeof(rtcp_sr_t) - sizeof(report_block_t))) { ortp_warning("Too short RTCP SR packet."); return FALSE; } @@ -75,35 +75,35 @@ bool_t rtcp_is_SR(const mblk_t *m){ } /*Sender Report accessors */ -uint32_t rtcp_SR_get_ssrc(const mblk_t *m){ - rtcp_sr_t *sr=(rtcp_sr_t*)m->b_rptr; +uint32_t rtcp_SR_get_ssrc(const mblk_t *m) { + rtcp_sr_t *sr = (rtcp_sr_t *)m->b_rptr; return ntohl(sr->ssrc); } -const sender_info_t * rtcp_SR_get_sender_info(const mblk_t *m){ - rtcp_sr_t *sr=(rtcp_sr_t*)m->b_rptr; +const sender_info_t *rtcp_SR_get_sender_info(const mblk_t *m) { + rtcp_sr_t *sr = (rtcp_sr_t *)m->b_rptr; return &sr->si; } -const report_block_t * rtcp_SR_get_report_block(const mblk_t *m, int idx){ - rtcp_sr_t *sr=(rtcp_sr_t*)m->b_rptr; - report_block_t *rb=&sr->rb[idx]; - size_t size=rtcp_get_size(m); - if ( ( (uint8_t*)rb)+sizeof(report_block_t) <= m->b_rptr + size ) { +const report_block_t *rtcp_SR_get_report_block(const mblk_t *m, int idx) { + rtcp_sr_t *sr = (rtcp_sr_t *)m->b_rptr; + report_block_t *rb = &sr->rb[idx]; + size_t size = rtcp_get_size(m); + if (((uint8_t *)rb) + sizeof(report_block_t) <= m->b_rptr + size) { return rb; - }else{ - if (idxch)){ - ortp_warning("RTCP packet should include a report_block_t at pos %i but has no space for it.",idx); + } else { + if (idx < rtcp_common_header_get_rc(&sr->ch)) { + ortp_warning("RTCP packet should include a report_block_t at pos %i but has no space for it.", idx); } } return NULL; } /*Receiver report accessors*/ -bool_t rtcp_is_RR(const mblk_t *m){ - const rtcp_common_header_t *ch=rtcp_get_common_header(m); - if (ch!=NULL && rtcp_common_header_get_packet_type(ch)==RTCP_RR){ - if (msgdsize(m)b_rptr; +uint32_t rtcp_RR_get_ssrc(const mblk_t *m) { + rtcp_rr_t *rr = (rtcp_rr_t *)m->b_rptr; return ntohl(rr->ssrc); } -const report_block_t * rtcp_RR_get_report_block(const mblk_t *m,int idx){ - rtcp_rr_t *rr=(rtcp_rr_t*)m->b_rptr; - report_block_t *rb=&rr->rb[idx]; - size_t size=rtcp_get_size(m); - if ( ( (uint8_t*)rb)+sizeof(report_block_t) <= (m->b_rptr + size ) ){ +const report_block_t *rtcp_RR_get_report_block(const mblk_t *m, int idx) { + rtcp_rr_t *rr = (rtcp_rr_t *)m->b_rptr; + report_block_t *rb = &rr->rb[idx]; + size_t size = rtcp_get_size(m); + if (((uint8_t *)rb) + sizeof(report_block_t) <= (m->b_rptr + size)) { return rb; - }else{ - if (idxch)){ - ortp_warning("RTCP packet should include a report_block_t at pos %i but has no space for it.",idx); + } else { + if (idx < rtcp_common_header_get_rc(&rr->ch)) { + ortp_warning("RTCP packet should include a report_block_t at pos %i but has no space for it.", idx); } } return NULL; } /*SDES accessors */ -bool_t rtcp_is_SDES(const mblk_t *m){ - const rtcp_common_header_t *ch=rtcp_get_common_header(m); - if (ch && rtcp_common_header_get_packet_type(ch)==RTCP_SDES){ - if (msgdsize(m)b_rptr+sizeof(rtcp_common_header_t); - const rtcp_common_header_t *ch=(rtcp_common_header_t*)m->b_rptr; - uint8_t *end=rptr+(4*(rtcp_common_header_get_length(ch)+1)); - uint32_t ssrc=0; - int nchunk=0; - bool_t chunk_start=TRUE; +void rtcp_sdes_parse(const mblk_t *m, SdesItemFoundCallback cb, void *user_data) { + uint8_t *rptr = (uint8_t *)m->b_rptr + sizeof(rtcp_common_header_t); + const rtcp_common_header_t *ch = (rtcp_common_header_t *)m->b_rptr; + uint8_t *end = rptr + (4 * (rtcp_common_header_get_length(ch) + 1)); + uint32_t ssrc = 0; + int nchunk = 0; + bool_t chunk_start = TRUE; - if (end>(uint8_t*)m->b_wptr) end=(uint8_t*)m->b_wptr; + if (end > (uint8_t *)m->b_wptr) end = (uint8_t *)m->b_wptr; - while(rptrb_rptr; - int rc=rtcp_common_header_get_rc(&bye->ch); - if (idxssrc[idx]<=(m->b_rptr - + rtcp_get_size(m)-4)) { - *ssrc=ntohl(bye->ssrc[idx]); +bool_t rtcp_BYE_get_ssrc(const mblk_t *m, int idx, uint32_t *ssrc) { + rtcp_bye_t *bye = (rtcp_bye_t *)m->b_rptr; + int rc = rtcp_common_header_get_rc(&bye->ch); + if (idx < rc) { + if ((uint8_t *)&bye->ssrc[idx] <= (m->b_rptr + rtcp_get_size(m) - 4)) { + *ssrc = ntohl(bye->ssrc[idx]); return TRUE; - }else{ - ortp_warning("RTCP BYE should contain %i ssrc, but there is not enough room for it.",rc); + } else { + ortp_warning("RTCP BYE should contain %i ssrc, but there is not enough room for it.", rc); } } return FALSE; } -bool_t rtcp_BYE_get_reason(const mblk_t *m, const char **reason, int *reason_len){ - rtcp_bye_t *bye=(rtcp_bye_t*)m->b_rptr; - int rc=rtcp_common_header_get_rc(&bye->ch); - uint8_t *rptr=(uint8_t*)m->b_rptr+sizeof(rtcp_common_header_t)+rc*4; - uint8_t *end=(uint8_t*)(m->b_rptr+rtcp_get_size(m)); - if (rptrb_rptr; + int rc = rtcp_common_header_get_rc(&bye->ch); + uint8_t *rptr = (uint8_t *)m->b_rptr + sizeof(rtcp_common_header_t) + rc * 4; + uint8_t *end = (uint8_t *)(m->b_rptr + rtcp_get_size(m)); + if (rptr < end) { + uint8_t content_len = rptr[0]; + if (rptr + 1 + content_len <= end) { + *reason = (char *)rptr + 1; + *reason_len = content_len; return TRUE; - }else{ + } else { ortp_warning("RTCP BYE has not enough space for reason phrase."); return FALSE; } @@ -242,15 +241,15 @@ bool_t rtcp_BYE_get_reason(const mblk_t *m, const char **reason, int *reason_len } /*APP accessors */ -bool_t rtcp_is_APP(const mblk_t *m){ - const rtcp_common_header_t *ch=rtcp_get_common_header(m); - size_t size=rtcp_get_size(m); - if (ch!=NULL && rtcp_common_header_get_packet_type(ch)==RTCP_APP){ - if (msgdsize(m)b_rptr; +int rtcp_APP_get_subtype(const mblk_t *m) { + rtcp_app_t *app = (rtcp_app_t *)m->b_rptr; return rtcp_common_header_get_rc(&app->ch); } -uint32_t rtcp_APP_get_ssrc(const mblk_t *m){ - rtcp_app_t *app=(rtcp_app_t*)m->b_rptr; +uint32_t rtcp_APP_get_ssrc(const mblk_t *m) { + rtcp_app_t *app = (rtcp_app_t *)m->b_rptr; return ntohl(app->ssrc); } /* name argument is supposed to be at least 4 characters (note: no '\0' written)*/ -void rtcp_APP_get_name(const mblk_t *m, char *name){ - rtcp_app_t *app=(rtcp_app_t*)m->b_rptr; - memcpy(name,app->name,4); +void rtcp_APP_get_name(const mblk_t *m, char *name) { + rtcp_app_t *app = (rtcp_app_t *)m->b_rptr; + memcpy(name, app->name, 4); } /* retrieve the data. when returning, data points directly into the mblk_t */ -void rtcp_APP_get_data(const mblk_t *m, uint8_t **data, int *len){ - int datalen=(int)rtcp_get_size(m)-sizeof(rtcp_app_t); - if (datalen>0){ - *data=(uint8_t*)m->b_rptr+sizeof(rtcp_app_t); - *len=datalen; - }else{ - *len=0; - *data=NULL; +void rtcp_APP_get_data(const mblk_t *m, uint8_t **data, int *len) { + int datalen = (int)rtcp_get_size(m) - sizeof(rtcp_app_t); + if (datalen > 0) { + *data = (uint8_t *)m->b_rptr + sizeof(rtcp_app_t); + *len = datalen; + } else { + *len = 0; + *data = NULL; } } - /* RTCP XR accessors */ bool_t rtcp_is_XR(const mblk_t *m) { const rtcp_common_header_t *ch = rtcp_get_common_header(m); @@ -319,17 +317,20 @@ uint64_t rtcp_XR_rcvr_rtt_get_ntp_timestamp(const mblk_t *m) { } uint32_t rtcp_XR_dlrr_get_ssrc(const mblk_t *m) { - rtcp_xr_dlrr_report_subblock_t *b = (rtcp_xr_dlrr_report_subblock_t *)(m->b_rptr + sizeof(rtcp_xr_header_t) + sizeof(rtcp_xr_generic_block_header_t)); + rtcp_xr_dlrr_report_subblock_t *b = (rtcp_xr_dlrr_report_subblock_t *)(m->b_rptr + sizeof(rtcp_xr_header_t) + + sizeof(rtcp_xr_generic_block_header_t)); return ntohl(b->ssrc); } uint32_t rtcp_XR_dlrr_get_lrr(const mblk_t *m) { - rtcp_xr_dlrr_report_subblock_t *b = (rtcp_xr_dlrr_report_subblock_t *)(m->b_rptr + sizeof(rtcp_xr_header_t) + sizeof(rtcp_xr_generic_block_header_t)); + rtcp_xr_dlrr_report_subblock_t *b = (rtcp_xr_dlrr_report_subblock_t *)(m->b_rptr + sizeof(rtcp_xr_header_t) + + sizeof(rtcp_xr_generic_block_header_t)); return ntohl(b->lrr); } uint32_t rtcp_XR_dlrr_get_dlrr(const mblk_t *m) { - rtcp_xr_dlrr_report_subblock_t *b = (rtcp_xr_dlrr_report_subblock_t *)(m->b_rptr + sizeof(rtcp_xr_header_t) + sizeof(rtcp_xr_generic_block_header_t)); + rtcp_xr_dlrr_report_subblock_t *b = (rtcp_xr_dlrr_report_subblock_t *)(m->b_rptr + sizeof(rtcp_xr_header_t) + + sizeof(rtcp_xr_generic_block_header_t)); return ntohl(b->dlrr); } @@ -339,176 +340,209 @@ uint8_t rtcp_XR_stat_summary_get_flags(const mblk_t *m) { } uint32_t rtcp_XR_stat_summary_get_ssrc(const mblk_t *m) { - rtcp_xr_stat_summary_report_block_t *b = (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_stat_summary_report_block_t *b = + (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohl(b->ssrc); } uint16_t rtcp_XR_stat_summary_get_begin_seq(const mblk_t *m) { - rtcp_xr_stat_summary_report_block_t *b = (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_stat_summary_report_block_t *b = + (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohs(b->begin_seq); } uint16_t rtcp_XR_stat_summary_get_end_seq(const mblk_t *m) { - rtcp_xr_stat_summary_report_block_t *b = (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_stat_summary_report_block_t *b = + (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohs(b->end_seq); } uint32_t rtcp_XR_stat_summary_get_lost_packets(const mblk_t *m) { - rtcp_xr_stat_summary_report_block_t *b = (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_stat_summary_report_block_t *b = + (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohl(b->lost_packets); } uint32_t rtcp_XR_stat_summary_get_dup_packets(const mblk_t *m) { - rtcp_xr_stat_summary_report_block_t *b = (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_stat_summary_report_block_t *b = + (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohl(b->dup_packets); } uint32_t rtcp_XR_stat_summary_get_min_jitter(const mblk_t *m) { - rtcp_xr_stat_summary_report_block_t *b = (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_stat_summary_report_block_t *b = + (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohl(b->min_jitter); } uint32_t rtcp_XR_stat_summary_get_max_jitter(const mblk_t *m) { - rtcp_xr_stat_summary_report_block_t *b = (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_stat_summary_report_block_t *b = + (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohl(b->max_jitter); } uint32_t rtcp_XR_stat_summary_get_mean_jitter(const mblk_t *m) { - rtcp_xr_stat_summary_report_block_t *b = (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_stat_summary_report_block_t *b = + (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohl(b->mean_jitter); } uint32_t rtcp_XR_stat_summary_get_dev_jitter(const mblk_t *m) { - rtcp_xr_stat_summary_report_block_t *b = (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_stat_summary_report_block_t *b = + (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohl(b->dev_jitter); } uint8_t rtcp_XR_stat_summary_get_min_ttl_or_hl(const mblk_t *m) { - rtcp_xr_stat_summary_report_block_t *b = (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_stat_summary_report_block_t *b = + (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->min_ttl_or_hl; } uint8_t rtcp_XR_stat_summary_get_max_ttl_or_hl(const mblk_t *m) { - rtcp_xr_stat_summary_report_block_t *b = (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_stat_summary_report_block_t *b = + (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->max_ttl_or_hl; } uint8_t rtcp_XR_stat_summary_get_mean_ttl_or_hl(const mblk_t *m) { - rtcp_xr_stat_summary_report_block_t *b = (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_stat_summary_report_block_t *b = + (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->mean_ttl_or_hl; } uint8_t rtcp_XR_stat_summary_get_dev_ttl_or_hl(const mblk_t *m) { - rtcp_xr_stat_summary_report_block_t *b = (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_stat_summary_report_block_t *b = + (rtcp_xr_stat_summary_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->dev_ttl_or_hl; } uint32_t rtcp_XR_voip_metrics_get_ssrc(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohl(b->ssrc); } uint8_t rtcp_XR_voip_metrics_get_loss_rate(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->loss_rate; } uint8_t rtcp_XR_voip_metrics_get_discard_rate(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->discard_rate; } uint8_t rtcp_XR_voip_metrics_get_burst_density(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->burst_density; } uint8_t rtcp_XR_voip_metrics_get_gap_density(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->gap_density; } uint16_t rtcp_XR_voip_metrics_get_burst_duration(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohs(b->burst_duration); } uint16_t rtcp_XR_voip_metrics_get_gap_duration(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohs(b->gap_duration); } uint16_t rtcp_XR_voip_metrics_get_round_trip_delay(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohs(b->round_trip_delay); } uint16_t rtcp_XR_voip_metrics_get_end_system_delay(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohs(b->end_system_delay); } uint8_t rtcp_XR_voip_metrics_get_signal_level(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->signal_level; } uint8_t rtcp_XR_voip_metrics_get_noise_level(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->noise_level; } uint8_t rtcp_XR_voip_metrics_get_rerl(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->rerl; } uint8_t rtcp_XR_voip_metrics_get_gmin(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->gmin; } uint8_t rtcp_XR_voip_metrics_get_r_factor(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->r_factor; } uint8_t rtcp_XR_voip_metrics_get_ext_r_factor(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->ext_r_factor; } uint8_t rtcp_XR_voip_metrics_get_mos_lq(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->mos_lq; } uint8_t rtcp_XR_voip_metrics_get_mos_cq(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->mos_cq; } uint8_t rtcp_XR_voip_metrics_get_rx_config(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return b->rx_config; } uint16_t rtcp_XR_voip_metrics_get_jb_nominal(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohs(b->jb_nominal); } uint16_t rtcp_XR_voip_metrics_get_jb_maximum(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohs(b->jb_maximum); } uint16_t rtcp_XR_voip_metrics_get_jb_abs_max(const mblk_t *m) { - rtcp_xr_voip_metrics_report_block_t *b = (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); + rtcp_xr_voip_metrics_report_block_t *b = + (rtcp_xr_voip_metrics_report_block_t *)(m->b_rptr + sizeof(rtcp_xr_header_t)); return ntohs(b->jb_abs_max); } - /* RTCP RTPFB accessors */ bool_t rtcp_is_RTPFB(const mblk_t *m) { const rtcp_common_header_t *ch = rtcp_get_common_header(m); @@ -543,7 +577,7 @@ uint32_t rtcp_RTPFB_get_media_source_ssrc(const mblk_t *m) { return ntohl(fbh->media_source_ssrc); } -rtcp_fb_generic_nack_fci_t * rtcp_RTPFB_generic_nack_get_fci(const mblk_t *m) { +rtcp_fb_generic_nack_fci_t *rtcp_RTPFB_generic_nack_get_fci(const mblk_t *m) { size_t size = sizeof(rtcp_common_header_t) + sizeof(rtcp_fb_header_t) + sizeof(rtcp_fb_generic_nack_fci_t); size_t rtcp_size = rtcp_get_size(m); if (size > rtcp_size) { @@ -552,7 +586,7 @@ rtcp_fb_generic_nack_fci_t * rtcp_RTPFB_generic_nack_get_fci(const mblk_t *m) { return (rtcp_fb_generic_nack_fci_t *)(m->b_rptr + size - sizeof(rtcp_fb_generic_nack_fci_t)); } -rtcp_fb_tmmbr_fci_t * rtcp_RTPFB_tmmbr_get_fci(const mblk_t *m) { +rtcp_fb_tmmbr_fci_t *rtcp_RTPFB_tmmbr_get_fci(const mblk_t *m) { size_t size = sizeof(rtcp_common_header_t) + sizeof(rtcp_fb_header_t) + sizeof(rtcp_fb_tmmbr_fci_t); size_t rtcp_size = rtcp_get_size(m); if (size > rtcp_size) { @@ -566,7 +600,6 @@ uint64_t rtcp_RTPFB_tmmbr_get_max_bitrate(const mblk_t *m) { return rtcp_fb_tmmbr_fci_get_mxtbr_mantissa(fci) * (1 << rtcp_fb_tmmbr_fci_get_mxtbr_exp(fci)); } - /* RTCP PSFB accessors */ bool_t rtcp_is_PSFB(const mblk_t *m) { const rtcp_common_header_t *ch = rtcp_get_common_header(m); @@ -601,7 +634,7 @@ uint32_t rtcp_PSFB_get_media_source_ssrc(const mblk_t *m) { return ntohl(fbh->media_source_ssrc); } -rtcp_fb_fir_fci_t * rtcp_PSFB_fir_get_fci(const mblk_t *m, unsigned int idx) { +rtcp_fb_fir_fci_t *rtcp_PSFB_fir_get_fci(const mblk_t *m, unsigned int idx) { size_t size = sizeof(rtcp_common_header_t) + sizeof(rtcp_fb_header_t) + ((idx + 1) * sizeof(rtcp_fb_fir_fci_t)); size_t rtcp_size = rtcp_get_size(m); if (size > rtcp_size) { @@ -610,7 +643,7 @@ rtcp_fb_fir_fci_t * rtcp_PSFB_fir_get_fci(const mblk_t *m, unsigned int idx) { return (rtcp_fb_fir_fci_t *)(m->b_rptr + size - sizeof(rtcp_fb_fir_fci_t)); } -rtcp_fb_sli_fci_t * rtcp_PSFB_sli_get_fci(const mblk_t *m, unsigned int idx) { +rtcp_fb_sli_fci_t *rtcp_PSFB_sli_get_fci(const mblk_t *m, unsigned int idx) { size_t size = sizeof(rtcp_common_header_t) + sizeof(rtcp_fb_header_t) + ((idx + 1) * sizeof(rtcp_fb_sli_fci_t)); size_t rtcp_size = rtcp_get_size(m); if (size > rtcp_size) { @@ -619,12 +652,13 @@ rtcp_fb_sli_fci_t * rtcp_PSFB_sli_get_fci(const mblk_t *m, unsigned int idx) { return (rtcp_fb_sli_fci_t *)(m->b_rptr + size - sizeof(rtcp_fb_sli_fci_t)); } -rtcp_fb_rpsi_fci_t * rtcp_PSFB_rpsi_get_fci(const mblk_t *m) { +rtcp_fb_rpsi_fci_t *rtcp_PSFB_rpsi_get_fci(const mblk_t *m) { return (rtcp_fb_rpsi_fci_t *)(m->b_rptr + sizeof(rtcp_common_header_t) + sizeof(rtcp_fb_header_t)); } uint16_t rtcp_PSFB_rpsi_get_fci_bit_string_len(const mblk_t *m) { rtcp_fb_rpsi_fci_t *fci = rtcp_PSFB_rpsi_get_fci(m); - uint16_t bit_string_len_in_bytes = (uint16_t)(rtcp_get_size(m) - (sizeof(rtcp_common_header_t) + sizeof(rtcp_fb_header_t) + 2)); + uint16_t bit_string_len_in_bytes = + (uint16_t)(rtcp_get_size(m) - (sizeof(rtcp_common_header_t) + sizeof(rtcp_fb_header_t) + 2)); return ((bit_string_len_in_bytes * 8) - fci->pb); } diff --git a/src/rtpaudiolevel.c b/src/rtpaudiolevel.c index 31e89164..d1a868a9 100644 --- a/src/rtpaudiolevel.c +++ b/src/rtpaudiolevel.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -28,7 +28,7 @@ * @param id the identifier of the client to mixer audio level extension. * @param voice_activity TRUE if there is voice activity, FALSE otherwise. * @param audio_level the audio level to set expressed in dBov. -**/ + **/ void rtp_add_client_to_mixer_audio_level(mblk_t *packet, int id, bool_t voice_activity, int audio_level) { uint8_t data = (voice_activity ? 0x1 : 0x0) << 7 | (audio_level * -1); rtp_add_extension_header(packet, id, sizeof(data), &data); @@ -41,7 +41,7 @@ void rtp_add_client_to_mixer_audio_level(mblk_t *packet, int id, bool_t voice_ac * @param id the identifier of the client to mixer audio level extension. * @param voice_activity set to TRUE if there is voice activity, FALSE otherwise * @return the client to mixer audio level in dBov, -1 if there is no extension header or the extension was not found. -**/ + **/ int rtp_get_client_to_mixer_audio_level(mblk_t *packet, int id, bool_t *voice_activity) { uint8_t *data; int ret; @@ -56,16 +56,18 @@ int rtp_get_client_to_mixer_audio_level(mblk_t *packet, int id, bool_t *voice_ac return -1; } -static void rtp_add_mixer_to_client_audio_level_base(mblk_t *packet, int id, size_t size, rtp_audio_level_t *audio_levels, bool_t allocate_buffer) { +static void rtp_add_mixer_to_client_audio_level_base( + mblk_t *packet, int id, size_t size, rtp_audio_level_t *audio_levels, bool_t allocate_buffer) { uint8_t *data; int i; if (audio_levels == NULL || size <= 0) return; if (allocate_buffer != FALSE) { - // Increase packet size to have enough space to add csrc. Make room just after the header and possible CSRC already there - // but before possible extension header - msgpullup_with_insert(packet, RTP_FIXED_HEADER_SIZE+(rtp_get_cc(packet)*sizeof(uint32_t)), size * sizeof(uint32_t)); + // Increase packet size to have enough space to add csrc. Make room just after the header and possible CSRC + // already there but before possible extension header + msgpullup_with_insert(packet, RTP_FIXED_HEADER_SIZE + (rtp_get_cc(packet) * sizeof(uint32_t)), + size * sizeof(uint32_t)); } data = ortp_new0(uint8_t, size); @@ -91,7 +93,7 @@ static void rtp_add_mixer_to_client_audio_level_base(mblk_t *packet, int id, siz * @param id the identifier of the client to mixer audio level extension. * @param size the size of the audio_levels list. * @param audio_levels the list if audio levels to set. -**/ + **/ void rtp_write_mixer_to_client_audio_level(mblk_t *packet, int id, size_t size, rtp_audio_level_t *audio_levels) { rtp_add_mixer_to_client_audio_level_base(packet, id, size, audio_levels, FALSE); } @@ -103,7 +105,7 @@ void rtp_write_mixer_to_client_audio_level(mblk_t *packet, int id, size_t size, * @param id the identifier of the client to mixer audio level extension. * @param size the size of the audio_levels list. * @param audio_levels the list if audio levels to set. -**/ + **/ void rtp_add_mixer_to_client_audio_level(mblk_t *packet, int id, size_t size, rtp_audio_level_t *audio_levels) { rtp_add_mixer_to_client_audio_level_base(packet, id, size, audio_levels, TRUE); } @@ -113,19 +115,22 @@ void rtp_add_mixer_to_client_audio_level(mblk_t *packet, int id, size_t size, rt * See https://tools.ietf.org/html/rfc6465 * @param packet the RTP packet. * @param id the identifier of the mixer to client audio level extension. - * @param audio_levels the list of mixer to client audio levels, this array must be allocated before calling this function. + * @param audio_levels the list of mixer to client audio levels, this array must be allocated before calling this + *function. * @return the size of the mixer to client audio levels list, -1 in case of error. -**/ -int rtp_get_mixer_to_client_audio_level(mblk_t *packet, int id, rtp_audio_level_t* audio_levels) { + **/ +int rtp_get_mixer_to_client_audio_level(mblk_t *packet, int id, rtp_audio_level_t *audio_levels) { int ret, i; uint8_t *data; ret = rtp_get_extension_header(packet, id, &data); if (ret != -1) { - rtp_header_t *header = (rtp_header_t*) packet->b_rptr; + rtp_header_t *header = (rtp_header_t *)packet->b_rptr; if (ret != header->cc) { - ortp_error("Error while retrieving mixer to client audio levels [%p]: number of audio level and csrc do not match", packet); + ortp_error( + "Error while retrieving mixer to client audio levels [%p]: number of audio level and csrc do not match", + packet); return -1; } diff --git a/src/rtpbundle.cc b/src/rtpbundle.cc index 921600eb..bf4c84df 100644 --- a/src/rtpbundle.cc +++ b/src/rtpbundle.cc @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -20,6 +20,8 @@ #include +#include + #include "ortp/logging.h" #include "ortp/rtpsession.h" #include "rtpbundle.h" @@ -44,7 +46,8 @@ extern "C" void rtp_bundle_set_mid_extension_id(RtpBundle *bundle, int id) { extern "C" void rtp_bundle_add_session(RtpBundle *bundle, const char *mid, RtpSession *session) { ((RtpBundleCxx *)bundle)->addSession(mid, session); } -extern "C" void rtp_bundle_add_fec_session(RtpBundle *bundle, const RtpSession *source_session, RtpSession *fec_session) { +extern "C" void +rtp_bundle_add_fec_session(RtpBundle *bundle, const RtpSession *source_session, RtpSession *fec_session) { ((RtpBundleCxx *)bundle)->addFecSession(source_session, fec_session); } extern "C" void rtp_bundle_remove_session_by_id(RtpBundle *bundle, const char *mid) { @@ -95,14 +98,14 @@ void RtpBundleCxx::setMidId(int id) { } void RtpBundleCxx::addSession(const std::string &mid, RtpSession *session) { auto it = - std::find_if(sessions.begin(), sessions.end(), - [session](const std::pair &t) -> bool { return t.second == session; }); + std::find_if(sessions.begin(), sessions.end(), + [session](const std::pair &t) -> bool { return t.second == session; }); if (it != sessions.end()) { ortp_error("RtpBundle [%p]: Cannot add session (%p) has it is already in the bundle", this, session); return; } - + sessions.emplace(mid, session); session->bundle = (RtpBundle *)this; @@ -112,13 +115,14 @@ void RtpBundleCxx::addSession(const std::string &mid, RtpSession *session) { session->is_primary = TRUE; } } -void RtpBundleCxx::addFecSession(const RtpSession *sourceSession, RtpSession *fecSession){ - auto it = - std::find_if(sessions.begin(), sessions.end(), - [sourceSession](const std::pair &t) -> bool { return t.second == sourceSession; }); +void RtpBundleCxx::addFecSession(const RtpSession *sourceSession, RtpSession *fecSession) { + auto it = std::find_if( + sessions.begin(), sessions.end(), + [sourceSession](const std::pair &t) -> bool { return t.second == sourceSession; }); if (it == sessions.end()) { - ortp_error("RtpBundle [%p]: Cannot add session (%p) because the associated source session isn't in the bundle", this, fecSession); + ortp_error("RtpBundle [%p]: Cannot add session (%p) because the associated source session isn't in the bundle", + this, fecSession); return; } std::string mid = getSessionMid(it->second); @@ -145,9 +149,9 @@ void RtpBundleCxx::removeSession(const std::string &mid) { } ssrcToMidMutex.unlock(); - if(session->second->fec_stream != NULL){ + if (session->second->fec_stream != NULL) { auto fec_session = fec_sessions.find(mid); - if(fec_session != fec_sessions.end()){ + if (fec_session != fec_sessions.end()) { fec_session->second->bundle = NULL; fec_sessions.erase(mid); } @@ -159,8 +163,8 @@ void RtpBundleCxx::removeSession(const std::string &mid) { void RtpBundleCxx::removeSession(RtpSession *session) { auto it = - std::find_if(sessions.begin(), sessions.end(), - [session](const std::pair &t) -> bool { return t.second == session; }); + std::find_if(sessions.begin(), sessions.end(), + [session](const std::pair &t) -> bool { return t.second == session; }); if (it != sessions.end()) { removeSession(it->first); @@ -172,7 +176,7 @@ void RtpBundleCxx::clear() { RtpSession *session = entry.second; session->bundle = NULL; } - for(const auto &entry : fec_sessions){ + for (const auto &entry : fec_sessions) { RtpSession *session = entry.second; session->bundle = NULL; } @@ -200,15 +204,15 @@ void RtpBundleCxx::setPrimarySession(const std::string &mid) { const std::string &RtpBundleCxx::getSessionMid(RtpSession *session) const { auto it = - std::find_if(sessions.begin(), sessions.end(), - [session](const std::pair &t) -> bool { return t.second == session; }); + std::find_if(sessions.begin(), sessions.end(), + [session](const std::pair &t) -> bool { return t.second == session; }); if (it != sessions.end()) { return it->first; - } - else {//Could be a FEC session - it = std::find_if(fec_sessions.begin(), fec_sessions.end(), - [session](const std::pair &t) -> bool { return t.second == session; }); + } else { // Could be a FEC session + it = std::find_if( + fec_sessions.begin(), fec_sessions.end(), + [session](const std::pair &t) -> bool { return t.second == session; }); if (it != sessions.end()) { return it->first; } @@ -227,7 +231,7 @@ bool RtpBundleCxx::updateMid(const std::string &mid, const uint32_t ssrc, const ortp_message("Rtp Bundle [%p] SSRC [%u] paired with mid [%s]", this, ssrc, mid.c_str()); return true; } else if ((*entry).second.mid != mid) { - if (isRtp) { + if (isRtp) { ortp_message("Rtp Bundle [%p]: received a mid update via RTP.", this); if (entry->second.sequenceNumber < sequenceNumber) { Mid value = {mid, sequenceNumber}; @@ -246,8 +250,11 @@ bool RtpBundleCxx::updateMid(const std::string &mid, const uint32_t ssrc, const return false; } -static void getSsrcFromSdes(void *userData, uint32_t ssrc, rtcp_sdes_type_t t, const char *content, - uint8_t contentLen) { +static void getSsrcFromSdes(void *userData, + uint32_t ssrc, + rtcp_sdes_type_t t, + BCTBX_UNUSED(const char *content), + BCTBX_UNUSED(uint8_t contentLen)) { uint32_t *value = (uint32_t *)userData; if (*value == 0 || t == RTCP_SDES_MID) { @@ -264,37 +271,37 @@ static uint32_t getSsrcFromMessage(mblk_t *m, bool isRtp) { uint32_t ssrc = 0; switch (rtcp_common_header_get_packet_type(ch)) { - case RTCP_SR: - return rtcp_SR_get_ssrc(m); - case RTCP_RR: - return rtcp_RR_get_ssrc(m); - case RTCP_SDES: - rtcp_sdes_parse(m, getSsrcFromSdes, &ssrc); - return ssrc; - case RTCP_BYE: - if (rtcp_BYE_get_ssrc(m, 0, &ssrc)) { + case RTCP_SR: + return rtcp_SR_get_ssrc(m); + case RTCP_RR: + return rtcp_RR_get_ssrc(m); + case RTCP_SDES: + rtcp_sdes_parse(m, getSsrcFromSdes, &ssrc); return ssrc; - } - return -1; - case RTCP_APP: - return rtcp_APP_get_ssrc(m); - case RTCP_RTPFB: - return rtcp_RTPFB_get_packet_sender_ssrc(m); - case RTCP_PSFB: - return rtcp_PSFB_get_packet_sender_ssrc(m); - case RTCP_XR: - return rtcp_XR_get_ssrc(m); - default: - ortp_warning("Unknown RTCP packet type (%u) while retrieving it's SSRC", - rtcp_common_header_get_packet_type(ch)); - break; + case RTCP_BYE: + if (rtcp_BYE_get_ssrc(m, 0, &ssrc)) { + return ssrc; + } + return -1; + case RTCP_APP: + return rtcp_APP_get_ssrc(m); + case RTCP_RTPFB: + return rtcp_RTPFB_get_packet_sender_ssrc(m); + case RTCP_PSFB: + return rtcp_PSFB_get_packet_sender_ssrc(m); + case RTCP_XR: + return rtcp_XR_get_ssrc(m); + default: + ortp_warning("Unknown RTCP packet type (%u) while retrieving it's SSRC", + rtcp_common_header_get_packet_type(ch)); + break; } return -1; } -static void checkForSessionSdesCallback(void *userData, uint32_t ssrc, rtcp_sdes_type_t t, const char *content, - uint8_t contentLen) { +static void checkForSessionSdesCallback( + void *userData, uint32_t ssrc, rtcp_sdes_type_t t, const char *content, uint8_t contentLen) { RtpBundleCxx *bundle = (RtpBundleCxx *)userData; std::string value(content, contentLen); @@ -302,8 +309,8 @@ static void checkForSessionSdesCallback(void *userData, uint32_t ssrc, rtcp_sdes // Update the mid map with the corresponding session if (!bundle->updateMid(value, ssrc, UINT16_MAX, false)) { ortp_warning("Rtp Bundle [%p]: SSRC %u not found and SDES mid \"%s\" from msg does not " - "correspond to any sessions", - bundle, ssrc, value.c_str()); + "correspond to any sessions", + bundle, ssrc, value.c_str()); } bundle->sdesParseMid = value; @@ -314,9 +321,9 @@ RtpSession *RtpBundleCxx::checkForSession(mblk_t *m, bool isRtp) { const std::lock_guard guard(ssrcToMidMutex); uint32_t ssrc; - if (isRtp && rtp_get_version(m)!= 2) { + if (isRtp && rtp_get_version(m) != 2) { /* STUN packet*/ - return primary; + return primary; } ssrc = getSsrcFromMessage(m, isRtp); @@ -335,22 +342,22 @@ RtpSession *RtpBundleCxx::checkForSession(mblk_t *m, bool isRtp) { if (!updateMid(mid, ssrc, rtp_get_seqnumber(m), true)) { if (it == ssrcToMid.end()) { ortp_warning("Rtp Bundle [%p]: SSRC %u not found and mid \"%s\" from msg (%d) does not " - "correspond to any sessions", - this, ssrc, mid.c_str(), (int)rtp_get_seqnumber(m)); + "correspond to any sessions", + this, ssrc, mid.c_str(), (int)rtp_get_seqnumber(m)); return NULL; } } } else { if (it == ssrcToMid.end()) { ortp_warning("Rtp Bundle [%p]: SSRC %u not found and msg (%d) does not have a mid extension header", - this, ssrc, (int)rtp_get_seqnumber(m)); + this, ssrc, (int)rtp_get_seqnumber(m)); return NULL; } } } else { if (it == ssrcToMid.end()) { ortp_warning("Rtp Bundle [%p]: SSRC %u not found and msg (%d) does not have an extension header", this, - ssrc, (int)rtp_get_seqnumber(m)); + ssrc, (int)rtp_get_seqnumber(m)); return NULL; } } @@ -380,15 +387,16 @@ RtpSession *RtpBundleCxx::checkForSession(mblk_t *m, bool isRtp) { } else { try { auto session = sessions.at(it->second.mid); - if(session->fec_stream){ + if (session->fec_stream) { RtpSession *fec_session = fec_stream_get_fec_session(session->fec_stream); - if(rtp_session_get_recv_payload_type(fec_session) == rtp_get_payload_type(m)){ + if (rtp_session_get_recv_payload_type(fec_session) == rtp_get_payload_type(m)) { return fec_session; } } return session; - } catch (std::out_of_range&) { - ortp_warning("Rtp Bundle [%p]: Unable to find session with mid %s (SSRC %u)", this, it->second.mid.c_str(), ssrc); + } catch (std::out_of_range &) { + ortp_warning("Rtp Bundle [%p]: Unable to find session with mid %s (SSRC %u)", this, it->second.mid.c_str(), + ssrc); return nullptr; } } @@ -454,7 +462,7 @@ bool RtpBundleCxx::dispatchRtcpMessage(mblk_t *m) { } else { const rtcp_common_header_t *ch = rtcp_get_common_header(tmp); ortp_warning("Rtp Bundle [%p]: Rctp msg (%d) ssrc=%u does not correspond to any sessions", this, - rtcp_common_header_get_packet_type(ch), getSsrcFromMessage(tmp, false)); + rtcp_common_header_get_packet_type(ch), getSsrcFromMessage(tmp, false)); freemsg(tmp); } } while (rtcp_next_packet(m)); diff --git a/src/rtpbundle.h b/src/rtpbundle.h index 584be7e0..786ed477 100644 --- a/src/rtpbundle.h +++ b/src/rtpbundle.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -33,13 +33,13 @@ static void checkForSessionSdesCallback(void *, uint32_t, rtcp_sdes_type_t, cons class RtpBundleCxx { friend void checkForSessionSdesCallback(void *, uint32_t, rtcp_sdes_type_t, const char *, uint8_t); - public: +public: RtpBundleCxx() = default; ~RtpBundleCxx(); RtpBundleCxx(const RtpBundleCxx &) = delete; RtpBundleCxx(RtpBundleCxx &&) = delete; - + int getMidId() const; void setMidId(int id); void addFecSession(const RtpSession *sourceSession, RtpSession *fecSession); @@ -59,7 +59,7 @@ class RtpBundleCxx { bool updateMid(const std::string &mid, const uint32_t ssrc, const uint16_t sequenceNumber, bool isRtp); - private: +private: struct Mid { std::string mid; uint16_t sequenceNumber; @@ -78,6 +78,6 @@ class RtpBundleCxx { std::string sdesParseMid = ""; int midId = -1; -}; +}; #endif /* RTPBUNDLE_H */ diff --git a/src/rtpframemarking.c b/src/rtpframemarking.c index f68980fa..ddc4754d 100644 --- a/src/rtpframemarking.c +++ b/src/rtpframemarking.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -27,7 +27,7 @@ * @param packet the RTP packet. * @param id the identifier of the frame marking extension. * @param marker the frame marker to add. -**/ + **/ void rtp_add_frame_marker(mblk_t *packet, int id, uint8_t marker) { rtp_add_extension_header(packet, id, 1, &marker); } @@ -39,7 +39,7 @@ void rtp_add_frame_marker(mblk_t *packet, int id, uint8_t marker) { * @param id the identifier of the frame marking extension. * @param marker the frame marker to set. * @return 1 if the frame marker if present, 0 otherwise. -**/ + **/ int rtp_get_frame_marker(mblk_t *packet, int id, uint8_t *marker) { uint8_t *data; diff --git a/src/rtpparse.c b/src/rtpparse.c index a1c5e17f..da02a0bb 100644 --- a/src/rtpparse.c +++ b/src/rtpparse.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,26 +18,24 @@ * along with this program. If not, see . */ - #ifdef HAVE_CONFIG_H #include "ortp-config.h" #endif -#include "ortp/ortp.h" +#include "congestiondetector.h" #include "jitterctl.h" -#include "utils.h" +#include "ortp/ortp.h" #include "rtpsession_priv.h" -#include "congestiondetector.h" +#include "utils.h" #include "videobandwidthestimator.h" -static bool_t queue_packet(queue_t *q, int maxrqsz, mblk_t *mp, rtp_header_t *rtp, int *discarded, int *duplicate) -{ +static bool_t queue_packet(queue_t *q, int maxrqsz, mblk_t *mp, rtp_header_t *rtp, int *discarded, int *duplicate) { mblk_t *tmp; int header_size; - *discarded=0; - *duplicate=0; - header_size=RTP_FIXED_HEADER_SIZE+ (4*rtp->cc); - if ((mp->b_wptr - mp->b_rptr)==header_size){ + *discarded = 0; + *duplicate = 0; + header_size = RTP_FIXED_HEADER_SIZE + (4 * rtp->cc); + if ((mp->b_wptr - mp->b_rptr) == header_size) { ortp_debug("Rtp packet contains no data."); (*discarded)++; freemsg(mp); @@ -45,16 +43,15 @@ static bool_t queue_packet(queue_t *q, int maxrqsz, mblk_t *mp, rtp_header_t *rt } /* and then add the packet to the queue */ - if (rtp_putq(q,mp) < 0) { + if (rtp_putq(q, mp) < 0) { /* It was a duplicate packet */ (*duplicate)++; } /* make some checks: q size must not exceed RtpStream::max_rq_size */ - while (q->q_mcount > maxrqsz) - { + while (q->q_mcount > maxrqsz) { /* remove the oldest mblk_t */ - tmp=getq(q); + tmp = getq(q); ortp_warning("rtp_putq: Queue is full. Discarding message with ts=%u", rtp_get_timestamp(tmp)); freemsg(tmp); @@ -81,12 +78,11 @@ static void update_rtcp_xr_stat_summary(RtpSession *session, mblk_t *mp, uint32_ session->rtcp_xr_stats.oldm_ttl_or_hl_since_last_stat_summary = mp->ttl_or_hl; session->rtcp_xr_stats.newm_ttl_or_hl_since_last_stat_summary = mp->ttl_or_hl; } - compute_mean_and_deviation(session->rtcp_xr_stats.rcv_since_last_stat_summary, - (double)mp->ttl_or_hl, - &session->rtcp_xr_stats.olds_ttl_or_hl_since_last_stat_summary, - &session->rtcp_xr_stats.oldm_ttl_or_hl_since_last_stat_summary, - &session->rtcp_xr_stats.news_ttl_or_hl_since_last_stat_summary, - &session->rtcp_xr_stats.newm_ttl_or_hl_since_last_stat_summary); + compute_mean_and_deviation(session->rtcp_xr_stats.rcv_since_last_stat_summary, (double)mp->ttl_or_hl, + &session->rtcp_xr_stats.olds_ttl_or_hl_since_last_stat_summary, + &session->rtcp_xr_stats.oldm_ttl_or_hl_since_last_stat_summary, + &session->rtcp_xr_stats.news_ttl_or_hl_since_last_stat_summary, + &session->rtcp_xr_stats.newm_ttl_or_hl_since_last_stat_summary); if (mp->ttl_or_hl < session->rtcp_xr_stats.min_ttl_or_hl_since_last_stat_summary) { session->rtcp_xr_stats.min_ttl_or_hl_since_last_stat_summary = mp->ttl_or_hl; } @@ -106,12 +102,11 @@ static void update_rtcp_xr_stat_summary(RtpSession *session, mblk_t *mp, uint32_ } else { jitter = (uint32_t)(signed_jitter); } - compute_mean_and_deviation(session->rtcp_xr_stats.rcv_since_last_stat_summary - 1, - (double)jitter, - &session->rtcp_xr_stats.olds_jitter_since_last_stat_summary, - &session->rtcp_xr_stats.oldm_jitter_since_last_stat_summary, - &session->rtcp_xr_stats.news_jitter_since_last_stat_summary, - &session->rtcp_xr_stats.newm_jitter_since_last_stat_summary); + compute_mean_and_deviation(session->rtcp_xr_stats.rcv_since_last_stat_summary - 1, (double)jitter, + &session->rtcp_xr_stats.olds_jitter_since_last_stat_summary, + &session->rtcp_xr_stats.oldm_jitter_since_last_stat_summary, + &session->rtcp_xr_stats.news_jitter_since_last_stat_summary, + &session->rtcp_xr_stats.newm_jitter_since_last_stat_summary); if (jitter < session->rtcp_xr_stats.min_jitter_since_last_stat_summary) { session->rtcp_xr_stats.min_jitter_since_last_stat_summary = jitter; } @@ -128,10 +123,9 @@ static void check_for_seq_number_gap_immediate(RtpSession *session, rtp_header_t uint16_t seq_number = rtp_header_get_seqnumber(rtp); /*don't check anything before first packet delivered*/ - if (session->flags & RTP_SESSION_FIRST_PACKET_DELIVERED - && RTP_SEQ_IS_STRICTLY_GREATER_THAN(seq_number, session->rtp.rcv_last_seq + 1) - && RTP_SEQ_IS_STRICTLY_GREATER_THAN(seq_number, session->rtp.snd_last_nack + 1) - ) { + if (session->flags & RTP_SESSION_FIRST_PACKET_DELIVERED && + RTP_SEQ_IS_STRICTLY_GREATER_THAN(seq_number, session->rtp.rcv_last_seq + 1) && + RTP_SEQ_IS_STRICTLY_GREATER_THAN(seq_number, session->rtp.snd_last_nack + 1)) { uint16_t first_missed_seq = session->rtp.rcv_last_seq + 1; uint16_t diff; @@ -150,10 +144,10 @@ static void check_for_seq_number_gap_immediate(RtpSession *session, rtp_header_t } if (session->rtp.congdetect != NULL && session->rtp.congdetect->state == CongestionStateDetected) { /* - * Do not send NACK in IMMEDIATE_NACK mode in congestion, because the retransmission by the other party of the missing packets - * will necessarily increase or at least sustain the congestion. - * Furthermore, due to the congestion, the retransmitted packets have very few chance to arrive in time. - */ + * Do not send NACK in IMMEDIATE_NACK mode in congestion, because the retransmission by the other party + * of the missing packets will necessarily increase or at least sustain the congestion. Furthermore, due + * to the congestion, the retransmitted packets have very few chance to arrive in time. + */ ortp_message("Immediate NACK not sent because of congestion."); return; } @@ -168,43 +162,42 @@ static void check_for_seq_number_gap_immediate(RtpSession *session, rtp_header_t } } -void rtp_session_rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_ts, struct sockaddr *addr, socklen_t addrlen) -{ +void rtp_session_rtp_parse( + RtpSession *session, mblk_t *mp, uint32_t local_str_ts, struct sockaddr *addr, socklen_t addrlen) { int discarded; int duplicate; rtp_header_t *rtp; int msgsize; - RtpStream *rtpstream=&session->rtp; - rtp_stats_t *stats=&session->stats; + RtpStream *rtpstream = &session->rtp; + rtp_stats_t *stats = &session->stats; uint16_t seq_number; uint32_t timestamp, ssrc; - msgsize=(int)(mp->b_wptr-mp->b_rptr); + msgsize = (int)(mp->b_wptr - mp->b_rptr); - if (msgsizestats.bad++; ortp_global_stats.bad++; freemsg(mp); return; } - rtp=(rtp_header_t*)mp->b_rptr; - if (rtp->version!=2) - { + rtp = (rtp_header_t *)mp->b_rptr; + if (rtp->version != 2) { /* try to see if it is a STUN packet */ - uint16_t stunlen=*((uint16_t*)(mp->b_rptr + sizeof(uint16_t))); + uint16_t stunlen = *((uint16_t *)(mp->b_rptr + sizeof(uint16_t))); stunlen = ntohs(stunlen); - if (stunlen+20==mp->b_wptr-mp->b_rptr){ + if (stunlen + 20 == mp->b_wptr - mp->b_rptr) { /* this looks like a stun packet */ - rtp_session_update_remote_sock_addr(session,mp,TRUE,TRUE); - if (session->eventqs!=NULL){ - OrtpEvent *ev=ortp_event_new(ORTP_EVENT_STUN_PACKET_RECEIVED); - OrtpEventData *ed=ortp_event_get_data(ev); - ed->packet=mp; - memcpy(&ed->source_addr,addr,addrlen); - ed->source_addrlen=addrlen; + rtp_session_update_remote_sock_addr(session, mp, TRUE, TRUE); + if (session->eventqs != NULL) { + OrtpEvent *ev = ortp_event_new(ORTP_EVENT_STUN_PACKET_RECEIVED); + OrtpEventData *ed = ortp_event_get_data(ev); + ed->packet = mp; + memcpy(&ed->source_addr, addr, addrlen); + ed->source_addrlen = addrlen; ed->info.socket_type = OrtpRTPSocket; - rtp_session_dispatch_event(session,ev); + rtp_session_dispatch_event(session, ev); return; } } @@ -219,8 +212,8 @@ void rtp_session_rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_t /* only count non-stun packets. */ ortp_global_stats.packet_recv++; stats->packet_recv++; - ortp_global_stats.hw_recv+=msgsize; - stats->hw_recv+=msgsize; + ortp_global_stats.hw_recv += msgsize; + stats->hw_recv += msgsize; session->rtp.hwrcv_since_last_SR++; session->rtcp_xr_stats.rcv_since_last_stat_summary++; @@ -229,7 +222,7 @@ void rtp_session_rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_t timestamp = rtp_header_get_timestamp(rtp); ssrc = rtp_header_get_ssrc(rtp); /* convert csrc if necessary */ - if (rtp->cc*sizeof(uint32_t) > (uint32_t) (msgsize-RTP_FIXED_HEADER_SIZE)){ + if (rtp->cc * sizeof(uint32_t) > (uint32_t)(msgsize - RTP_FIXED_HEADER_SIZE)) { ortp_debug("Receiving too short rtp packet."); stats->bad++; ortp_global_stats.bad++; @@ -244,22 +237,22 @@ void rtp_session_rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_t /*the goal of the following code is to lock on an incoming SSRC to avoid receiving "mixed streams"*/ - if (session->ssrc_set){ + if (session->ssrc_set) { /*the ssrc is set, so we must check it */ - if (session->rcv.ssrc!=ssrc){ - if (session->inc_ssrc_candidate==ssrc){ + if (session->rcv.ssrc != ssrc) { + if (session->inc_ssrc_candidate == ssrc) { session->inc_same_ssrc_count++; - }else{ - session->inc_same_ssrc_count=0; - session->inc_ssrc_candidate=ssrc; + } else { + session->inc_same_ssrc_count = 0; + session->inc_ssrc_candidate = ssrc; } - if (session->inc_same_ssrc_count>=session->rtp.ssrc_changed_thres){ + if (session->inc_same_ssrc_count >= session->rtp.ssrc_changed_thres) { /* store the sender rtp address to do symmetric RTP */ - rtp_session_update_remote_sock_addr(session,mp,TRUE,FALSE); + rtp_session_update_remote_sock_addr(session, mp, TRUE, FALSE); session->rtp.rcv_last_ts = timestamp; - session->rcv.ssrc=ssrc; + session->rcv.ssrc = ssrc; rtp_signal_table_emit(&session->on_ssrc_changed); - }else{ + } else { /*discard the packet*/ ortp_debug("Receiving packet with unknown ssrc."); stats->bad++; @@ -267,23 +260,23 @@ void rtp_session_rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_t freemsg(mp); return; } - } else{ + } else { /* The SSRC change must not happen if we still receive ssrc from the initial source. */ - session->inc_same_ssrc_count=0; + session->inc_same_ssrc_count = 0; } - }else{ - session->ssrc_set=TRUE; - session->rcv.ssrc=ssrc; - rtp_session_update_remote_sock_addr(session,mp,TRUE,FALSE); + } else { + session->ssrc_set = TRUE; + session->rcv.ssrc = ssrc; + rtp_session_update_remote_sock_addr(session, mp, TRUE, FALSE); } /* update some statistics */ { - poly32_t *extseq = (poly32_t*)&rtpstream->hwrcv_extseq; + poly32_t *extseq = (poly32_t *)&rtpstream->hwrcv_extseq; if (seq_number > extseq->split.lo) { extseq->split.lo = seq_number; - } else if (seq_number < 200 && extseq->split.lo > ((1<<16) - 200)) { + } else if (seq_number < 200 && extseq->split.lo > ((1 << 16) - 200)) { /* this is a check for sequence number looping */ extseq->split.lo = seq_number; extseq->split.hi++; @@ -296,19 +289,19 @@ void rtp_session_rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_t rtpstream->hwrcv_seq_at_last_SR = seq_number - 1; session->rtcp_xr_stats.rcv_seq_at_last_stat_summary = seq_number - 1; } - if (stats->packet_recv==1){ - session->rtcp_xr_stats.first_rcv_seq=extseq->one; + if (stats->packet_recv == 1) { + session->rtcp_xr_stats.first_rcv_seq = extseq->one; } - session->rtcp_xr_stats.last_rcv_seq=extseq->one; + session->rtcp_xr_stats.last_rcv_seq = extseq->one; } /* check for possible telephone events */ - if (rtp_profile_is_telephone_event(session->snd.profile, rtp->paytype)){ - queue_packet(&session->rtp.tev_rq,session->rtp.jittctl.params.max_packets,mp,rtp,&discarded,&duplicate); - stats->discarded+=discarded; - ortp_global_stats.discarded+=discarded; - stats->packet_dup_recv+=duplicate; - ortp_global_stats.packet_dup_recv+=duplicate; + if (rtp_profile_is_telephone_event(session->snd.profile, rtp->paytype)) { + queue_packet(&session->rtp.tev_rq, session->rtp.jittctl.params.max_packets, mp, rtp, &discarded, &duplicate); + stats->discarded += discarded; + ortp_global_stats.discarded += discarded; + stats->packet_dup_recv += duplicate; + ortp_global_stats.packet_dup_recv += duplicate; session->rtcp_xr_stats.discarded_count += discarded; session->rtcp_xr_stats.dup_since_last_stat_summary += duplicate; return; @@ -316,8 +309,8 @@ void rtp_session_rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_t /* check for possible payload type change, in order to update accordingly our clock-rate dependant parameters */ - if (session->hw_recv_pt!=rtp->paytype){ - rtp_session_update_payload_type(session,rtp->paytype); + if (session->hw_recv_pt != rtp->paytype) { + rtp_session_update_payload_type(session, rtp->paytype); } /* Drop the packets while the RTP_SESSION_FLUSH flag is set. */ @@ -326,19 +319,20 @@ void rtp_session_rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_t return; } - jitter_control_new_packet(&session->rtp.jittctl,timestamp,local_str_ts); + jitter_control_new_packet(&session->rtp.jittctl, timestamp, local_str_ts); if (session->video_bandwidth_estimator_enabled && session->rtp.video_bw_estimator) { int overhead = ortp_stream_is_ipv6(&session->rtp.gs) ? IP6_UDP_OVERHEAD : IP_UDP_OVERHEAD; - ortp_video_bandwidth_estimator_process_packet(session->rtp.video_bw_estimator, timestamp, &mp->timestamp, msgsize + overhead, rtp->markbit == 1); + ortp_video_bandwidth_estimator_process_packet(session->rtp.video_bw_estimator, timestamp, &mp->timestamp, + msgsize + overhead, rtp->markbit == 1); } - if (session->congestion_detector_enabled && session->rtp.congdetect){ - if (ortp_congestion_detector_record(session->rtp.congdetect,timestamp,local_str_ts)) { - OrtpEvent *ev=ortp_event_new(ORTP_EVENT_CONGESTION_STATE_CHANGED); - OrtpEventData *ed=ortp_event_get_data(ev); + if (session->congestion_detector_enabled && session->rtp.congdetect) { + if (ortp_congestion_detector_record(session->rtp.congdetect, timestamp, local_str_ts)) { + OrtpEvent *ev = ortp_event_new(ORTP_EVENT_CONGESTION_STATE_CHANGED); + OrtpEventData *ed = ortp_event_get_data(ev); ed->info.congestion_detected = session->rtp.congdetect->state == CongestionStateDetected; - rtp_session_dispatch_event(session,ev); + rtp_session_dispatch_event(session, ev); } } @@ -346,24 +340,23 @@ void rtp_session_rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_t if (session->flags & RTP_SESSION_FIRST_PACKET_DELIVERED) { /* detect timestamp important jumps in the future, to workaround stupid rtp senders */ - if (RTP_TIMESTAMP_IS_NEWER_THAN(timestamp,session->rtp.rcv_last_ts+session->rtp.ts_jump)){ + if (RTP_TIMESTAMP_IS_NEWER_THAN(timestamp, session->rtp.rcv_last_ts + session->rtp.ts_jump)) { ortp_warning("rtp_parse: timestamp jump in the future detected."); - rtp_signal_table_emit2(&session->on_timestamp_jump,×tamp); - } - else if (RTP_TIMESTAMP_IS_STRICTLY_NEWER_THAN(session->rtp.rcv_last_ts,timestamp) - || RTP_SEQ_IS_STRICTLY_GREATER_THAN(session->rtp.rcv_last_seq, seq_number)) { + rtp_signal_table_emit2(&session->on_timestamp_jump, ×tamp); + } else if (RTP_TIMESTAMP_IS_STRICTLY_NEWER_THAN(session->rtp.rcv_last_ts, timestamp) || + RTP_SEQ_IS_STRICTLY_GREATER_THAN(session->rtp.rcv_last_seq, seq_number)) { /* don't queue packets older than the last returned packet to the application, or whose sequence number is behind the last packet returned to the application*/ /* Call timestamp jump in case of * large negative Ts jump or if ts is set to 0 */ - if ( RTP_TIMESTAMP_IS_STRICTLY_NEWER_THAN(session->rtp.rcv_last_ts, timestamp + session->rtp.ts_jump) ){ + if (RTP_TIMESTAMP_IS_STRICTLY_NEWER_THAN(session->rtp.rcv_last_ts, timestamp + session->rtp.ts_jump)) { ortp_warning("rtp_parse: negative timestamp jump detected"); rtp_signal_table_emit2(&session->on_timestamp_jump, ×tamp); } - ortp_error("rtp_parse: discarding too old packet (seq=%i, ts=%u, last_delivered was seq=%i, ts=%u)", seq_number, timestamp, - (int)session->rtp.rcv_last_seq, session->rtp.rcv_last_ts); + ortp_error("rtp_parse: discarding too old packet (seq=%i, ts=%u, last_delivered was seq=%i, ts=%u)", + seq_number, timestamp, (int)session->rtp.rcv_last_seq, session->rtp.rcv_last_ts); freemsg(mp); stats->outoftime++; ortp_global_stats.outoftime++; @@ -372,9 +365,9 @@ void rtp_session_rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_t } } - if ((rtp_session_avpf_enabled(session) == TRUE) - && (rtp_session_avpf_feature_enabled(session, ORTP_AVPF_FEATURE_GENERIC_NACK) == TRUE) - && (rtp_session_avpf_feature_enabled(session, ORTP_AVPF_FEATURE_IMMEDIATE_NACK) == TRUE)) { + if ((rtp_session_avpf_enabled(session) == TRUE) && + (rtp_session_avpf_feature_enabled(session, ORTP_AVPF_FEATURE_GENERIC_NACK) == TRUE) && + (rtp_session_avpf_feature_enabled(session, ORTP_AVPF_FEATURE_IMMEDIATE_NACK) == TRUE)) { /* * If immediate nack is enabled then we check for missing packets here instead of * rtp_session_recvm_with_ts @@ -386,18 +379,16 @@ void rtp_session_rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_t // { // fec_stream_on_new_packet_recieved(session->fec_stream, mp); // } - - - if (queue_packet(&session->rtp.rq,session->rtp.jittctl.params.max_packets,mp,rtp,&discarded,&duplicate)) - jitter_control_update_size(&session->rtp.jittctl,&session->rtp.rq); - stats->discarded+=discarded; - ortp_global_stats.discarded+=discarded; - stats->packet_dup_recv+=duplicate; - ortp_global_stats.packet_dup_recv+=duplicate; + + if (queue_packet(&session->rtp.rq, session->rtp.jittctl.params.max_packets, mp, rtp, &discarded, &duplicate)) + jitter_control_update_size(&session->rtp.jittctl, &session->rtp.rq); + stats->discarded += discarded; + ortp_global_stats.discarded += discarded; + stats->packet_dup_recv += duplicate; + ortp_global_stats.packet_dup_recv += duplicate; session->rtcp_xr_stats.discarded_count += discarded; session->rtcp_xr_stats.dup_since_last_stat_summary += duplicate; if ((discarded == 0) && (duplicate == 0)) { session->rtcp_xr_stats.rcv_count++; } - } diff --git a/src/rtpprofile.c b/src/rtpprofile.c index e036d84e..c804a22c 100644 --- a/src/rtpprofile.c +++ b/src/rtpprofile.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -21,14 +21,11 @@ #include "ortp/ortp.h" #include - -int rtp_profile_get_payload_number_from_mime(RtpProfile *profile, const char *mime) -{ +int rtp_profile_get_payload_number_from_mime(RtpProfile *profile, const char *mime) { return rtp_profile_get_payload_number_from_mime_and_flag(profile, mime, -1); } -int rtp_profile_get_payload_number_from_mime_and_flag(RtpProfile *profile, const char *mime, int flag) -{ +int rtp_profile_get_payload_number_from_mime_and_flag(RtpProfile *profile, const char *mime, int flag) { PayloadType *pt; int i; for (i = 0; i < RTP_PROFILE_MAX_PAYLOADS; i++) { @@ -44,18 +41,14 @@ int rtp_profile_get_payload_number_from_mime_and_flag(RtpProfile *profile, const return -1; } -int rtp_profile_find_payload_number(RtpProfile*profile,const char *mime,int rate,int channels) -{ +int rtp_profile_find_payload_number(RtpProfile *profile, const char *mime, int rate, int channels) { int i; PayloadType *pt; - for (i=0;imime_type,mime)==0 && - pt->clock_rate==rate && - (pt->channels==channels || channels<=0 || pt->channels<=0)) { + for (i = 0; i < RTP_PROFILE_MAX_PAYLOADS; i++) { + pt = rtp_profile_get_payload(profile, i); + if (pt != NULL) { + if (strcasecmp(pt->mime_type, mime) == 0 && pt->clock_rate == rate && + (pt->channels == channels || channels <= 0 || pt->channels <= 0)) { /*we don't look at channels if it is undefined ie a negative or zero value*/ return i; @@ -65,22 +58,21 @@ int rtp_profile_find_payload_number(RtpProfile*profile,const char *mime,int rate return -1; } -int rtp_profile_get_payload_number_from_rtpmap(RtpProfile *profile,const char *rtpmap) -{ +int rtp_profile_get_payload_number_from_rtpmap(RtpProfile *profile, const char *rtpmap) { int clock_rate, channels, ret; - char* subtype = ortp_strdup( rtpmap ); - char* rate_str = NULL; - char* chan_str = NULL; + char *subtype = ortp_strdup(rtpmap); + char *rate_str = NULL; + char *chan_str = NULL; /* find the slash after the subtype */ rate_str = strchr(subtype, '/'); - if (rate_str && strlen(rate_str)>1) { + if (rate_str && strlen(rate_str) > 1) { *rate_str = 0; rate_str++; /* Look for another slash */ chan_str = strchr(rate_str, '/'); - if (chan_str && strlen(chan_str)>1) { + if (chan_str && strlen(chan_str) > 1) { *chan_str = 0; chan_str++; } else { @@ -98,55 +90,49 @@ int rtp_profile_get_payload_number_from_rtpmap(RtpProfile *profile,const char *r if (chan_str) channels = atoi(chan_str); else channels = -1; - //printf("Searching for payload %s at freq %i with %i channels\n",subtype,clock_rate,ch1annels); - ret=rtp_profile_find_payload_number(profile,subtype,clock_rate,channels); + // printf("Searching for payload %s at freq %i with %i channels\n",subtype,clock_rate,ch1annels); + ret = rtp_profile_find_payload_number(profile, subtype, clock_rate, channels); ortp_free(subtype); return ret; } -PayloadType * rtp_profile_find_payload(RtpProfile *prof,const char *mime,int rate,int channels) -{ +PayloadType *rtp_profile_find_payload(RtpProfile *prof, const char *mime, int rate, int channels) { int i; - i=rtp_profile_find_payload_number(prof,mime,rate,channels); - if (i>=0) return rtp_profile_get_payload(prof,i); + i = rtp_profile_find_payload_number(prof, mime, rate, channels); + if (i >= 0) return rtp_profile_get_payload(prof, i); return NULL; } - -PayloadType * rtp_profile_get_payload_from_mime(RtpProfile *profile,const char *mime) -{ +PayloadType *rtp_profile_get_payload_from_mime(RtpProfile *profile, const char *mime) { int pt; - pt=rtp_profile_get_payload_number_from_mime(profile,mime); - if (pt==-1) return NULL; - else return rtp_profile_get_payload(profile,pt); + pt = rtp_profile_get_payload_number_from_mime(profile, mime); + if (pt == -1) return NULL; + else return rtp_profile_get_payload(profile, pt); } - -PayloadType * rtp_profile_get_payload_from_rtpmap(RtpProfile *profile, const char *rtpmap) -{ - int pt = rtp_profile_get_payload_number_from_rtpmap(profile,rtpmap); - if (pt==-1) return NULL; - else return rtp_profile_get_payload(profile,pt); +PayloadType *rtp_profile_get_payload_from_rtpmap(RtpProfile *profile, const char *rtpmap) { + int pt = rtp_profile_get_payload_number_from_rtpmap(profile, rtpmap); + if (pt == -1) return NULL; + else return rtp_profile_get_payload(profile, pt); } -int rtp_profile_move_payload(RtpProfile *prof,int oldpos,int newpos){ - if (oldpos<0 || oldpos>=RTP_PROFILE_MAX_PAYLOADS) { - ortp_error("Bad old pos index %i",oldpos); +int rtp_profile_move_payload(RtpProfile *prof, int oldpos, int newpos) { + if (oldpos < 0 || oldpos >= RTP_PROFILE_MAX_PAYLOADS) { + ortp_error("Bad old pos index %i", oldpos); return -1; } - if (newpos<0 || newpos>=RTP_PROFILE_MAX_PAYLOADS) { - ortp_error("Bad new pos index %i",newpos); + if (newpos < 0 || newpos >= RTP_PROFILE_MAX_PAYLOADS) { + ortp_error("Bad new pos index %i", newpos); return -1; } - prof->payload[newpos]=prof->payload[oldpos]; - prof->payload[oldpos]=NULL; + prof->payload[newpos] = prof->payload[oldpos]; + prof->payload[oldpos] = NULL; return 0; } -RtpProfile * rtp_profile_new(const char *name) -{ - RtpProfile *prof=(RtpProfile*)ortp_new0(RtpProfile,1); - rtp_profile_set_name(prof,name); +RtpProfile *rtp_profile_new(const char *name) { + RtpProfile *prof = (RtpProfile *)ortp_new0(RtpProfile, 1); + rtp_profile_set_name(prof, name); return prof; } @@ -156,83 +142,76 @@ RtpProfile * rtp_profile_new(const char *name) * @param idx the payload type number * @param pt the payload type description * -**/ -void rtp_profile_set_payload(RtpProfile *profile, int idx, PayloadType *pt){ - if (idx<0 || idx>=RTP_PROFILE_MAX_PAYLOADS) { - ortp_error("Bad index %i",idx); + **/ +void rtp_profile_set_payload(RtpProfile *profile, int idx, PayloadType *pt) { + if (idx < 0 || idx >= RTP_PROFILE_MAX_PAYLOADS) { + ortp_error("Bad index %i", idx); return; } - profile->payload[idx]=pt; + profile->payload[idx] = pt; } /** * Initialize the profile to the empty profile (all payload type are unassigned). *@param profile a RTP profile * -**/ -void rtp_profile_clear_all(RtpProfile *profile){ + **/ +void rtp_profile_clear_all(RtpProfile *profile) { int i; - for (i=0;ipayload[i]=0; + for (i = 0; i < RTP_PROFILE_MAX_PAYLOADS; i++) { + profile->payload[i] = 0; } } - /** * Set a name to the rtp profile. (This is not required) * @param profile a rtp profile object * @param name a string * -**/ -void rtp_profile_set_name(RtpProfile *profile, const char *name){ - if (profile->name!=NULL) ortp_free(profile->name); - profile->name=ortp_strdup(name); + **/ +void rtp_profile_set_name(RtpProfile *profile, const char *name) { + if (profile->name != NULL) ortp_free(profile->name); + profile->name = ortp_strdup(name); } /* ! payload are not cloned*/ -RtpProfile * rtp_profile_clone(RtpProfile *prof) -{ +RtpProfile *rtp_profile_clone(RtpProfile *prof) { int i; PayloadType *pt; - RtpProfile *newprof=rtp_profile_new(prof->name); - for (i=0;iname); + for (i = 0; i < RTP_PROFILE_MAX_PAYLOADS; i++) { + pt = rtp_profile_get_payload(prof, i); + if (pt != NULL) { + rtp_profile_set_payload(newprof, i, pt); } } return newprof; } - /*clone a profile and its payloads */ -RtpProfile * rtp_profile_clone_full(RtpProfile *prof) -{ +RtpProfile *rtp_profile_clone_full(RtpProfile *prof) { int i; PayloadType *pt; - RtpProfile *newprof=rtp_profile_new(prof->name); - for (i=0;iname); + for (i = 0; i < RTP_PROFILE_MAX_PAYLOADS; i++) { + pt = rtp_profile_get_payload(prof, i); + if (pt != NULL) { + rtp_profile_set_payload(newprof, i, payload_type_clone(pt)); } } return newprof; } -void rtp_profile_destroy(RtpProfile *prof) -{ +void rtp_profile_destroy(RtpProfile *prof) { int i; PayloadType *payload; if (prof->name) { ortp_free(prof->name); prof->name = NULL; } - for (i=0;iflags & PAYLOAD_TYPE_ALLOCATED)) - payload_type_destroy(payload); + for (i = 0; i < RTP_PROFILE_MAX_PAYLOADS; i++) { + payload = rtp_profile_get_payload(prof, i); + if (payload != NULL && (payload->flags & PAYLOAD_TYPE_ALLOCATED)) payload_type_destroy(payload); } ortp_free(prof); } diff --git a/src/rtpsession.c b/src/rtpsession.c index 0af57784..0b8145d1 100644 --- a/src/rtpsession.c +++ b/src/rtpsession.c @@ -18,6 +18,8 @@ * along with this program. If not, see . */ +#include + #ifdef HAVE_CONFIG_H #include "ortp-config.h" #endif @@ -2779,8 +2781,10 @@ int meta_rtp_transport_modifier_inject_packet_to_send_to( return ret; } -static int -_meta_rtp_transport_recv_through_modifiers(RtpTransport *t, RtpTransportModifier *tpm, mblk_t *msg, int flags) { +static int _meta_rtp_transport_recv_through_modifiers(RtpTransport *t, + RtpTransportModifier *tpm, + mblk_t *msg, + BCTBX_UNUSED(int flags)) { int ret = 0; size_t prev_ret; bool_t foundMyself = tpm ? FALSE : TRUE; /*if no modifier, start from the beginning*/ diff --git a/src/rtpsession_inet.c b/src/rtpsession_inet.c index 314ee2a4..d65bbdb8 100644 --- a/src/rtpsession_inet.c +++ b/src/rtpsession_inet.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,7 +18,6 @@ * along with this program. If not, see . */ - #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif @@ -30,11 +29,12 @@ #ifdef HAVE_CONFIG_H #include "ortp-config.h" /*needed for HAVE_SYS_UIO_H and HAVE_ARC4RANDOM */ #endif -#include #include "ortp/ortp.h" #include "ortp/str_utils.h" -#include "utils.h" #include "rtpsession_priv.h" +#include "utils.h" +#include +#include #if (_WIN32_WINNT >= 0x0600) #include @@ -48,11 +48,13 @@ #if (defined(_WIN32) || defined(_WIN32_WCE)) && defined(ORTP_WINDOWS_DESKTOP) #include #include -// On Windows, SO_TIMESTAMP is only defined if NTDDI_VERSION >= NTDDI_WIN10_FE. ie: it is only available for Windows10 20h2 (10/08/2020). -// => CMakeLists.txt may add add_definitions(-DNTDDI_VERSION=NTDDI_WIN10_FE -D_WIN32_WINNT=0x0A00) to limit minimum version. -// From this version, we can read the timestamp through the SIO_TIMESTAMPING IOCTL. https://docs.microsoft.com/en-us/windows/win32/winsock/winsock-timestamping -// This is not currently implemented because of unworking WSAIoctl and undocumented failures (usually WSAEOPNOTSUPP=10045). -// Check of "WSAIoctl configured successfully timestamping" in logs to look forward on success cases. +// On Windows, SO_TIMESTAMP is only defined if NTDDI_VERSION >= NTDDI_WIN10_FE. ie: it is only available for Windows10 +// 20h2 (10/08/2020). +// => CMakeLists.txt may add add_definitions(-DNTDDI_VERSION=NTDDI_WIN10_FE -D_WIN32_WINNT=0x0A00) to limit minimum +// version. From this version, we can read the timestamp through the SIO_TIMESTAMPING IOCTL. +// https://docs.microsoft.com/en-us/windows/win32/winsock/winsock-timestamping This is not currently implemented because +// of unworking WSAIoctl and undocumented failures (usually WSAEOPNOTSUPP=10045). Check of "WSAIoctl configured +// successfully timestamping" in logs to look forward on success cases. #include #endif @@ -62,7 +64,7 @@ #elif defined(SO_TIMESTAMP) #define _RECV_SO_TIMESTAMP_TYPE SO_TIMESTAMP #else -#undef _RECV_SO_TIMESTAMP_TYPE // Just in case +#undef _RECV_SO_TIMESTAMP_TYPE // Just in case #endif #ifdef HAVE_SYS_UIO_H @@ -75,30 +77,47 @@ #endif #endif -#define can_connect(s) ( (s)->use_connect && !(s)->symmetric_rtp) +#define can_connect(s) ((s)->use_connect && !(s)->symmetric_rtp) #if defined(_WIN32) || defined(_WIN32_WCE) #ifndef WSAID_WSARECVMSG /* http://source.winehq.org/git/wine.git/blob/HEAD:/include/mswsock.h */ -#define WSAID_WSARECVMSG {0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}} +#define WSAID_WSARECVMSG \ + { \ + 0xf689d7c8, 0x6f1f, 0x436b, { \ + 0x8a, 0x53, 0xe5, 0x4f, 0xe3, 0x51, 0xc3, 0x22 \ + } \ + } #ifndef MAX_NATURAL_ALIGNMENT #define MAX_NATURAL_ALIGNMENT sizeof(DWORD) #endif #ifndef TYPE_ALIGNMENT -#define TYPE_ALIGNMENT(t) FIELD_OFFSET(struct { char x; t test; },test) +#define TYPE_ALIGNMENT(t) \ + FIELD_OFFSET( \ + struct { \ + char x; \ + t test; \ + }, \ + test) #endif typedef WSACMSGHDR *LPWSACMSGHDR; #ifndef WSA_CMSGHDR_ALIGN -#define WSA_CMSGHDR_ALIGN(length) (((length) + TYPE_ALIGNMENT(WSACMSGHDR)-1) & (~(TYPE_ALIGNMENT(WSACMSGHDR)-1))) +#define WSA_CMSGHDR_ALIGN(length) (((length) + TYPE_ALIGNMENT(WSACMSGHDR) - 1) & (~(TYPE_ALIGNMENT(WSACMSGHDR) - 1))) #endif #ifndef WSA_CMSGDATA_ALIGN -#define WSA_CMSGDATA_ALIGN(length) (((length) + MAX_NATURAL_ALIGNMENT-1) & (~(MAX_NATURAL_ALIGNMENT-1))) +#define WSA_CMSGDATA_ALIGN(length) (((length) + MAX_NATURAL_ALIGNMENT - 1) & (~(MAX_NATURAL_ALIGNMENT - 1))) #endif #ifndef WSA_CMSG_FIRSTHDR -#define WSA_CMSG_FIRSTHDR(msg) (((msg)->Control.len >= sizeof(WSACMSGHDR)) ? (LPWSACMSGHDR)(msg)->Control.buf : (LPWSACMSGHDR)NULL) +#define WSA_CMSG_FIRSTHDR(msg) \ + (((msg)->Control.len >= sizeof(WSACMSGHDR)) ? (LPWSACMSGHDR)(msg)->Control.buf : (LPWSACMSGHDR)NULL) #endif #ifndef WSA_CMSG_NXTHDR -#define WSA_CMSG_NXTHDR(msg,cmsg) ((!(cmsg)) ? WSA_CMSG_FIRSTHDR(msg) : ((((u_char *)(cmsg) + WSA_CMSGHDR_ALIGN((cmsg)->cmsg_len) + sizeof(WSACMSGHDR)) > (u_char *)((msg)->Control.buf) + (msg)->Control.len) ? (LPWSACMSGHDR)NULL : (LPWSACMSGHDR)((u_char *)(cmsg) + WSA_CMSGHDR_ALIGN((cmsg)->cmsg_len)))) +#define WSA_CMSG_NXTHDR(msg, cmsg) \ + ((!(cmsg)) ? WSA_CMSG_FIRSTHDR(msg) \ + : ((((u_char *)(cmsg) + WSA_CMSGHDR_ALIGN((cmsg)->cmsg_len) + sizeof(WSACMSGHDR)) > \ + (u_char *)((msg)->Control.buf) + (msg)->Control.len) \ + ? (LPWSACMSGHDR)NULL \ + : (LPWSACMSGHDR)((u_char *)(cmsg) + WSA_CMSGHDR_ALIGN((cmsg)->cmsg_len)))) #endif #ifndef WSA_CMSG_DATA #define WSA_CMSG_DATA(cmsg) ((u_char *)(cmsg) + WSA_CMSGDATA_ALIGN(sizeof(WSACMSGHDR))) @@ -110,40 +129,41 @@ typedef WSACMSGHDR *LPWSACMSGHDR; #define CMSG_NXTHDR WSA_CMSG_NXTHDR #undef CMSG_DATA #define CMSG_DATA WSA_CMSG_DATA -typedef INT (WINAPI * LPFN_WSARECVMSG)(SOCKET, LPWSAMSG, LPDWORD, LPWSAOVERLAPPED, LPWSAOVERLAPPED_COMPLETION_ROUTINE); +typedef INT(WINAPI *LPFN_WSARECVMSG)(SOCKET, LPWSAMSG, LPDWORD, LPWSAOVERLAPPED, LPWSAOVERLAPPED_COMPLETION_ROUTINE); static LPFN_WSARECVMSG ortp_WSARecvMsg = NULL; #endif #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__QNX__) -/* Mingw32 does not define AI_V4MAPPED, however it is supported starting from Windows Vista. QNX also does not define AI_V4MAPPED. */ -# ifndef AI_V4MAPPED -# define AI_V4MAPPED 0x00000800 -# endif -# ifndef AI_ALL -# define AI_ALL 0x00000100 -# endif -# ifndef IPV6_V6ONLY -# define IPV6_V6ONLY 27 -# endif +/* Mingw32 does not define AI_V4MAPPED, however it is supported starting from Windows Vista. QNX also does not define + * AI_V4MAPPED. */ +#ifndef AI_V4MAPPED +#define AI_V4MAPPED 0x00000800 +#endif +#ifndef AI_ALL +#define AI_ALL 0x00000100 +#endif +#ifndef IPV6_V6ONLY +#define IPV6_V6ONLY 27 +#endif #endif #ifndef IN6_IS_ADDR_MULTICAST -#define IN6_IS_ADDR_MULTICAST(i) (((uint8_t *) (i))[0] == 0xff) +#define IN6_IS_ADDR_MULTICAST(i) (((uint8_t *)(i))[0] == 0xff) #endif -static int -_rtp_session_set_remote_addr_full (RtpSession * session, const char * rtp_addr, int rtp_port, const char * rtcp_addr, int rtcp_port, bool_t is_aux); +static int _rtp_session_set_remote_addr_full( + RtpSession *session, const char *rtp_addr, int rtp_port, const char *rtcp_addr, int rtcp_port, bool_t is_aux); -static bool_t try_connect(ortp_socket_t fd, const struct sockaddr *dest, socklen_t addrlen){ - if (connect(fd,dest,addrlen)<0){ - ortp_warning("Could not connect() socket: %s",getSocketError()); +static bool_t try_connect(ortp_socket_t fd, const struct sockaddr *dest, socklen_t addrlen) { + if (connect(fd, dest, addrlen) < 0) { + ortp_warning("Could not connect() socket: %s", getSocketError()); return FALSE; } return TRUE; } -static int set_multicast_group(ortp_socket_t sock, const char *addr){ +static int set_multicast_group(ortp_socket_t sock, const char *addr) { #ifndef __hpux struct addrinfo *res; int err; @@ -151,35 +171,33 @@ static int set_multicast_group(ortp_socket_t sock, const char *addr){ res = bctbx_name_to_addrinfo(AF_UNSPEC, SOCK_DGRAM, addr, 0); if (res == NULL) return -1; - switch (res->ai_family){ + switch (res->ai_family) { case AF_INET: - if (IN_MULTICAST(ntohl(((struct sockaddr_in *) res->ai_addr)->sin_addr.s_addr))) - { + if (IN_MULTICAST(ntohl(((struct sockaddr_in *)res->ai_addr)->sin_addr.s_addr))) { struct ip_mreq mreq; - mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *) res->ai_addr)->sin_addr.s_addr; + mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr.s_addr; mreq.imr_interface.s_addr = INADDR_ANY; - err = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (SOCKET_OPTION_VALUE) &mreq, sizeof(mreq)); - if (err < 0){ - ortp_warning ("Fail to join address group: %s.", getSocketError()); + err = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (SOCKET_OPTION_VALUE)&mreq, sizeof(mreq)); + if (err < 0) { + ortp_warning("Fail to join address group: %s.", getSocketError()); } else { - ortp_message ("RTP socket [%i] has joined address group [%s]",sock, addr); + ortp_message("RTP socket [%i] has joined address group [%s]", sock, addr); } } - break; + break; case AF_INET6: - if IN6_IS_ADDR_MULTICAST(&(((struct sockaddr_in6 *) res->ai_addr)->sin6_addr)) - { + if IN6_IS_ADDR_MULTICAST (&(((struct sockaddr_in6 *)res->ai_addr)->sin6_addr)) { struct ipv6_mreq mreq; - mreq.ipv6mr_multiaddr = ((struct sockaddr_in6 *) res->ai_addr)->sin6_addr; + mreq.ipv6mr_multiaddr = ((struct sockaddr_in6 *)res->ai_addr)->sin6_addr; mreq.ipv6mr_interface = 0; err = setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP, (SOCKET_OPTION_VALUE)&mreq, sizeof(mreq)); - if (err < 0 ){ - ortp_warning ("Fail to join address group: %s.", getSocketError()); + if (err < 0) { + ortp_warning("Fail to join address group: %s.", getSocketError()); } else { - ortp_message ("RTP socket 6 [%i] has joined address group [%s]",sock, addr); + ortp_message("RTP socket 6 [%i] has joined address group [%s]", sock, addr); } } - break; + break; } freeaddrinfo(res); return 0; @@ -188,75 +206,76 @@ static int set_multicast_group(ortp_socket_t sock, const char *addr){ #endif } -static ortp_socket_t create_and_bind(const char *addr, int *port, int *sock_family, bool_t reuse_addr,struct sockaddr_storage* bound_addr,socklen_t *bound_addr_len){ +static ortp_socket_t create_and_bind(const char *addr, + int *port, + int *sock_family, + bool_t reuse_addr, + struct sockaddr_storage *bound_addr, + socklen_t *bound_addr_len) { int err; int optval = 1; - ortp_socket_t sock=-1; + ortp_socket_t sock = -1; struct addrinfo *res0, *res; - if (*port==-1) *port=0; - if (*port==0) reuse_addr=FALSE; + if (*port == -1) *port = 0; + if (*port == 0) reuse_addr = FALSE; res0 = bctbx_name_to_addrinfo(AF_UNSPEC, SOCK_DGRAM, addr, *port); - if (res0 == NULL){ + if (res0 == NULL) { ortp_error("Cannot create addrinfo from address [%s], port [%i].", addr, *port); return -1; } for (res = res0; res; res = res->ai_next) { sock = socket(res->ai_family, res->ai_socktype, 0); - if (sock==-1){ - ortp_error("Cannot create a socket with family=[%i] and socktype=[%i]: %s", res->ai_family, res->ai_socktype, getSocketError()); + if (sock == -1) { + ortp_error("Cannot create a socket with family=[%i] and socktype=[%i]: %s", res->ai_family, + res->ai_socktype, getSocketError()); continue; } - if (reuse_addr){ - err = setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, - (SOCKET_OPTION_VALUE)&optval, sizeof (optval)); - if (err < 0) - { - ortp_warning ("Fail to set rtp address reusable: %s.", getSocketError()); + if (reuse_addr) { + err = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (SOCKET_OPTION_VALUE)&optval, sizeof(optval)); + if (err < 0) { + ortp_warning("Fail to set rtp address reusable: %s.", getSocketError()); } #ifdef SO_REUSEPORT /*SO_REUSEPORT is required on mac and ios especially for doing multicast*/ - err = setsockopt (sock, SOL_SOCKET, SO_REUSEPORT, - (SOCKET_OPTION_VALUE)&optval, sizeof (optval)); - if (err < 0) - { - ortp_warning ("Fail to set rtp port reusable: %s.", getSocketError()); + err = setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (SOCKET_OPTION_VALUE)&optval, sizeof(optval)); + if (err < 0) { + ortp_warning("Fail to set rtp port reusable: %s.", getSocketError()); } #endif } /*enable dual stack operation, default is enabled on unix, disabled on windows.*/ - if (res->ai_family==AF_INET6){ - optval=0; - err=setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&optval, sizeof(optval)); - if (err < 0){ - ortp_warning ("Fail to IPV6_V6ONLY: %s.",getSocketError()); + if (res->ai_family == AF_INET6) { + optval = 0; + err = setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char *)&optval, sizeof(optval)); + if (err < 0) { + ortp_warning("Fail to IPV6_V6ONLY: %s.", getSocketError()); } } #ifdef SO_TIMESTAMP - optval=1; - err = setsockopt (sock, SOL_SOCKET, SO_TIMESTAMP, - (SOCKET_OPTION_VALUE)&optval, sizeof (optval)); - if (err < 0) - { - ortp_warning ("Fail to set rtp timestamp: %s.",getSocketError()); + optval = 1; + err = setsockopt(sock, SOL_SOCKET, SO_TIMESTAMP, (SOCKET_OPTION_VALUE)&optval, sizeof(optval)); + if (err < 0) { + ortp_warning("Fail to set rtp timestamp: %s.", getSocketError()); } #ifdef _WIN32 DWORD bytes_returned; // Configure tx timestamp reception. - TIMESTAMPING_CONFIG config = { 0 }; + TIMESTAMPING_CONFIG config = {0}; config.Flags |= TIMESTAMPING_FLAG_RX; - if( WSAIoctl( sock, SIO_TIMESTAMPING, &config, sizeof(config), NULL, 0, &bytes_returned, NULL, NULL) == SOCKET_ERROR) { + if (WSAIoctl(sock, SIO_TIMESTAMPING, &config, sizeof(config), NULL, 0, &bytes_returned, NULL, NULL) == + SOCKET_ERROR) { ortp_warning("WSAIoctl cannot configure timestamping %d\n", WSAGetLastError()); - }else { + } else { ortp_message("WSAIoctl configured successfully timestamping with SIO_TIMESTAMPING\n"); } #endif #endif err = 0; - optval=1; + optval = 1; switch (res->ai_family) { default: case AF_INET: @@ -274,12 +293,12 @@ static ortp_socket_t create_and_bind(const char *addr, int *port, int *sock_fami ortp_warning("Fail to set recv TTL/HL socket option: %s.", getSocketError()); } - *sock_family=res->ai_family; + *sock_family = res->ai_family; err = bind(sock, res->ai_addr, (int)res->ai_addrlen); - if (err != 0){ - ortp_error ("Fail to bind rtp/rtcp socket to (addr=%s port=%i) : %s.", addr, *port, getSocketError()); + if (err != 0) { + ortp_error("Fail to bind rtp/rtcp socket to (addr=%s port=%i) : %s.", addr, *port, getSocketError()); close_socket(sock); - sock=-1; + sock = -1; continue; } /*compatibility mode. New applications should use rtp_session_set_multicast_group() instead*/ @@ -293,76 +312,74 @@ static ortp_socket_t create_and_bind(const char *addr, int *port, int *sock_fami if (ortp_WSARecvMsg == NULL) { GUID guid = WSAID_WSARECVMSG; DWORD bytes_returned; - if ( WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid), - &ortp_WSARecvMsg, sizeof(ortp_WSARecvMsg), &bytes_returned, NULL, NULL) == SOCKET_ERROR) { + if (WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid), &ortp_WSARecvMsg, + sizeof(ortp_WSARecvMsg), &bytes_returned, NULL, NULL) == SOCKET_ERROR) { ortp_warning("WSARecvMsg function not found [%d].", WSAGetLastError()); } } #endif - if (sock!=-1){ + if (sock != -1) { struct sockaddr_storage saddr; - socklen_t slen=sizeof(saddr); + socklen_t slen = sizeof(saddr); - set_non_blocking_socket (sock); - err=getsockname(sock,(struct sockaddr*)&saddr,&slen); - if (err==-1){ - ortp_error("getsockname(): %s",getSocketError()); + set_non_blocking_socket(sock); + err = getsockname(sock, (struct sockaddr *)&saddr, &slen); + if (err == -1) { + ortp_error("getsockname(): %s", getSocketError()); close_socket(sock); return (ortp_socket_t)-1; } /*update the bind address, especially useful if requested port was 0 (random)*/ - memcpy(bound_addr,&saddr,slen); - *bound_addr_len=slen; - if (*port==0){ + memcpy(bound_addr, &saddr, slen); + *bound_addr_len = slen; + if (*port == 0) { err = bctbx_sockaddr_to_ip_address((struct sockaddr *)&saddr, slen, NULL, 0, port); - if (err!=0){ + if (err != 0) { close_socket(sock); return (ortp_socket_t)-1; } } - } return sock; } -void _rtp_session_apply_socket_sizes(RtpSession * session){ +void _rtp_session_apply_socket_sizes(RtpSession *session) { int err; - bool_t done=FALSE; + bool_t done = FALSE; ortp_socket_t sock = session->rtp.gs.socket; unsigned int sndbufsz = session->rtp.snd_socket_size; unsigned int rcvbufsz = session->rtp.rcv_socket_size; if (sock == (ortp_socket_t)-1) return; - if (sndbufsz>0){ + if (sndbufsz > 0) { #ifdef SO_SNDBUFFORCE err = setsockopt(sock, SOL_SOCKET, SO_SNDBUFFORCE, (void *)&sndbufsz, sizeof(sndbufsz)); if (err == -1) { ortp_warning("Fail to increase socket's send buffer size with SO_SNDBUFFORCE: %s.", getSocketError()); - }else done=TRUE; + } else done = TRUE; #endif - if (!done){ + if (!done) { err = setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *)&sndbufsz, sizeof(sndbufsz)); if (err == -1) { ortp_error("Fail to increase socket's send buffer size with SO_SNDBUF: %s.", getSocketError()); } } } - done=FALSE; - if (rcvbufsz>0){ + done = FALSE; + if (rcvbufsz > 0) { #ifdef SO_RCVBUFFORCE err = setsockopt(sock, SOL_SOCKET, SO_RCVBUFFORCE, (void *)&rcvbufsz, sizeof(rcvbufsz)); if (err == -1) { ortp_warning("Fail to increase socket's recv buffer size with SO_RCVBUFFORCE: %s.", getSocketError()); } #endif - if (!done){ + if (!done) { err = setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbufsz, sizeof(rcvbufsz)); if (err == -1) { ortp_error("Fail to increase socket's recv buffer size with SO_RCVBUF: %s.", getSocketError()); } } - } } @@ -380,62 +397,63 @@ void _rtp_session_apply_socket_sizes(RtpSession * session){ * rtp_session_set_local_addr() is mandatory when the session is recv-only or duplex. * * Returns: 0 on success. -**/ + **/ -int -rtp_session_set_local_addr (RtpSession * session, const char * addr, int rtp_port, int rtcp_port) -{ +int rtp_session_set_local_addr(RtpSession *session, const char *addr, int rtp_port, int rtcp_port) { ortp_socket_t sock; int sockfamily; // Stop async rtp recv thread before recreating the socket rtp_session_reset_recvfrom(session); - if (session->rtp.gs.socket!=(ortp_socket_t)-1){ + if (session->rtp.gs.socket != (ortp_socket_t)-1) { /* don't rebind, but close before*/ _rtp_session_release_sockets(session, FALSE); } /* try to bind the rtp port */ - sock=create_and_bind(addr,&rtp_port,&sockfamily,session->reuseaddr,&session->rtp.gs.loc_addr,&session->rtp.gs.loc_addrlen); - if (sock!=-1){ - session->rtp.gs.sockfamily=sockfamily; - session->rtp.gs.socket=sock; - session->rtp.gs.loc_port=rtp_port; + sock = create_and_bind(addr, &rtp_port, &sockfamily, session->reuseaddr, &session->rtp.gs.loc_addr, + &session->rtp.gs.loc_addrlen); + if (sock != -1) { + session->rtp.gs.sockfamily = sockfamily; + session->rtp.gs.socket = sock; + session->rtp.gs.loc_port = rtp_port; _rtp_session_apply_socket_sizes(session); /*try to bind rtcp port */ - sock=create_and_bind(addr,&rtcp_port,&sockfamily,session->reuseaddr,&session->rtcp.gs.loc_addr,&session->rtcp.gs.loc_addrlen); - if (sock!=(ortp_socket_t)-1){ - session->rtcp.gs.sockfamily=sockfamily; - session->rtcp.gs.socket=sock; - session->rtcp.gs.loc_port=rtcp_port; - }else { - ortp_error("Could not create and bind rtcp socket for session [%p]",session); + sock = create_and_bind(addr, &rtcp_port, &sockfamily, session->reuseaddr, &session->rtcp.gs.loc_addr, + &session->rtcp.gs.loc_addrlen); + if (sock != (ortp_socket_t)-1) { + session->rtcp.gs.sockfamily = sockfamily; + session->rtcp.gs.socket = sock; + session->rtcp.gs.loc_port = rtcp_port; + } else { + ortp_error("Could not create and bind rtcp socket for session [%p]", session); return -1; } /* set socket options (but don't change chosen states) */ - rtp_session_set_multicast_ttl( session, -1 ); - rtp_session_set_multicast_loopback( session, -1 ); + rtp_session_set_multicast_ttl(session, -1); + rtp_session_set_multicast_loopback(session, -1); if (session->use_pktinfo) rtp_session_set_pktinfo(session, TRUE); ortp_message("RtpSession bound to [%s] ports [%i] [%i]", addr, rtp_port, rtcp_port); return 0; } - ortp_error("Could not bind RTP socket to %s on port %i for session [%p]",addr,rtp_port,session); + ortp_error("Could not bind RTP socket to %s on port %i for session [%p]", addr, rtp_port, session); return -1; } -static void _rtp_session_recreate_sockets(RtpSession *session){ +static void _rtp_session_recreate_sockets(RtpSession *session) { char addr[NI_MAXHOST]; - int err = bctbx_sockaddr_to_ip_address((struct sockaddr *)&session->rtp.gs.loc_addr, session->rtp.gs.loc_addrlen, addr, sizeof(addr), NULL); + int err = bctbx_sockaddr_to_ip_address((struct sockaddr *)&session->rtp.gs.loc_addr, session->rtp.gs.loc_addrlen, + addr, sizeof(addr), NULL); if (err != 0) return; /*re create and bind sockets as they were done previously*/ ortp_message("RtpSession %p is going to re-create its socket.", session); rtp_session_set_local_addr(session, addr, session->rtp.gs.loc_port, session->rtcp.gs.loc_port); } -static void _rtp_session_check_socket_refresh(RtpSession *session){ - if (session->flags & RTP_SESSION_SOCKET_REFRESH_REQUESTED){ +static void _rtp_session_check_socket_refresh(RtpSession *session) { + if (session->flags & RTP_SESSION_SOCKET_REFRESH_REQUESTED) { session->flags &= ~RTP_SESSION_SOCKET_REFRESH_REQUESTED; _rtp_session_recreate_sockets(session); } @@ -445,21 +463,22 @@ static void _rtp_session_check_socket_refresh(RtpSession *session){ * Requests the session to re-create and bind its RTP and RTCP sockets same as they are currently. * This is used when a change in the routing rules of the host or process was made, in order to have * this routing rules change taking effect on the RTP/RTCP packets sent by the session. -**/ -void rtp_session_refresh_sockets(RtpSession *session){ - if (session->rtp.gs.socket != (ortp_socket_t) -1){ + **/ +void rtp_session_refresh_sockets(RtpSession *session) { + if (session->rtp.gs.socket != (ortp_socket_t)-1) { session->flags |= RTP_SESSION_SOCKET_REFRESH_REQUESTED; } } -int rtp_session_join_multicast_group(RtpSession *session, const char *ip){ +int rtp_session_join_multicast_group(RtpSession *session, const char *ip) { int err; - if (session->rtp.gs.socket==(ortp_socket_t)-1){ - ortp_error("rtp_session_set_multicast_group() must be done only on bound sockets, use rtp_session_set_local_addr() first"); + if (session->rtp.gs.socket == (ortp_socket_t)-1) { + ortp_error("rtp_session_set_multicast_group() must be done only on bound sockets, use " + "rtp_session_set_local_addr() first"); return -1; } - err=set_multicast_group(session->rtp.gs.socket,ip); - set_multicast_group(session->rtcp.gs.socket,ip); + err = set_multicast_group(session->rtp.gs.socket, ip); + set_multicast_group(session->rtcp.gs.socket, ip); return err; } @@ -472,9 +491,8 @@ int rtp_session_join_multicast_group(RtpSession *session, const char *ip){ * * Returns: 0 on success. * -**/ -int rtp_session_set_pktinfo(RtpSession *session, int activate) -{ + **/ +int rtp_session_set_pktinfo(RtpSession *session, int activate) { int retval; int optname; #if defined(_WIN32) || defined(_WIN32_WCE) @@ -499,11 +517,11 @@ int rtp_session_set_pktinfo(RtpSession *session, int activate) #endif retval = setsockopt(session->rtp.gs.socket, IPPROTO_IP, optname, optval, optlen); if (retval < 0) { - ortp_warning ("Fail to set IPv4 packet info on RTP socket: %s.", getSocketError()); + ortp_warning("Fail to set IPv4 packet info on RTP socket: %s.", getSocketError()); } retval = setsockopt(session->rtcp.gs.socket, IPPROTO_IP, optname, optval, optlen); if (retval < 0) { - ortp_warning ("Fail to set IPv4 packet info on RTCP socket: %s.", getSocketError()); + ortp_warning("Fail to set IPv4 packet info on RTCP socket: %s.", getSocketError()); } if (session->rtp.gs.sockfamily != AF_INET) { @@ -529,7 +547,6 @@ int rtp_session_set_pktinfo(RtpSession *session, int activate) return retval; } - /** *rtp_session_set_multicast_ttl: *@param session: a rtp session @@ -539,13 +556,12 @@ int rtp_session_set_pktinfo(RtpSession *session, int activate) * * Returns: 0 on success. * -**/ -int rtp_session_set_multicast_ttl(RtpSession *session, int ttl) -{ + **/ +int rtp_session_set_multicast_ttl(RtpSession *session, int ttl) { int retval; // Store new TTL if one is specified - if (ttl>0) session->multicast_ttl = ttl; + if (ttl > 0) session->multicast_ttl = ttl; // Don't do anything if socket hasn't been created yet if (session->rtp.gs.socket == (ortp_socket_t)-1) return 0; @@ -553,50 +569,45 @@ int rtp_session_set_multicast_ttl(RtpSession *session, int ttl) switch (session->rtp.gs.sockfamily) { case AF_INET: { - retval= setsockopt(session->rtp.gs.socket, IPPROTO_IP, IP_MULTICAST_TTL, - (SOCKET_OPTION_VALUE) &session->multicast_ttl, sizeof(session->multicast_ttl)); + retval = setsockopt(session->rtp.gs.socket, IPPROTO_IP, IP_MULTICAST_TTL, + (SOCKET_OPTION_VALUE)&session->multicast_ttl, sizeof(session->multicast_ttl)); - if (retval<0) break; + if (retval < 0) break; - retval= setsockopt(session->rtcp.gs.socket, IPPROTO_IP, IP_MULTICAST_TTL, - (SOCKET_OPTION_VALUE) &session->multicast_ttl, sizeof(session->multicast_ttl)); + retval = setsockopt(session->rtcp.gs.socket, IPPROTO_IP, IP_MULTICAST_TTL, + (SOCKET_OPTION_VALUE)&session->multicast_ttl, sizeof(session->multicast_ttl)); } break; case AF_INET6: { - retval= setsockopt(session->rtp.gs.socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, - (SOCKET_OPTION_VALUE)&session->multicast_ttl, sizeof(session->multicast_ttl)); + retval = setsockopt(session->rtp.gs.socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, + (SOCKET_OPTION_VALUE)&session->multicast_ttl, sizeof(session->multicast_ttl)); - if (retval<0) break; + if (retval < 0) break; - retval= setsockopt(session->rtcp.gs.socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, - (SOCKET_OPTION_VALUE) &session->multicast_ttl, sizeof(session->multicast_ttl)); + retval = setsockopt(session->rtcp.gs.socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, + (SOCKET_OPTION_VALUE)&session->multicast_ttl, sizeof(session->multicast_ttl)); } break; - default: - retval=-1; + default: + retval = -1; } - if (retval<0) - ortp_warning("Failed to set multicast TTL on socket."); - + if (retval < 0) ortp_warning("Failed to set multicast TTL on socket."); return retval; } - /** *rtp_session_get_multicast_ttl: *@param session: a rtp session * * Returns the TTL (Time-To-Live) for outgoing multicast packets. * -**/ -int rtp_session_get_multicast_ttl(RtpSession *session) -{ + **/ +int rtp_session_get_multicast_ttl(RtpSession *session) { return session->multicast_ttl; } - /** *@param session: a rtp session *@param yesno: enable multicast loopback @@ -605,16 +616,15 @@ int rtp_session_get_multicast_ttl(RtpSession *session) * * Returns: 0 on success. * -**/ -int rtp_session_set_multicast_loopback(RtpSession *session, int yesno) -{ + **/ +int rtp_session_set_multicast_loopback(RtpSession *session, int yesno) { int retval; // Store new loopback state if one is specified - if (yesno==0) { + if (yesno == 0) { // Don't loop back session->multicast_loopback = 0; - } else if (yesno>0) { + } else if (yesno > 0) { // Do loop back session->multicast_loopback = 1; } @@ -625,45 +635,42 @@ int rtp_session_set_multicast_loopback(RtpSession *session, int yesno) switch (session->rtp.gs.sockfamily) { case AF_INET: { - retval= setsockopt(session->rtp.gs.socket, IPPROTO_IP, IP_MULTICAST_LOOP, - (SOCKET_OPTION_VALUE) &session->multicast_loopback, sizeof(session->multicast_loopback)); + retval = setsockopt(session->rtp.gs.socket, IPPROTO_IP, IP_MULTICAST_LOOP, + (SOCKET_OPTION_VALUE)&session->multicast_loopback, sizeof(session->multicast_loopback)); - if (retval<0) break; + if (retval < 0) break; - retval= setsockopt(session->rtcp.gs.socket, IPPROTO_IP, IP_MULTICAST_LOOP, - (SOCKET_OPTION_VALUE) &session->multicast_loopback, sizeof(session->multicast_loopback)); + retval = setsockopt(session->rtcp.gs.socket, IPPROTO_IP, IP_MULTICAST_LOOP, + (SOCKET_OPTION_VALUE)&session->multicast_loopback, sizeof(session->multicast_loopback)); } break; case AF_INET6: { - retval= setsockopt(session->rtp.gs.socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, - (SOCKET_OPTION_VALUE) &session->multicast_loopback, sizeof(session->multicast_loopback)); + retval = setsockopt(session->rtp.gs.socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, + (SOCKET_OPTION_VALUE)&session->multicast_loopback, sizeof(session->multicast_loopback)); - if (retval<0) break; + if (retval < 0) break; - retval= setsockopt(session->rtcp.gs.socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, - (SOCKET_OPTION_VALUE) &session->multicast_loopback, sizeof(session->multicast_loopback)); + retval = setsockopt(session->rtcp.gs.socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, + (SOCKET_OPTION_VALUE)&session->multicast_loopback, sizeof(session->multicast_loopback)); } break; - default: - retval=-1; + default: + retval = -1; } - if (retval<0) - ortp_warning("Failed to set multicast loopback on socket."); + if (retval < 0) ortp_warning("Failed to set multicast loopback on socket."); return retval; } - /** *rtp_session_get_multicast_loopback: *@param session: a rtp session * * Returns the multicast loopback state of rtp session (true or false). * -**/ -int rtp_session_get_multicast_loopback(RtpSession *session) -{ + **/ +int rtp_session_get_multicast_loopback(RtpSession *session) { return session->multicast_loopback; } @@ -676,15 +683,15 @@ int rtp_session_get_multicast_loopback(RtpSession *session) * * Returns: 0 on success. * -**/ -int rtp_session_set_dscp(RtpSession *session, int dscp){ - int retval=0; + **/ +int rtp_session_set_dscp(RtpSession *session, int dscp) { + int retval = 0; int tos; int proto; int value_type; // Store new DSCP value if one is specified - if (dscp>=0) session->dscp = dscp; + if (dscp >= 0) session->dscp = dscp; // Don't do anything if socket hasn't been created yet if (session->rtp.gs.socket == (ortp_socket_t)-1) return 0; @@ -693,18 +700,13 @@ int rtp_session_set_dscp(RtpSession *session, int dscp){ #if !defined(ENABLE_MICROSOFT_STORE_APP) && !defined(ORTP_WINDOWS_UWP) ortp_message("check OS support for qwave.lib"); if (IsWindowsVistaOrGreater()) { - if (session->dscp==0) - tos=QOSTrafficTypeBestEffort; - else if (session->dscp==0x8) - tos=QOSTrafficTypeBackground; - else if (session->dscp==0x28) - tos=QOSTrafficTypeAudioVideo; - else if (session->dscp==0x38) - tos=QOSTrafficTypeVoice; - else - tos=QOSTrafficTypeExcellentEffort; /* 0x28 */ - - if (session->rtp.QoSHandle==NULL) { + if (session->dscp == 0) tos = QOSTrafficTypeBestEffort; + else if (session->dscp == 0x8) tos = QOSTrafficTypeBackground; + else if (session->dscp == 0x28) tos = QOSTrafficTypeAudioVideo; + else if (session->dscp == 0x38) tos = QOSTrafficTypeVoice; + else tos = QOSTrafficTypeExcellentEffort; /* 0x28 */ + + if (session->rtp.QoSHandle == NULL) { QOS_VERSION version; BOOL QoSResult; @@ -713,54 +715,49 @@ int rtp_session_set_dscp(RtpSession *session, int dscp){ QoSResult = QOSCreateHandle(&version, &session->rtp.QoSHandle); - if (QoSResult != TRUE){ + if (QoSResult != TRUE) { ortp_error("QOSCreateHandle failed to create handle with error %d", GetLastError()); - retval=-1; + retval = -1; } } - if (session->rtp.QoSHandle!=NULL) { + if (session->rtp.QoSHandle != NULL) { BOOL QoSResult; - QoSResult = QOSAddSocketToFlow( - session->rtp.QoSHandle, - session->rtp.gs.socket, - (struct sockaddr*)&session->rtp.gs.rem_addr, - tos, - QOS_NON_ADAPTIVE_FLOW, - &session->rtp.QoSFlowID); - - if (QoSResult != TRUE){ + QoSResult = QOSAddSocketToFlow(session->rtp.QoSHandle, session->rtp.gs.socket, + (struct sockaddr *)&session->rtp.gs.rem_addr, tos, QOS_NON_ADAPTIVE_FLOW, + &session->rtp.QoSFlowID); + + if (QoSResult != TRUE) { ortp_error("QOSAddSocketToFlow failed to add a flow with error %d", GetLastError()); - retval=-1; + retval = -1; } } } else { -#endif //ENABLE_MICROSOFT_STORE_APP +#endif // ENABLE_MICROSOFT_STORE_APP #endif // DSCP value is in the upper six bits of the TOS field tos = (session->dscp << 2) & 0xFC; switch (session->rtp.gs.sockfamily) { case AF_INET: - proto=IPPROTO_IP; - value_type=IP_TOS; - break; - case AF_INET6: - proto=IPPROTO_IPV6; -# ifdef IPV6_TCLASS /*seems not defined by my libc*/ - value_type=IPV6_TCLASS; -# else - value_type=IP_TOS; -# endif - break; - default: - ortp_error("Cannot set DSCP because socket family is unspecified."); - return -1; + proto = IPPROTO_IP; + value_type = IP_TOS; + break; + case AF_INET6: + proto = IPPROTO_IPV6; +#ifdef IPV6_TCLASS /*seems not defined by my libc*/ + value_type = IPV6_TCLASS; +#else + value_type = IP_TOS; +#endif + break; + default: + ortp_error("Cannot set DSCP because socket family is unspecified."); + return -1; } retval = setsockopt(session->rtp.gs.socket, proto, value_type, (SOCKET_OPTION_VALUE)&tos, sizeof(tos)); - if (retval==-1) - ortp_error("Fail to set DSCP value on rtp socket: %s",getSocketError()); - if (session->rtcp.gs.socket != (ortp_socket_t)-1){ - if (setsockopt(session->rtcp.gs.socket, proto, value_type, (SOCKET_OPTION_VALUE)&tos, sizeof(tos))==-1){ - ortp_error("Fail to set DSCP value on rtcp socket: %s",getSocketError()); + if (retval == -1) ortp_error("Fail to set DSCP value on rtp socket: %s", getSocketError()); + if (session->rtcp.gs.socket != (ortp_socket_t)-1) { + if (setsockopt(session->rtcp.gs.socket, proto, value_type, (SOCKET_OPTION_VALUE)&tos, sizeof(tos)) == -1) { + ortp_error("Fail to set DSCP value on rtcp socket: %s", getSocketError()); } } #if (_WIN32_WINNT >= 0x0600) && defined(ORTP_WINDOWS_DESKTOP) @@ -771,36 +768,34 @@ int rtp_session_set_dscp(RtpSession *session, int dscp){ return retval; } - /** *rtp_session_get_dscp: *@param session: a rtp session * * Returns the DSCP (Differentiated Services Code Point) for outgoing RTP packets. * -**/ -int rtp_session_get_dscp(const RtpSession *session) -{ + **/ +int rtp_session_get_dscp(const RtpSession *session) { return session->dscp; } - /** *rtp_session_get_local_port: - *@param session: a rtp session for which rtp_session_set_local_addr() or rtp_session_set_remote_addr() has been called + *@param session: a rtp session for which rtp_session_set_local_addr() or rtp_session_set_remote_addr() has been + *called * * This function can be useful to retrieve the local port that was randomly choosen by * rtp_session_set_remote_addr() when rtp_session_set_local_addr() was not called. * * Returns: the local port used to listen for rtp packets, -1 if not set. -**/ + **/ -int rtp_session_get_local_port(const RtpSession *session){ - return (session->rtp.gs.loc_port>0) ? session->rtp.gs.loc_port : -1; +int rtp_session_get_local_port(const RtpSession *session) { + return (session->rtp.gs.loc_port > 0) ? session->rtp.gs.loc_port : -1; } -int rtp_session_get_local_rtcp_port(const RtpSession *session){ - return (session->rtcp.gs.loc_port>0) ? session->rtcp.gs.loc_port : -1; +int rtp_session_get_local_rtcp_port(const RtpSession *session) { + return (session->rtcp.gs.loc_port > 0) ? session->rtcp.gs.loc_port : -1; } /** @@ -814,10 +809,9 @@ int rtp_session_get_local_rtcp_port(const RtpSession *session){ * packets. Rtp packets that don't come from addr:port are discarded. * * Returns: 0 on success. -**/ -int -rtp_session_set_remote_addr (RtpSession * session, const char * addr, int port){ - return rtp_session_set_remote_addr_full(session, addr, port, addr, port+1); + **/ +int rtp_session_set_remote_addr(RtpSession *session, const char *addr, int port) { + return rtp_session_set_remote_addr_full(session, addr, port, addr, port + 1); } /** @@ -833,141 +827,148 @@ rtp_session_set_remote_addr (RtpSession * session, const char * addr, int port){ * packets. Rtp packets that don't come from addr:port are discarded. * * Returns: 0 on success. -**/ + **/ -int -rtp_session_set_remote_addr_full (RtpSession * session, const char * rtp_addr, int rtp_port, const char * rtcp_addr, int rtcp_port){ - return _rtp_session_set_remote_addr_full(session,rtp_addr,rtp_port,rtcp_addr,rtcp_port,FALSE); +int rtp_session_set_remote_addr_full( + RtpSession *session, const char *rtp_addr, int rtp_port, const char *rtcp_addr, int rtcp_port) { + return _rtp_session_set_remote_addr_full(session, rtp_addr, rtp_port, rtcp_addr, rtcp_port, FALSE); } -static int -_rtp_session_set_remote_addr_full (RtpSession * session, const char * rtp_addr, int rtp_port, const char * rtcp_addr, int rtcp_port, bool_t is_aux){ +static int _rtp_session_set_remote_addr_full( + RtpSession *session, const char *rtp_addr, int rtp_port, const char *rtcp_addr, int rtcp_port, bool_t is_aux) { char rtp_printable_addr[64]; char rtcp_printable_addr[64]; int err; struct addrinfo *res0, *res; - struct sockaddr_storage *rtp_saddr=&session->rtp.gs.rem_addr; - socklen_t *rtp_saddr_len=&session->rtp.gs.rem_addrlen; - struct sockaddr_storage *rtcp_saddr=&session->rtcp.gs.rem_addr; - socklen_t *rtcp_saddr_len=&session->rtcp.gs.rem_addrlen; - OrtpAddress *aux_rtp=NULL,*aux_rtcp=NULL; - - if (is_aux){ - aux_rtp=ortp_malloc0(sizeof(OrtpAddress)); - rtp_saddr=&aux_rtp->addr; - rtp_saddr_len=&aux_rtp->len; - aux_rtcp=ortp_malloc0(sizeof(OrtpAddress)); - rtcp_saddr=&aux_rtcp->addr; - rtcp_saddr_len=&aux_rtcp->len; - } - - res0 = bctbx_name_to_addrinfo((session->rtp.gs.socket == -1) ? AF_UNSPEC : session->rtp.gs.sockfamily, SOCK_DGRAM, rtp_addr, rtp_port); + struct sockaddr_storage *rtp_saddr = &session->rtp.gs.rem_addr; + socklen_t *rtp_saddr_len = &session->rtp.gs.rem_addrlen; + struct sockaddr_storage *rtcp_saddr = &session->rtcp.gs.rem_addr; + socklen_t *rtcp_saddr_len = &session->rtcp.gs.rem_addrlen; + OrtpAddress *aux_rtp = NULL, *aux_rtcp = NULL; + + if (is_aux) { + aux_rtp = ortp_malloc0(sizeof(OrtpAddress)); + rtp_saddr = &aux_rtp->addr; + rtp_saddr_len = &aux_rtp->len; + aux_rtcp = ortp_malloc0(sizeof(OrtpAddress)); + rtcp_saddr = &aux_rtcp->addr; + rtcp_saddr_len = &aux_rtcp->len; + } + + res0 = bctbx_name_to_addrinfo((session->rtp.gs.socket == -1) ? AF_UNSPEC : session->rtp.gs.sockfamily, SOCK_DGRAM, + rtp_addr, rtp_port); if (res0 == NULL) { - ortp_error("_rtp_session_set_remote_addr_full(): cannot set RTP destination to %s port %i.", rtp_addr, rtp_port); - err=-1; + ortp_error("_rtp_session_set_remote_addr_full(): cannot set RTP destination to %s port %i.", rtp_addr, + rtp_port); + err = -1; goto end; } else { bctbx_addrinfo_to_printable_ip_address(res0, rtp_printable_addr, sizeof(rtp_printable_addr)); } - if (session->rtp.gs.socket == -1){ + if (session->rtp.gs.socket == -1) { /* the session has not its socket bound, do it */ - ortp_message ("Setting random local addresses."); + ortp_message("Setting random local addresses."); /* bind to an address type that matches the destination address */ - if (res0->ai_addr->sa_family==AF_INET6) - err = rtp_session_set_local_addr (session, "::", -1, -1); - else err=rtp_session_set_local_addr (session, "0.0.0.0", -1, -1); - if (err<0) { - err=-1; + if (res0->ai_addr->sa_family == AF_INET6) err = rtp_session_set_local_addr(session, "::", -1, -1); + else err = rtp_session_set_local_addr(session, "0.0.0.0", -1, -1); + if (err < 0) { + err = -1; goto end; } } - err=-1; + err = -1; for (res = res0; res; res = res->ai_next) { /* set a destination address that has the same type as the local address */ - if (res->ai_family==session->rtp.gs.sockfamily ) { + if (res->ai_family == session->rtp.gs.sockfamily) { memcpy(rtp_saddr, res->ai_addr, res->ai_addrlen); - *rtp_saddr_len=(socklen_t)res->ai_addrlen; - err=0; + *rtp_saddr_len = (socklen_t)res->ai_addrlen; + err = 0; break; } } bctbx_freeaddrinfo(res0); if (err) { - ortp_warning("Could not set destination for RTP socket to %s:%i.",rtp_addr,rtp_port); + ortp_warning("Could not set destination for RTP socket to %s:%i.", rtp_addr, rtp_port); goto end; } if ((rtcp_addr != NULL) && (rtcp_port > 0)) { - res0 = bctbx_name_to_addrinfo((session->rtcp.gs.socket == -1) ? AF_UNSPEC : session->rtcp.gs.sockfamily, SOCK_DGRAM, rtcp_addr, rtcp_port); + res0 = bctbx_name_to_addrinfo((session->rtcp.gs.socket == -1) ? AF_UNSPEC : session->rtcp.gs.sockfamily, + SOCK_DGRAM, rtcp_addr, rtcp_port); if (res0 == NULL) { - ortp_error("_rtp_session_set_remote_addr_full(): cannot set RTCP destination to %s port %i.", rtcp_addr, rtcp_port); - err=-1; + ortp_error("_rtp_session_set_remote_addr_full(): cannot set RTCP destination to %s port %i.", rtcp_addr, + rtcp_port); + err = -1; goto end; } else { bctbx_addrinfo_to_printable_ip_address(res0, rtcp_printable_addr, sizeof(rtcp_printable_addr)); } - err=-1; + err = -1; for (res = res0; res; res = res->ai_next) { /* set a destination address that has the same type as the local address */ - if (res->ai_family==session->rtcp.gs.sockfamily ) { - err=0; + if (res->ai_family == session->rtcp.gs.sockfamily) { + err = 0; memcpy(rtcp_saddr, res->ai_addr, res->ai_addrlen); - *rtcp_saddr_len=(socklen_t)res->ai_addrlen; + *rtcp_saddr_len = (socklen_t)res->ai_addrlen; break; } } bctbx_freeaddrinfo(res0); if (err) { - ortp_warning("Could not set destination for RCTP socket to %s:%i.",rtcp_addr,rtcp_port); + ortp_warning("Could not set destination for RCTP socket to %s:%i.", rtcp_addr, rtcp_port); goto end; } - if (can_connect(session)){ - if (try_connect(session->rtp.gs.socket,(struct sockaddr*)&session->rtp.gs.rem_addr,session->rtp.gs.rem_addrlen)) - session->flags|=RTP_SOCKET_CONNECTED; - if (session->rtcp.gs.socket!=(ortp_socket_t)-1){ - if (try_connect(session->rtcp.gs.socket,(struct sockaddr*)&session->rtcp.gs.rem_addr,session->rtcp.gs.rem_addrlen)) - session->flags|=RTCP_SOCKET_CONNECTED; + if (can_connect(session)) { + if (try_connect(session->rtp.gs.socket, (struct sockaddr *)&session->rtp.gs.rem_addr, + session->rtp.gs.rem_addrlen)) + session->flags |= RTP_SOCKET_CONNECTED; + if (session->rtcp.gs.socket != (ortp_socket_t)-1) { + if (try_connect(session->rtcp.gs.socket, (struct sockaddr *)&session->rtcp.gs.rem_addr, + session->rtcp.gs.rem_addrlen)) + session->flags |= RTCP_SOCKET_CONNECTED; } - }else if (session->flags & RTP_SOCKET_CONNECTED){ + } else if (session->flags & RTP_SOCKET_CONNECTED) { /*must dissolve association done by connect(). See connect(2) manpage*/ struct sockaddr sa; - sa.sa_family=AF_UNSPEC; - if (connect(session->rtp.gs.socket,&sa,sizeof(sa))<0){ + sa.sa_family = AF_UNSPEC; + if (connect(session->rtp.gs.socket, &sa, sizeof(sa)) < 0) { ortp_error("Cannot dissolve connect() association for rtp socket: %s", getSocketError()); } - if (connect(session->rtcp.gs.socket,&sa,sizeof(sa))<0){ + if (connect(session->rtcp.gs.socket, &sa, sizeof(sa)) < 0) { ortp_error("Cannot dissolve connect() association for rtcp socket: %s", getSocketError()); } - session->flags&=~RTP_SOCKET_CONNECTED; - session->flags&=~RTCP_SOCKET_CONNECTED; + session->flags &= ~RTP_SOCKET_CONNECTED; + session->flags &= ~RTCP_SOCKET_CONNECTED; } - ortp_message("RtpSession [%p] sending to rtp %s rtcp %s %s", session, rtp_printable_addr, rtcp_printable_addr, is_aux ? "as auxiliary destination" : ""); + ortp_message("RtpSession [%p] sending to rtp %s rtcp %s %s", session, rtp_printable_addr, rtcp_printable_addr, + is_aux ? "as auxiliary destination" : ""); } else { - ortp_message("RtpSession [%p] sending to rtp %s %s", session, rtp_printable_addr, is_aux ? "as auxiliary destination" : ""); + ortp_message("RtpSession [%p] sending to rtp %s %s", session, rtp_printable_addr, + is_aux ? "as auxiliary destination" : ""); } /*Apply DSCP setting. On windows the destination address is required for doing this.*/ rtp_session_set_dscp(session, -1); end: - if (is_aux){ - if (err==-1){ + if (is_aux) { + if (err == -1) { ortp_free(aux_rtp); ortp_free(aux_rtcp); - }else{ + } else { ortp_mutex_lock(&session->main_mutex); - session->rtp.gs.aux_destinations=o_list_append(session->rtp.gs.aux_destinations,aux_rtp); - session->rtcp.gs.aux_destinations=o_list_append(session->rtcp.gs.aux_destinations,aux_rtcp); + session->rtp.gs.aux_destinations = o_list_append(session->rtp.gs.aux_destinations, aux_rtp); + session->rtcp.gs.aux_destinations = o_list_append(session->rtcp.gs.aux_destinations, aux_rtcp); ortp_mutex_unlock(&session->main_mutex); } } return err; } -int rtp_session_set_remote_addr_and_port(RtpSession * session, const char * addr, int rtp_port, int rtcp_port){ - return rtp_session_set_remote_addr_full(session,addr,rtp_port,addr,rtcp_port); +int rtp_session_set_remote_addr_and_port(RtpSession *session, const char *addr, int rtp_port, int rtcp_port) { + return rtp_session_set_remote_addr_full(session, addr, rtp_port, addr, rtcp_port); } /** @@ -982,49 +983,44 @@ int rtp_session_set_remote_addr_and_port(RtpSession * session, const char * addr * are sent. * * Returns: 0 on success. -**/ + **/ -int -rtp_session_add_aux_remote_addr_full(RtpSession * session, const char * rtp_addr, int rtp_port, const char * rtcp_addr, int rtcp_port){ - return _rtp_session_set_remote_addr_full(session,rtp_addr,rtp_port,rtcp_addr,rtcp_port,TRUE); +int rtp_session_add_aux_remote_addr_full( + RtpSession *session, const char *rtp_addr, int rtp_port, const char *rtcp_addr, int rtcp_port) { + return _rtp_session_set_remote_addr_full(session, rtp_addr, rtp_port, rtcp_addr, rtcp_port, TRUE); } -void rtp_session_clear_aux_remote_addr(RtpSession * session){ +void rtp_session_clear_aux_remote_addr(RtpSession *session) { ortp_mutex_lock(&session->main_mutex); ortp_stream_clear_aux_addresses(&session->rtp.gs); ortp_stream_clear_aux_addresses(&session->rtcp.gs); ortp_mutex_unlock(&session->main_mutex); } -void rtp_session_set_sockets(RtpSession *session, int rtpfd, int rtcpfd){ - if (rtpfd!=-1) set_non_blocking_socket(rtpfd); - if (rtcpfd!=-1) set_non_blocking_socket(rtcpfd); - session->rtp.gs.socket=rtpfd; - session->rtcp.gs.socket=rtcpfd; - if (rtpfd!=-1 || rtcpfd!=-1 ) - session->flags|=(RTP_SESSION_USING_EXT_SOCKETS|RTP_SOCKET_CONNECTED|RTCP_SOCKET_CONNECTED); - else session->flags&=~(RTP_SESSION_USING_EXT_SOCKETS|RTP_SOCKET_CONNECTED|RTCP_SOCKET_CONNECTED); +void rtp_session_set_sockets(RtpSession *session, int rtpfd, int rtcpfd) { + if (rtpfd != -1) set_non_blocking_socket(rtpfd); + if (rtcpfd != -1) set_non_blocking_socket(rtcpfd); + session->rtp.gs.socket = rtpfd; + session->rtcp.gs.socket = rtcpfd; + if (rtpfd != -1 || rtcpfd != -1) + session->flags |= (RTP_SESSION_USING_EXT_SOCKETS | RTP_SOCKET_CONNECTED | RTCP_SOCKET_CONNECTED); + else session->flags &= ~(RTP_SESSION_USING_EXT_SOCKETS | RTP_SOCKET_CONNECTED | RTCP_SOCKET_CONNECTED); } -void rtp_session_set_transports(RtpSession *session, struct _RtpTransport *rtptr, struct _RtpTransport *rtcptr) -{ +void rtp_session_set_transports(RtpSession *session, struct _RtpTransport *rtptr, struct _RtpTransport *rtcptr) { session->rtp.gs.tr = rtptr; session->rtcp.gs.tr = rtcptr; - if (rtptr) - rtptr->session=session; - if (rtcptr) - rtcptr->session=session; - - if (rtptr || rtcptr ) - session->flags|=(RTP_SESSION_USING_TRANSPORT); - else session->flags&=~(RTP_SESSION_USING_TRANSPORT); -} + if (rtptr) rtptr->session = session; + if (rtcptr) rtcptr->session = session; -void rtp_session_get_transports(const RtpSession *session, RtpTransport **rtptr, RtpTransport **rtcptr){ - if (rtptr) *rtptr=session->rtp.gs.tr; - if (rtcptr) *rtcptr=session->rtcp.gs.tr; + if (rtptr || rtcptr) session->flags |= (RTP_SESSION_USING_TRANSPORT); + else session->flags &= ~(RTP_SESSION_USING_TRANSPORT); } +void rtp_session_get_transports(const RtpSession *session, RtpTransport **rtptr, RtpTransport **rtcptr) { + if (rtptr) *rtptr = session->rtp.gs.tr; + if (rtcptr) *rtcptr = session->rtcp.gs.tr; +} /** *rtp_session_flush_sockets: @@ -1035,14 +1031,13 @@ void rtp_session_get_transports(const RtpSession *session, RtpTransport **rtptr, * and wishes to start to receive again. During the time no receive is made * packets get bufferised into the internal kernel socket structure. * -**/ -void rtp_session_flush_sockets(RtpSession *session){ + **/ +void rtp_session_flush_sockets(RtpSession *session) { rtp_session_set_flag(session, RTP_SESSION_FLUSH); rtp_session_rtp_recv(session, 0); rtp_session_unset_flag(session, RTP_SESSION_FLUSH); } - #if defined(_WIN32) || defined(_WIN32_WCE) #define MAX_BUF 64 static int rtp_sendmsg(ortp_socket_t sock, mblk_t *m, const struct sockaddr *rem_addr, socklen_t addr_len) { @@ -1056,10 +1051,10 @@ static int rtp_sendmsg(ortp_socket_t sock, mblk_t *m, const struct sockaddr *rem mblk_t *mTrack = m; PWSACMSGHDR cmsg = NULL; struct sockaddr_storage v4, v6Mapped; - socklen_t v4Len=0, v6MappedLen=0; + socklen_t v4Len = 0, v6MappedLen = 0; bool_t useV4 = FALSE; struct sockaddr remote_address = {0}; - struct addrinfo* feed_server = NULL; + struct addrinfo *feed_server = NULL; for (wsabufLen = 0; wsabufLen < MAX_BUF && mTrack != NULL; mTrack = mTrack->b_cont, ++wsabufLen) { wsabuf[wsabufLen].len = (ULONG)(mTrack->b_wptr - mTrack->b_rptr); @@ -1075,11 +1070,11 @@ static int rtp_sendmsg(ortp_socket_t sock, mblk_t *m, const struct sockaddr *rem } ortp_error("Too long msgb (%i fragments) , didn't fit into iov, end discarded.", MAX_BUF + count); } - if( addr_len == 0){ + if (addr_len == 0) { // Get the local host information msg.namelen = 0; msg.name = NULL; - }else{ + } else { msg.namelen = addr_len; msg.name = (SOCKADDR *)rem_addr; } @@ -1087,11 +1082,12 @@ static int rtp_sendmsg(ortp_socket_t sock, mblk_t *m, const struct sockaddr *rem msg.Control.len = sizeof(ctrlBuffer); cmsg = WSA_CMSG_FIRSTHDR(&msg); #ifdef IPV6_PKTINFO - if (m->recv_addr.family == AF_INET6 && !IN6_IS_ADDR_UNSPECIFIED(&m->recv_addr.addr.ipi6_addr) && !IN6_IS_ADDR_LOOPBACK(&m->recv_addr.addr.ipi6_addr)) { + if (m->recv_addr.family == AF_INET6 && !IN6_IS_ADDR_UNSPECIFIED(&m->recv_addr.addr.ipi6_addr) && + !IN6_IS_ADDR_LOOPBACK(&m->recv_addr.addr.ipi6_addr)) { if (IN6_IS_ADDR_V4MAPPED(&m->recv_addr.addr.ipi6_addr)) { useV4 = TRUE; - ortp_recvaddr_to_sockaddr(&m->recv_addr, (struct sockaddr*)&v6Mapped, &v6MappedLen); - bctbx_sockaddr_remove_v4_mapping((struct sockaddr*)&v6Mapped, (struct sockaddr*)&v4, &v4Len); + ortp_recvaddr_to_sockaddr(&m->recv_addr, (struct sockaddr *)&v6Mapped, &v6MappedLen); + bctbx_sockaddr_remove_v4_mapping((struct sockaddr *)&v6Mapped, (struct sockaddr *)&v4, &v4Len); } else { PIN6_PKTINFO pPktInfo = NULL; cmsg->cmsg_len = WSA_CMSG_LEN(sizeof(IN6_PKTINFO)); @@ -1105,89 +1101,85 @@ static int rtp_sendmsg(ortp_socket_t sock, mblk_t *m, const struct sockaddr *rem } #endif #ifdef IP_PKTINFO - if (m->recv_addr.family == AF_INET || useV4==TRUE) { // Add IPV4 to the message control + if (m->recv_addr.family == AF_INET || useV4 == TRUE) { // Add IPV4 to the message control PIN_PKTINFO pPktInfo = NULL; cmsg->cmsg_len = WSA_CMSG_LEN(sizeof(IN_PKTINFO)); cmsg->cmsg_level = IPPROTO_IP; cmsg->cmsg_type = IP_PKTINFO; pPktInfo = (PIN_PKTINFO)WSA_CMSG_DATA(cmsg); - if (useV4 == TRUE) - pPktInfo->ipi_addr = ((SOCKADDR_IN *)&v4)->sin_addr; - else - pPktInfo->ipi_addr = m->recv_addr.addr.ipi_addr; + if (useV4 == TRUE) pPktInfo->ipi_addr = ((SOCKADDR_IN *)&v4)->sin_addr; + else pPktInfo->ipi_addr = m->recv_addr.addr.ipi_addr; controlSize += WSA_CMSG_SPACE(sizeof(IN_PKTINFO)); } #endif msg.Control.len = controlSize; - if (controlSize == 0) - msg.Control.buf = NULL; + if (controlSize == 0) msg.Control.buf = NULL; error = WSASendMsg((SOCKET)sock, &msg, 0, &dwBytes, NULL, NULL); - if( error == SOCKET_ERROR && controlSize != 0){// Debug note : if unexpected WSAEFAULT, check the location of memory allocation of msg. It must be on ortp addresses space. + if (error == SOCKET_ERROR && controlSize != 0) { // Debug note : if unexpected WSAEFAULT, check the location of + // memory allocation of msg. It must be on ortp addresses space. int errorCode = WSAGetLastError(); - if( errorCode == WSAEINVAL || errorCode==WSAENETUNREACH || errorCode==WSAEFAULT) - { + if (errorCode == WSAEINVAL || errorCode == WSAENETUNREACH || errorCode == WSAEFAULT) { msg.Control.len = 0; msg.Control.buf = NULL; error = WSASendMsg((SOCKET)sock, &msg, 0, &dwBytes, NULL, NULL); } } mTrack = m; - if(error >= 0) - return dwBytes;// Return the bytes that have been sent - else - return error; + if (error >= 0) return dwBytes; // Return the bytes that have been sent + else return error; } #else #ifdef USE_SENDMSG #define MAX_IOV 64 -static int rtp_sendmsg(ortp_socket_t sock,mblk_t *m, const struct sockaddr *rem_addr, socklen_t addr_len){ +static int rtp_sendmsg(ortp_socket_t sock, mblk_t *m, const struct sockaddr *rem_addr, socklen_t addr_len) { struct msghdr msg; struct iovec iov[MAX_IOV]; int iovlen; u_char control_buffer[512] = {0}; - mblk_t * m_track = m; - int controlSize = 0; // Used to reset msg.msg_controllen to the real control size + mblk_t *m_track = m; + int controlSize = 0; // Used to reset msg.msg_controllen to the real control size struct cmsghdr *cmsg; struct sockaddr_storage v4, v6Mapped; - socklen_t v4Len=0, v6MappedLen=0; + socklen_t v4Len = 0, v6MappedLen = 0; bool_t useV4 = FALSE; int error; - for(iovlen=0; iovlenb_cont,iovlen++){ - iov[iovlen].iov_base=m_track->b_rptr; - iov[iovlen].iov_len=m_track->b_wptr-m_track->b_rptr; + for (iovlen = 0; iovlen < MAX_IOV && m_track != NULL; m_track = m_track->b_cont, iovlen++) { + iov[iovlen].iov_base = m_track->b_rptr; + iov[iovlen].iov_len = m_track->b_wptr - m_track->b_rptr; } - if (iovlen==MAX_IOV){ + if (iovlen == MAX_IOV) { int count = 0; - while (m_track!=NULL){ + while (m_track != NULL) { count++; - m_track=m_track->b_cont; + m_track = m_track->b_cont; } - ortp_error("Too long msgb (%i fragments) , didn't fit into iov, end discarded.", MAX_IOV+count); + ortp_error("Too long msgb (%i fragments) , didn't fit into iov, end discarded.", MAX_IOV + count); } - msg.msg_name=(void*)rem_addr; - msg.msg_namelen=addr_len; - msg.msg_iov=&iov[0]; - msg.msg_iovlen=iovlen; - msg.msg_flags=0; - msg.msg_control=control_buffer; - msg.msg_controllen=sizeof(control_buffer); + msg.msg_name = (void *)rem_addr; + msg.msg_namelen = addr_len; + msg.msg_iov = &iov[0]; + msg.msg_iovlen = iovlen; + msg.msg_flags = 0; + msg.msg_control = control_buffer; + msg.msg_controllen = sizeof(control_buffer); cmsg = CMSG_FIRSTHDR(&msg); #ifdef IPV6_PKTINFO - if( m->recv_addr.family == AF_INET6 && !IN6_IS_ADDR_UNSPECIFIED(&m->recv_addr.addr.ipi6_addr) && !IN6_IS_ADDR_LOOPBACK(&m->recv_addr.addr.ipi6_addr)) - {// Add IPV6 to the message control. We only add it if the IP is specified and is not link local + if (m->recv_addr.family == AF_INET6 && !IN6_IS_ADDR_UNSPECIFIED(&m->recv_addr.addr.ipi6_addr) && + !IN6_IS_ADDR_LOOPBACK(&m->recv_addr.addr.ipi6_addr)) { // Add IPV6 to the message control. We only add it if the + // IP is specified and is not link local if (IN6_IS_ADDR_V4MAPPED(&m->recv_addr.addr.ipi6_addr)) { useV4 = TRUE; - ortp_recvaddr_to_sockaddr(&m->recv_addr, (struct sockaddr*)&v6Mapped, &v6MappedLen); - bctbx_sockaddr_remove_v4_mapping((struct sockaddr*)&v6Mapped, (struct sockaddr*)&v4, &v4Len); + ortp_recvaddr_to_sockaddr(&m->recv_addr, (struct sockaddr *)&v6Mapped, &v6MappedLen); + bctbx_sockaddr_remove_v4_mapping((struct sockaddr *)&v6Mapped, (struct sockaddr *)&v4, &v4Len); } else { struct in6_pktinfo *pktinfo; cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); cmsg->cmsg_level = IPPROTO_IPV6; cmsg->cmsg_type = IPV6_PKTINFO; - pktinfo = (struct in6_pktinfo*) CMSG_DATA(cmsg); - pktinfo->ipi6_ifindex = 0; // Set to 0 to let the kernel to use routable interface + pktinfo = (struct in6_pktinfo *)CMSG_DATA(cmsg); + pktinfo->ipi6_ifindex = 0; // Set to 0 to let the kernel to use routable interface pktinfo->ipi6_addr = m->recv_addr.addr.ipi6_addr; controlSize += CMSG_SPACE(sizeof(struct in6_pktinfo)); cmsg = CMSG_NXTHDR(&msg, cmsg); @@ -1195,35 +1187,33 @@ static int rtp_sendmsg(ortp_socket_t sock,mblk_t *m, const struct sockaddr *rem_ } #endif #ifdef IP_PKTINFO - if( m->recv_addr.family == AF_INET || useV4==TRUE ) - {// Add IPV4 to the message control + if (m->recv_addr.family == AF_INET || useV4 == TRUE) { // Add IPV4 to the message control struct in_pktinfo *pktinfo; cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)); cmsg->cmsg_level = IPPROTO_IP; cmsg->cmsg_type = IP_PKTINFO; - pktinfo = (struct in_pktinfo*) CMSG_DATA(cmsg); - if(useV4 == TRUE) - pktinfo->ipi_spec_dst = ((struct sockaddr_in *)&v4)->sin_addr; - else - pktinfo->ipi_spec_dst = m->recv_addr.addr.ipi_addr; + pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsg); + if (useV4 == TRUE) pktinfo->ipi_spec_dst = ((struct sockaddr_in *)&v4)->sin_addr; + else pktinfo->ipi_spec_dst = m->recv_addr.addr.ipi_addr; controlSize += CMSG_SPACE(sizeof(struct in_pktinfo)); cmsg = CMSG_NXTHDR(&msg, cmsg); } #endif #ifdef IPV6_RECVDSTADDR - if( m->recv_addr.family == AF_INET6 && !IN6_IS_ADDR_UNSPECIFIED(&m->recv_addr.addr.ipi6_addr) && !IN6_IS_ADDR_LOOPBACK(&m->recv_addr.addr.ipi6_addr)) - {// Add IPV6 to the message control. We only add it if the IP is specified and is not link local + if (m->recv_addr.family == AF_INET6 && !IN6_IS_ADDR_UNSPECIFIED(&m->recv_addr.addr.ipi6_addr) && + !IN6_IS_ADDR_LOOPBACK(&m->recv_addr.addr.ipi6_addr)) { // Add IPV6 to the message control. We only add it if the + // IP is specified and is not link local if (IN6_IS_ADDR_V4MAPPED(&m->recv_addr.addr.ipi6_addr)) { useV4 = TRUE; - ortp_recvaddr_to_sockaddr(&m->recv_addr,(struct sockaddr*) &v6Mapped, &v6MappedLen); - bctbx_sockaddr_remove_v4_mapping((struct sockaddr*)&v6Mapped, (struct sockaddr*)&v4, &v4Len); + ortp_recvaddr_to_sockaddr(&m->recv_addr, (struct sockaddr *)&v6Mapped, &v6MappedLen); + bctbx_sockaddr_remove_v4_mapping((struct sockaddr *)&v6Mapped, (struct sockaddr *)&v4, &v4Len); } else { struct in6_addr *pktinfo; cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_addr)); cmsg->cmsg_level = IPPROTO_IPV6; cmsg->cmsg_type = IPV6_RECVDSTADDR; - pktinfo = (struct in6_addr*) CMSG_DATA(cmsg); + pktinfo = (struct in6_addr *)CMSG_DATA(cmsg); *pktinfo = m->recv_addr.addr.ipi6_addr; controlSize += CMSG_SPACE(sizeof(struct in6_addr)); cmsg = CMSG_NXTHDR(&msg, cmsg); @@ -1231,53 +1221,51 @@ static int rtp_sendmsg(ortp_socket_t sock,mblk_t *m, const struct sockaddr *rem_ } #endif #if defined(IP_RECVDSTADDR) - if( m->recv_addr.family == AF_INET || useV4==TRUE ) - {// Add IPV4 to the message control + if (m->recv_addr.family == AF_INET || useV4 == TRUE) { // Add IPV4 to the message control struct in_addr *pktinfo; cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr)); cmsg->cmsg_level = IPPROTO_IP; cmsg->cmsg_type = IP_RECVDSTADDR; - pktinfo = (struct in_addr*) CMSG_DATA(cmsg); - if(useV4 == TRUE) - *pktinfo = ((struct sockaddr_in *)&v4)->sin_addr; - else - *pktinfo = m->recv_addr.addr.ipi_addr; + pktinfo = (struct in_addr *)CMSG_DATA(cmsg); + if (useV4 == TRUE) *pktinfo = ((struct sockaddr_in *)&v4)->sin_addr; + else *pktinfo = m->recv_addr.addr.ipi_addr; controlSize += CMSG_SPACE(sizeof(struct in_addr)); -// cmsg = CMSG_NXTHDR(&msg, cmsg); // Uncomment if you want to add interfaces + // cmsg = CMSG_NXTHDR(&msg, cmsg); // Uncomment if you want to add interfaces } #endif msg.msg_controllen = controlSize; - if( controlSize==0) // Have to reset msg_control to NULL as msg_controllen is not sufficient on some platforms + if (controlSize == 0) // Have to reset msg_control to NULL as msg_controllen is not sufficient on some platforms msg.msg_control = NULL; - error = sendmsg((int)sock,&msg,0); - if( error == -1 && controlSize != 0 && (errno == EINVAL || errno==ENETUNREACH || errno==EFAULT)) { - msg.msg_controllen =0; + error = sendmsg((int)sock, &msg, 0); + if (error == -1 && controlSize != 0 && (errno == EINVAL || errno == ENETUNREACH || errno == EFAULT)) { + msg.msg_controllen = 0; msg.msg_control = NULL; - error = sendmsg((int)sock,&msg,0); + error = sendmsg((int)sock, &msg, 0); } return error; } #endif #endif -ortp_socket_t rtp_session_get_socket(RtpSession *session, bool_t is_rtp){ +ortp_socket_t rtp_session_get_socket(RtpSession *session, bool_t is_rtp) { return is_rtp ? session->rtp.gs.socket : session->rtcp.gs.socket; } -int _ortp_sendto(ortp_socket_t sockfd, mblk_t *m, int flags, const struct sockaddr *destaddr, socklen_t destlen) { +int _ortp_sendto( + ortp_socket_t sockfd, mblk_t *m, BCTBX_UNUSED(int flags), const struct sockaddr *destaddr, socklen_t destlen) { int sent_bytes; #if defined(_WIN32) || defined(_WIN32_WCE) || defined(USE_SENDMSG) sent_bytes = rtp_sendmsg(sockfd, m, destaddr, destlen); #else - if (m->b_cont != NULL) - msgpullup(m, -1); - sent_bytes = sendto(sockfd, (char*)m->b_rptr, (int)(m->b_wptr - m->b_rptr), 0, destaddr, destlen); + if (m->b_cont != NULL) msgpullup(m, -1); + sent_bytes = sendto(sockfd, (char *)m->b_rptr, (int)(m->b_wptr - m->b_rptr), 0, destaddr, destlen); #endif return sent_bytes; } -int rtp_session_sendto(RtpSession *session, bool_t is_rtp, mblk_t *m, int flags, const struct sockaddr *destaddr, socklen_t destlen){ +int rtp_session_sendto( + RtpSession *session, bool_t is_rtp, mblk_t *m, int flags, const struct sockaddr *destaddr, socklen_t destlen) { int ret; OrtpStream *ostr = is_rtp ? &session->rtp.gs : &session->rtcp.gs; _rtp_session_check_socket_refresh(session); @@ -1286,31 +1274,31 @@ int rtp_session_sendto(RtpSession *session, bool_t is_rtp, mblk_t *m, int flags, * If the "recv_addr" (which is the source address to use for sending) is not specified for this packet, * default to the source address specified in the RtpSession for the rtp or rtcp stream. */ - if( m->recv_addr.family == AF_UNSPEC && ostr->used_loc_addrlen != 0 ) - ortp_sockaddr_to_recvaddr((const struct sockaddr*)&ostr->used_loc_addr, &m->recv_addr); - - if (session->net_sim_ctx && (session->net_sim_ctx->params.mode==OrtpNetworkSimulatorOutbound - || session->net_sim_ctx->params.mode==OrtpNetworkSimulatorOutboundControlled)){ - ret=(int)msgdsize(m); - m=dupmsg(m); - memcpy(&m->net_addr,destaddr,destlen); - m->net_addrlen=destlen; - m->reserved1=is_rtp; + if (m->recv_addr.family == AF_UNSPEC && ostr->used_loc_addrlen != 0) + ortp_sockaddr_to_recvaddr((const struct sockaddr *)&ostr->used_loc_addr, &m->recv_addr); + + if (session->net_sim_ctx && (session->net_sim_ctx->params.mode == OrtpNetworkSimulatorOutbound || + session->net_sim_ctx->params.mode == OrtpNetworkSimulatorOutboundControlled)) { + ret = (int)msgdsize(m); + m = dupmsg(m); + memcpy(&m->net_addr, destaddr, destlen); + m->net_addrlen = destlen; + m->reserved1 = is_rtp; ortp_mutex_lock(&session->net_sim_ctx->mutex); putq(&session->net_sim_ctx->send_q, m); ortp_mutex_unlock(&session->net_sim_ctx->mutex); - }else{ + } else { ortp_socket_t sockfd = rtp_session_get_socket(session, is_rtp || session->rtcp_mux); - if (sockfd != (ortp_socket_t)-1){ - ret=_ortp_sendto(sockfd, m, flags, destaddr, destlen); - }else{ + if (sockfd != (ortp_socket_t)-1) { + ret = _ortp_sendto(sockfd, m, flags, destaddr, destlen); + } else { ret = -1; } } return ret; } -static const ortp_recv_addr_t * lookup_recv_addr(RtpSession *session, struct sockaddr *from, socklen_t fromlen) { +static const ortp_recv_addr_t *lookup_recv_addr(RtpSession *session, struct sockaddr *from, socklen_t fromlen) { const ortp_recv_addr_t *result = NULL; bctbx_list_t *iterator = session->recv_addr_map; while (iterator != NULL) { @@ -1328,9 +1316,9 @@ static const ortp_recv_addr_t * lookup_recv_addr(RtpSession *session, struct soc return result; } -static const ortp_recv_addr_t * get_recv_addr(RtpSession *session, struct sockaddr *from, socklen_t fromlen) { - char result[NI_MAXHOST] = { 0 }; - char dest[NI_MAXHOST] = { 0 }; +static const ortp_recv_addr_t *get_recv_addr(RtpSession *session, struct sockaddr *from, socklen_t fromlen) { + char result[NI_MAXHOST] = {0}; + char dest[NI_MAXHOST] = {0}; struct addrinfo *ai = NULL; int port = 0; int family = from->sa_family; @@ -1354,9 +1342,11 @@ static const ortp_recv_addr_t * get_recv_addr(RtpSession *session, struct sockad memcpy(&item->ss, from, fromlen); item->recv_addr.family = family; if (family == AF_INET) { - memcpy(&item->recv_addr.addr.ipi_addr, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, sizeof(item->recv_addr.addr.ipi_addr)); + memcpy(&item->recv_addr.addr.ipi_addr, &((struct sockaddr_in *)ai->ai_addr)->sin_addr, + sizeof(item->recv_addr.addr.ipi_addr)); } else if (family == AF_INET6) { - memcpy(&item->recv_addr.addr.ipi6_addr, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, sizeof(item->recv_addr.addr.ipi6_addr)); + memcpy(&item->recv_addr.addr.ipi6_addr, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr, + sizeof(item->recv_addr.addr.ipi6_addr)); } bctbx_freeaddrinfo(ai); item->ts = bctbx_get_cur_time_ms(); @@ -1365,18 +1355,21 @@ static const ortp_recv_addr_t * get_recv_addr(RtpSession *session, struct sockad } } -int rtp_session_recvfrom(RtpSession *session, bool_t is_rtp, mblk_t *m, int flags, struct sockaddr *from, socklen_t *fromlen) { - int ret = rtp_session_rtp_recv_abstract(is_rtp ? session->rtp.gs.socket : session->rtcp.gs.socket, m, flags, from, fromlen); +int rtp_session_recvfrom( + RtpSession *session, bool_t is_rtp, mblk_t *m, int flags, struct sockaddr *from, socklen_t *fromlen) { + int ret = rtp_session_rtp_recv_abstract(is_rtp ? session->rtp.gs.socket : session->rtcp.gs.socket, m, flags, from, + fromlen); if ((ret >= 0) && (session->use_pktinfo == TRUE)) { if (m->recv_addr.family == AF_UNSPEC) { const ortp_recv_addr_t *recv_addr; - if (!session->warn_non_working_pkt_info){ - ortp_error("IP_PKTINFO/IP6_PKTINFO not working as expected for recevied packets. An unreliable fallback method will be used."); + if (!session->warn_non_working_pkt_info) { + ortp_error("IP_PKTINFO/IP6_PKTINFO not working as expected for recevied packets. An unreliable " + "fallback method will be used."); session->warn_non_working_pkt_info = TRUE; } - /* The receive address has not been filled, this typically happens on Mac OS X when receiving an IPv4 packet on - * a dual stack socket. Try to guess the address because it is mandatory for ICE. */ + /* The receive address has not been filled, this typically happens on Mac OS X when receiving an IPv4 packet + * on a dual stack socket. Try to guess the address because it is mandatory for ICE. */ recv_addr = lookup_recv_addr(session, from, *fromlen); if (recv_addr == NULL) { recv_addr = get_recv_addr(session, from, *fromlen); @@ -1384,10 +1377,12 @@ int rtp_session_recvfrom(RtpSession *session, bool_t is_rtp, mblk_t *m, int flag if (recv_addr != NULL) { memcpy(&m->recv_addr, recv_addr, sizeof(ortp_recv_addr_t)); } else { - ortp_error("Did not succeed to fill the receive address, this should not happen! [family=%d, len=%d]", from->sa_family, (int)*fromlen); + ortp_error("Did not succeed to fill the receive address, this should not happen! [family=%d, len=%d]", + from->sa_family, (int)*fromlen); } } - /* Store the local port in the recv_addr of the mblk_t, the address is already filled in rtp_session_rtp_recv_abstract */ + /* Store the local port in the recv_addr of the mblk_t, the address is already filled in + * rtp_session_rtp_recv_abstract */ m->recv_addr.port = htons(is_rtp ? session->rtp.gs.loc_port : session->rtcp.gs.loc_port); } return ret; @@ -1411,16 +1406,18 @@ static void update_recv_bytes(OrtpStream *os, size_t nbytes, const struct timeva ortp_bw_estimator_packet_received(&os->recv_bw_estimator, nbytes + overhead, recv_time); } -static void log_send_error(RtpSession *session, const char *type, mblk_t *m, struct sockaddr *destaddr, socklen_t destlen){ - char printable_ip_address[65]={0}; +static void +log_send_error(RtpSession *session, const char *type, mblk_t *m, struct sockaddr *destaddr, socklen_t destlen) { + char printable_ip_address[65] = {0}; int errnum = getSocketErrorCode(); const char *errstr = getSocketError(); bctbx_sockaddr_to_printable_ip_address(destaddr, destlen, printable_ip_address, sizeof(printable_ip_address)); - ortp_error ("RtpSession [%p] error sending [%s] packet [%p] to %s: %s [%d]", - session, type, m, printable_ip_address, errstr, errnum); + ortp_error("RtpSession [%p] error sending [%s] packet [%p] to %s: %s [%d]", session, type, m, printable_ip_address, + errstr, errnum); } -static int rtp_session_rtp_sendto(RtpSession * session, mblk_t * m, struct sockaddr *destaddr, socklen_t destlen, bool_t is_aux){ +static int +rtp_session_rtp_sendto(RtpSession *session, mblk_t *m, struct sockaddr *destaddr, socklen_t destlen, bool_t is_aux) { int error; RtpSession *send_session = session; RtpBundle *bundle = session->bundle; @@ -1434,30 +1431,31 @@ static int rtp_session_rtp_sendto(RtpSession * session, mblk_t * m, struct socka destaddr = (struct sockaddr *)&send_session->rtp.gs.rem_addr; destlen = send_session->rtp.gs.rem_addrlen; } - if (rtp_session_using_transport(send_session, rtp)){ - error = (send_session->rtp.gs.tr->t_sendto) (send_session->rtp.gs.tr,m,0,destaddr,destlen); - }else{ - error=rtp_session_sendto(send_session, TRUE,m,0,destaddr,destlen); + if (rtp_session_using_transport(send_session, rtp)) { + error = (send_session->rtp.gs.tr->t_sendto)(send_session->rtp.gs.tr, m, 0, destaddr, destlen); + } else { + error = rtp_session_sendto(send_session, TRUE, m, 0, destaddr, destlen); } - if (!is_aux){ + if (!is_aux) { /*errors to auxiliary destinations are not notified*/ - if (error < 0){ - if (session->on_network_error.count>0){ - rtp_signal_table_emit3(&session->on_network_error,"Error sending RTP packet",ORTP_INT_TO_POINTER(getSocketErrorCode())); - }else log_send_error(session,"rtp",m,destaddr,destlen); - session->rtp.send_errno=getSocketErrorCode(); - }else{ + if (error < 0) { + if (session->on_network_error.count > 0) { + rtp_signal_table_emit3(&session->on_network_error, "Error sending RTP packet", + ORTP_INT_TO_POINTER(getSocketErrorCode())); + } else log_send_error(session, "rtp", m, destaddr, destlen); + session->rtp.send_errno = getSocketErrorCode(); + } else { update_sent_bytes(&session->rtp.gs, error); } } return error; } -int rtp_session_rtp_send (RtpSession * session, mblk_t * m){ - int error=0; - struct sockaddr *destaddr=(struct sockaddr*)&session->rtp.gs.rem_addr; - socklen_t destlen=session->rtp.gs.rem_addrlen; - OList *elem=NULL; +int rtp_session_rtp_send(RtpSession *session, mblk_t *m) { + int error = 0; + struct sockaddr *destaddr = (struct sockaddr *)&session->rtp.gs.rem_addr; + socklen_t destlen = session->rtp.gs.rem_addrlen; + OList *elem = NULL; if (session->is_spliced) { freemsg(m); @@ -1465,48 +1463,50 @@ int rtp_session_rtp_send (RtpSession * session, mblk_t * m){ } if (session->flags & RTP_SOCKET_CONNECTED) { - destaddr=NULL; - destlen=0; + destaddr = NULL; + destlen = 0; } /*first send to main destination*/ - error=rtp_session_rtp_sendto(session,m,destaddr,destlen,FALSE); + error = rtp_session_rtp_sendto(session, m, destaddr, destlen, FALSE); /*then iterate over auxiliary destinations*/ ortp_mutex_lock(&session->main_mutex); - for(elem=session->rtp.gs.aux_destinations;elem!=NULL;elem=elem->next){ - OrtpAddress *addr=(OrtpAddress*)elem->data; - rtp_session_rtp_sendto(session,m,(struct sockaddr*)&addr->addr,addr->len,TRUE); + for (elem = session->rtp.gs.aux_destinations; elem != NULL; elem = elem->next) { + OrtpAddress *addr = (OrtpAddress *)elem->data; + rtp_session_rtp_sendto(session, m, (struct sockaddr *)&addr->addr, addr->len, TRUE); } ortp_mutex_unlock(&session->main_mutex); freemsg(m); return error; } -static int rtp_session_rtcp_sendto(RtpSession * session, mblk_t * m, struct sockaddr *destaddr, socklen_t destlen, bool_t is_aux){ - int error=0; +static int +rtp_session_rtcp_sendto(RtpSession *session, mblk_t *m, struct sockaddr *destaddr, socklen_t destlen, bool_t is_aux) { + int error = 0; RtpSession *send_session = session; RtpBundle *bundle = session->bundle; if (bundle && !session->is_primary) { send_session = rtp_bundle_get_primary_session(bundle); - if (send_session){ + if (send_session) { destaddr = (struct sockaddr *)&send_session->rtp.gs.rem_addr; destlen = send_session->rtp.gs.rem_addrlen; - }else send_session = session; - } - /* Even in RTCP mux, we send through the RTCP RtpTransport, which will itself take in charge to do the sending of the packet - * through the RTP endpoint*/ - if (rtp_session_using_transport(send_session, rtcp)){ - error = (send_session->rtcp.gs.tr->t_sendto) (send_session->rtcp.gs.tr, m, 0, destaddr, destlen); - }else{ - error=_ortp_sendto(rtp_session_get_socket(send_session, send_session->rtcp_mux),m,0,destaddr,destlen); - } - - if (!is_aux){ - if (error < 0){ - if (session->on_network_error.count>0){ - rtp_signal_table_emit3(&session->on_network_error,"Error sending RTCP packet",ORTP_INT_TO_POINTER(getSocketErrorCode())); - }else{ - log_send_error(session,"rtcp",m,destaddr,destlen); + } else send_session = session; + } + /* Even in RTCP mux, we send through the RTCP RtpTransport, which will itself take in charge to do the sending of + * the packet through the RTP endpoint*/ + if (rtp_session_using_transport(send_session, rtcp)) { + error = (send_session->rtcp.gs.tr->t_sendto)(send_session->rtcp.gs.tr, m, 0, destaddr, destlen); + } else { + error = _ortp_sendto(rtp_session_get_socket(send_session, send_session->rtcp_mux), m, 0, destaddr, destlen); + } + + if (!is_aux) { + if (error < 0) { + if (session->on_network_error.count > 0) { + rtp_signal_table_emit3(&session->on_network_error, "Error sending RTCP packet", + ORTP_INT_TO_POINTER(getSocketErrorCode())); + } else { + log_send_error(session, "rtcp", m, destaddr, destlen); } } else { update_sent_bytes(&session->rtcp.gs, error); @@ -1516,39 +1516,45 @@ static int rtp_session_rtcp_sendto(RtpSession * session, mblk_t * m, struct sock return error; } -int -rtp_session_rtcp_send (RtpSession * session, mblk_t * m){ - int error=0; - ortp_socket_t sockfd=session->rtcp.gs.socket; - struct sockaddr *destaddr=session->rtcp_mux ? (struct sockaddr*)&session->rtp.gs.rem_addr : (struct sockaddr*)&session->rtcp.gs.rem_addr; - socklen_t destlen=session->rtcp_mux ? session->rtp.gs.rem_addrlen : session->rtcp.gs.rem_addrlen; - OList *elem=NULL; - bool_t using_connected_socket=(session->flags & RTCP_SOCKET_CONNECTED)!=0; +int rtp_session_rtcp_send(RtpSession *session, mblk_t *m) { + int error = 0; + ortp_socket_t sockfd = session->rtcp.gs.socket; + struct sockaddr *destaddr = session->rtcp_mux ? (struct sockaddr *)&session->rtp.gs.rem_addr + : (struct sockaddr *)&session->rtcp.gs.rem_addr; + socklen_t destlen = session->rtcp_mux ? session->rtp.gs.rem_addrlen : session->rtcp.gs.rem_addrlen; + OList *elem = NULL; + bool_t using_connected_socket = (session->flags & RTCP_SOCKET_CONNECTED) != 0; if (session->is_spliced) { freemsg(m); return 0; } if (using_connected_socket) { - destaddr=NULL; - destlen=0; + destaddr = NULL; + destlen = 0; } - if (session->rtcp.enabled){ - if ( (sockfd!=(ortp_socket_t)-1 && (destlen>0 || using_connected_socket)) - || rtp_session_using_transport(session, rtcp) ) { - rtp_session_rtcp_sendto(session,m,destaddr,destlen,FALSE); + if (session->rtcp.enabled) { + if ((sockfd != (ortp_socket_t)-1 && (destlen > 0 || using_connected_socket)) || + rtp_session_using_transport(session, rtcp)) { + rtp_session_rtcp_sendto(session, m, destaddr, destlen, FALSE); } - for(elem=session->rtcp.gs.aux_destinations;elem!=NULL;elem=elem->next){ - OrtpAddress *addr=(OrtpAddress*)elem->data; - rtp_session_rtcp_sendto(session,m,(struct sockaddr*)&addr->addr,addr->len,TRUE); + for (elem = session->rtcp.gs.aux_destinations; elem != NULL; elem = elem->next) { + OrtpAddress *addr = (OrtpAddress *)elem->data; + rtp_session_rtcp_sendto(session, m, (struct sockaddr *)&addr->addr, addr->len, TRUE); } - }else ortp_message("Not sending rtcp report, rtcp disabled."); + } else ortp_message("Not sending rtcp report, rtcp disabled."); freemsg(m); return error; } #ifdef USE_RECVMSG -static int rtp_recvmsg(ortp_socket_t socket, mblk_t *msg, int flags, struct sockaddr *from, socklen_t *fromlen, struct msghdr *msghdr, int bufsz) { +static int rtp_recvmsg(ortp_socket_t socket, + mblk_t *msg, + int flags, + struct sockaddr *from, + socklen_t *fromlen, + struct msghdr *msghdr, + int bufsz) { struct iovec iov; int error; @@ -1562,26 +1568,26 @@ static int rtp_recvmsg(ortp_socket_t socket, mblk_t *msg, int flags, struct sock msghdr->msg_iov = &iov; msghdr->msg_iovlen = 1; error = recvmsg(socket, msghdr, flags); - if (fromlen != NULL) - *fromlen = msghdr->msg_namelen; + if (fromlen != NULL) *fromlen = msghdr->msg_namelen; return error; } #endif -int rtp_session_rtp_recv_abstract(ortp_socket_t socket, mblk_t *msg, int flags, struct sockaddr *from, socklen_t *fromlen) { +int rtp_session_rtp_recv_abstract( + ortp_socket_t socket, mblk_t *msg, int flags, struct sockaddr *from, socklen_t *fromlen) { int ret; - int bufsz = (int) (msg->b_datap->db_lim - msg->b_datap->db_base); + int bufsz = (int)(msg->b_datap->db_lim - msg->b_datap->db_base); char control[512] = {0}; #ifdef _WIN32 WSAMSG msghdr = {0}; WSACMSGHDR *cmsghdr; WSABUF data_buf; - DWORD bytes_received=0; + DWORD bytes_received = 0; int error = 0; if (ortp_WSARecvMsg == NULL) { return recvfrom(socket, (char *)msg->b_wptr, bufsz, flags, from, fromlen); } - if(from != NULL && fromlen != NULL) { + if (from != NULL && fromlen != NULL) { msghdr.name = from; msghdr.namelen = *fromlen; } @@ -1593,9 +1599,8 @@ int rtp_session_rtp_recv_abstract(ortp_socket_t socket, mblk_t *msg, int flags, msghdr.Control.len = sizeof(control); msghdr.dwFlags = flags; ret = ortp_WSARecvMsg(socket, &msghdr, &bytes_received, NULL, NULL); - if(fromlen != NULL) - *fromlen = msghdr.namelen; - if(ret >= 0) { + if (fromlen != NULL) *fromlen = msghdr.namelen; + if (ret >= 0) { ret = bytes_received; #else struct msghdr msghdr = {0}; @@ -1606,10 +1611,10 @@ int rtp_session_rtp_recv_abstract(ortp_socket_t socket, mblk_t *msg, int flags, #else ret = recvfrom(socket, msg->b_wptr, bufsz, flags, from, fromlen); #endif - if(ret >= 0) { + if (ret >= 0) { struct cmsghdr *cmsghdr; #endif - for (cmsghdr = CMSG_FIRSTHDR(&msghdr); cmsghdr != NULL ; cmsghdr = CMSG_NXTHDR(&msghdr, cmsghdr)) { + for (cmsghdr = CMSG_FIRSTHDR(&msghdr); cmsghdr != NULL; cmsghdr = CMSG_NXTHDR(&msghdr, cmsghdr)) { #ifdef _RECV_SO_TIMESTAMP_TYPE if (cmsghdr->cmsg_level == SOL_SOCKET && cmsghdr->cmsg_type == _RECV_SO_TIMESTAMP_TYPE) { memcpy(&msg->timestamp, (struct timeval *)CMSG_DATA(cmsghdr), sizeof(struct timeval)); @@ -1658,38 +1663,37 @@ int rtp_session_rtp_recv_abstract(ortp_socket_t socket, mblk_t *msg, int flags, } /*store recv addr for use by modifiers*/ if (from && fromlen) { - memcpy(&msg->net_addr,from,*fromlen); + memcpy(&msg->net_addr, from, *fromlen); msg->net_addrlen = *fromlen; } - }else{ + } else { } return ret; } -void rtp_session_notify_inc_rtcp(RtpSession *session, mblk_t *m, bool_t received_via_rtcp_mux){ - if (session->eventqs!=NULL){ - OrtpEvent *ev=ortp_event_new(ORTP_EVENT_RTCP_PACKET_RECEIVED); - OrtpEventData *d=ortp_event_get_data(ev); - d->packet=m; +void rtp_session_notify_inc_rtcp(RtpSession *session, mblk_t *m, bool_t received_via_rtcp_mux) { + if (session->eventqs != NULL) { + OrtpEvent *ev = ortp_event_new(ORTP_EVENT_RTCP_PACKET_RECEIVED); + OrtpEventData *d = ortp_event_get_data(ev); + d->packet = m; d->info.socket_type = received_via_rtcp_mux ? OrtpRTPSocket : OrtpRTCPSocket; - rtp_session_dispatch_event(session,ev); - } - else freemsg(m); /* avoid memory leak */ + rtp_session_dispatch_event(session, ev); + } else freemsg(m); /* avoid memory leak */ } -static void compute_rtt(RtpSession *session, const struct timeval *now, uint32_t lrr, uint32_t dlrr){ - uint64_t curntp=ortp_timeval_to_ntp(now); - uint32_t approx_ntp=(curntp>>16) & 0xFFFFFFFF; +static void compute_rtt(RtpSession *session, const struct timeval *now, uint32_t lrr, uint32_t dlrr) { + uint64_t curntp = ortp_timeval_to_ntp(now); + uint32_t approx_ntp = (curntp >> 16) & 0xFFFFFFFF; /*ortp_message("rtt approx_ntp=%u, lrr=%u, dlrr=%u",approx_ntp,lrr,dlrr);*/ - if (lrr!=0 && dlrr!=0){ + if (lrr != 0 && dlrr != 0) { /*we cast to int32_t to check for crazy RTT time (negative)*/ - double rtt_frac=(int32_t)(approx_ntp-lrr-dlrr); - if (rtt_frac>=0){ - rtt_frac/=65536.0; + double rtt_frac = (int32_t)(approx_ntp - lrr - dlrr); + if (rtt_frac >= 0) { + rtt_frac /= 65536.0; - session->rtt=(float)rtt_frac; + session->rtt = (float)rtt_frac; /*ortp_message("rtt estimated to %f s",session->rtt);*/ - }else ortp_warning("Negative RTT computation, maybe due to clock adjustments."); + } else ortp_warning("Negative RTT computation, maybe due to clock adjustments."); } } @@ -1730,7 +1734,8 @@ static void handle_rtcp_rtpfb_packet(RtpSession *session, mblk_t *block) { if (session->rtcp.tmmbr_info.sent) { rtcp_fb_tmmbr_fci_t *tmmbn_fci = rtcp_RTPFB_tmmbr_get_fci(block); rtcp_fb_tmmbr_fci_t *tmmbr_fci = rtcp_RTPFB_tmmbr_get_fci(session->rtcp.tmmbr_info.sent); - if ((ntohl(tmmbn_fci->ssrc) == rtp_session_get_send_ssrc(session)) && (tmmbn_fci->value == tmmbr_fci->value)) { + if ((ntohl(tmmbn_fci->ssrc) == rtp_session_get_send_ssrc(session)) && + (tmmbn_fci->value == tmmbr_fci->value)) { freemsg(session->rtcp.tmmbr_info.sent); session->rtcp.tmmbr_info.sent = NULL; } @@ -1742,27 +1747,30 @@ static void handle_rtcp_rtpfb_packet(RtpSession *session, mblk_t *block) { } /* - * @brief : for SR packets, retrieves their timestamp, gets the date, and stores these information into the session descriptor. The date values may be used for setting some fields of the report block of the next RTCP packet to be sent. + * @brief : for SR packets, retrieves their timestamp, gets the date, and stores these information into the session + * descriptor. The date values may be used for setting some fields of the report block of the next RTCP packet to be + * sent. * @param session : the current session descriptor. * @param block : the block descriptor that may contain a SR RTCP message. * @return 0 if the packet is a real RTCP packet, -1 otherwise. - * @note a basic parsing is done on the block structure. However, if it fails, no error is returned, and the session descriptor is left as is, so it does not induce any change in the caller procedure behaviour. + * @note a basic parsing is done on the block structure. However, if it fails, no error is returned, and the session + * descriptor is left as is, so it does not induce any change in the caller procedure behaviour. * @note the packet is freed or is taken ownership if -1 is returned */ -static int process_rtcp_packet( RtpSession *session, mblk_t *block, struct sockaddr *addr, socklen_t addrlen ) { +static int process_rtcp_packet(RtpSession *session, mblk_t *block, struct sockaddr *addr, socklen_t addrlen) { rtcp_common_header_t *rtcp; - RtpStream * rtpstream = &session->rtp; + RtpStream *rtpstream = &session->rtp; - int msgsize = (int) ( block->b_wptr - block->b_rptr ); - if ( msgsize < RTCP_COMMON_HEADER_SIZE ) { - ortp_warning( "Receiving a too short RTCP packet" ); + int msgsize = (int)(block->b_wptr - block->b_rptr); + if (msgsize < RTCP_COMMON_HEADER_SIZE) { + ortp_warning("Receiving a too short RTCP packet"); freemsg(block); return -1; } rtcp = (rtcp_common_header_t *)block->b_rptr; - if (rtcp->version != 2){ + if (rtcp->version != 2) { /* try to see if it is a STUN packet */ uint16_t stunlen = *((uint16_t *)(block->b_rptr + sizeof(uint16_t))); stunlen = ntohs(stunlen); @@ -1774,13 +1782,13 @@ static int process_rtcp_packet( RtpSession *session, mblk_t *block, struct socka OrtpEvent *ev = ortp_event_new(ORTP_EVENT_STUN_PACKET_RECEIVED); OrtpEventData *ed = ortp_event_get_data(ev); ed->packet = block; - ed->source_addrlen=addrlen; - memcpy(&ed->source_addr,addr,addrlen); + ed->source_addrlen = addrlen; + memcpy(&ed->source_addr, addr, addrlen); ed->info.socket_type = OrtpRTCPSocket; rtp_session_dispatch_event(session, ev); return -1; } - }else{ + } else { ortp_warning("RtpSession [%p] receiving rtcp packet with version number != 2, discarded", session); } freemsg(block); @@ -1790,48 +1798,52 @@ static int process_rtcp_packet( RtpSession *session, mblk_t *block, struct socka update_recv_bytes(&session->rtcp.gs, (int)(block->b_wptr - block->b_rptr), &block->timestamp); /* compound rtcp packet can be composed by more than one rtcp message */ - do{ + do { struct timeval reception_date; const report_block_t *rb; /* Getting the reception date from the main clock */ - bctbx_gettimeofday( &reception_date, NULL ); + bctbx_gettimeofday(&reception_date, NULL); - if (rtcp_is_SR(block) ) { - rtcp_sr_t *sr = (rtcp_sr_t *) rtcp; + if (rtcp_is_SR(block)) { + rtcp_sr_t *sr = (rtcp_sr_t *)rtcp; /* The session descriptor values are reset in case there is an error in the SR block parsing */ rtpstream->last_rcv_SR_ts = 0; rtpstream->last_rcv_SR_time.tv_usec = 0; rtpstream->last_rcv_SR_time.tv_sec = 0; - if ( ntohl( sr->ssrc ) != session->rcv.ssrc ) { - ortp_debug( "Receiving a RTCP SR packet from an unknown ssrc" ); + if (ntohl(sr->ssrc) != session->rcv.ssrc) { + ortp_debug("Receiving a RTCP SR packet from an unknown ssrc"); return 0; } - if ( msgsize < RTCP_COMMON_HEADER_SIZE + RTCP_SSRC_FIELD_SIZE + RTCP_SENDER_INFO_SIZE + ( RTCP_REPORT_BLOCK_SIZE * sr->ch.rc ) ) { - ortp_debug( "Receiving a too short RTCP SR packet" ); + if (msgsize < RTCP_COMMON_HEADER_SIZE + RTCP_SSRC_FIELD_SIZE + RTCP_SENDER_INFO_SIZE + + (RTCP_REPORT_BLOCK_SIZE * sr->ch.rc)) { + ortp_debug("Receiving a too short RTCP SR packet"); return 0; } /* Saving the data to fill LSR and DLSR field in next RTCP report to be transmitted */ - /* This value will be the LSR field of the next RTCP report (only the central 32 bits are kept, as described in par.4 of RC3550) */ - rtpstream->last_rcv_SR_ts = ( ntohl( sr->si.ntp_timestamp_msw ) << 16 ) | ( ntohl( sr->si.ntp_timestamp_lsw ) >> 16 ); - /* This value will help in processing the DLSR of the next RTCP report ( see report_block_init() in rtcp.cc ) */ + /* This value will be the LSR field of the next RTCP report (only the central 32 bits are kept, as described + * in par.4 of RC3550) */ + rtpstream->last_rcv_SR_ts = + (ntohl(sr->si.ntp_timestamp_msw) << 16) | (ntohl(sr->si.ntp_timestamp_lsw) >> 16); + /* This value will help in processing the DLSR of the next RTCP report ( see report_block_init() in rtcp.cc + * ) */ rtpstream->last_rcv_SR_time.tv_usec = reception_date.tv_usec; rtpstream->last_rcv_SR_time.tv_sec = reception_date.tv_sec; - rb=rtcp_SR_get_report_block(block,0); - if (rb) compute_rtt_from_report_block(session,&reception_date,rb); - }else if ( rtcp_is_RR(block)){ - rb=rtcp_RR_get_report_block(block,0); - if (rb) compute_rtt_from_report_block(session,&reception_date,rb); + rb = rtcp_SR_get_report_block(block, 0); + if (rb) compute_rtt_from_report_block(session, &reception_date, rb); + } else if (rtcp_is_RR(block)) { + rb = rtcp_RR_get_report_block(block, 0); + if (rb) compute_rtt_from_report_block(session, &reception_date, rb); } else if (rtcp_is_XR(block)) { compute_rtcp_xr_statistics(session, block, &reception_date); } else if (rtcp_is_RTPFB(block)) { handle_rtcp_rtpfb_packet(session, block); } - }while (rtcp_next_packet(block)); + } while (rtcp_next_packet(block)); rtcp_rewind(block); rtp_session_update_remote_sock_addr(session, block, FALSE, FALSE); @@ -1844,17 +1856,17 @@ static void reply_to_collaborative_rtcp_xr_packet(RtpSession *session, mblk_t *b } } -static void rtp_process_incoming_packet(RtpSession * session, mblk_t * mp, bool_t is_rtp_packet, uint32_t user_ts, bool_t received_via_rtcp_mux) { - bool_t sock_connected=(is_rtp_packet && !!(session->flags & RTP_SOCKET_CONNECTED)) - || (!is_rtp_packet && !!(session->flags & RTCP_SOCKET_CONNECTED)); +static void rtp_process_incoming_packet( + RtpSession *session, mblk_t *mp, bool_t is_rtp_packet, uint32_t user_ts, bool_t received_via_rtcp_mux) { + bool_t sock_connected = (is_rtp_packet && !!(session->flags & RTP_SOCKET_CONNECTED)) || + (!is_rtp_packet && !!(session->flags & RTCP_SOCKET_CONNECTED)); struct sockaddr *remaddr = NULL; socklen_t addrlen; remaddr = (struct sockaddr *)&mp->net_addr; addrlen = mp->net_addrlen; - - if (session->spliced_session){ + if (session->spliced_session) { /*this will forward all traffic to the spliced session*/ rtp_session_do_splice(session, mp, is_rtp_packet); } @@ -1865,35 +1877,35 @@ static void rtp_process_incoming_packet(RtpSession * session, mblk_t * mp, bool_ * - if a RTP or RTCP packet is received, switch destination. * In all other cases, we don't switch. * This logic is implemented in rtp_session_rtp_parse() and process_rtcp_packet(). - **/ + **/ - if (is_rtp_packet){ - if (session->use_connect && session->symmetric_rtp && !sock_connected ){ + if (is_rtp_packet) { + if (session->use_connect && session->symmetric_rtp && !sock_connected) { /* In the case where use_connect is false, */ - if (try_connect(session->rtp.gs.socket,remaddr,addrlen)) { - session->flags|=RTP_SOCKET_CONNECTED; + if (try_connect(session->rtp.gs.socket, remaddr, addrlen)) { + session->flags |= RTP_SOCKET_CONNECTED; } } /* then parse the message and put on jitter buffer queue */ update_recv_bytes(&session->rtp.gs, (size_t)(mp->b_wptr - mp->b_rptr), &mp->timestamp); - rtp_session_rtp_parse(session, mp, user_ts, remaddr,addrlen); + rtp_session_rtp_parse(session, mp, user_ts, remaddr, addrlen); /*for bandwidth measurements:*/ - }else { - if (session->use_connect && session->symmetric_rtp && !sock_connected){ - if (try_connect(session->rtcp.gs.socket,remaddr,addrlen)) { - session->flags|=RTCP_SOCKET_CONNECTED; + } else { + if (session->use_connect && session->symmetric_rtp && !sock_connected) { + if (try_connect(session->rtcp.gs.socket, remaddr, addrlen)) { + session->flags |= RTCP_SOCKET_CONNECTED; } } - if (process_rtcp_packet(session, mp, remaddr, addrlen) == 0){ + if (process_rtcp_packet(session, mp, remaddr, addrlen) == 0) { /* a copy is needed since rtp_session_notify_inc_rtcp will free the mp, and we don't want to send RTCP XR packet before notifying the application that a message has been received*/ - mblk_t * copy = copymsg(mp); + mblk_t *copy = copymsg(mp); session->stats.recv_rtcp_packets++; /* post an event to notify the application */ rtp_session_notify_inc_rtcp(session, mp, received_via_rtcp_mux); /* reply to collaborative RTCP XR packets if needed. */ - if (session->rtcp.xr_conf.enabled == TRUE){ + if (session->rtcp.xr_conf.enabled == TRUE) { reply_to_collaborative_rtcp_xr_packet(session, copy); } freemsg(copy); @@ -1901,36 +1913,39 @@ static void rtp_process_incoming_packet(RtpSession * session, mblk_t * mp, bool_ } } -void rtp_session_process_incoming(RtpSession * session, mblk_t *mp, bool_t is_rtp_packet, uint32_t ts, bool_t received_via_rtcp_mux) { +void rtp_session_process_incoming( + RtpSession *session, mblk_t *mp, bool_t is_rtp_packet, uint32_t ts, bool_t received_via_rtcp_mux) { if (session->net_sim_ctx && session->net_sim_ctx->params.mode == OrtpNetworkSimulatorInbound) { /*drain possible packets queued in the network simulator*/ mp = rtp_session_network_simulate(session, mp, &is_rtp_packet); - if (mp) rtp_process_incoming_packet(session, mp, is_rtp_packet, ts, received_via_rtcp_mux); /*BUG here: received_via_rtcp_mux is not preserved by network simulator*/ + if (mp) + rtp_process_incoming_packet( + session, mp, is_rtp_packet, ts, + received_via_rtcp_mux); /*BUG here: received_via_rtcp_mux is not preserved by network simulator*/ } else if (mp != NULL) { rtp_process_incoming_packet(session, mp, is_rtp_packet, ts, received_via_rtcp_mux); } } - -static mblk_t *rtp_session_alloc_recv_block(RtpSession *session){ +static mblk_t *rtp_session_alloc_recv_block(RtpSession *session) { mblk_t *m = NULL; -#if defined(_WIN32) || defined(_WIN32_WCE) +#if defined(_WIN32) || defined(_WIN32_WCE) ortp_mutex_lock(&session->rtp.winrq_lock); #endif - if ((m = session->recv_block_cache) != NULL){ + if ((m = session->recv_block_cache) != NULL) { session->recv_block_cache = NULL; } -#if defined(_WIN32) || defined(_WIN32_WCE) +#if defined(_WIN32) || defined(_WIN32_WCE) ortp_mutex_unlock(&session->rtp.winrq_lock); #endif - if (!m){ + if (!m) { m = allocb(session->recv_buf_size, 0); } return m; } -static void rtp_session_recycle_recv_block(RtpSession *session, mblk_t *m){ - if (dblk_ref_value(m->b_datap) > 1){ +static void rtp_session_recycle_recv_block(RtpSession *session, mblk_t *m) { + if (dblk_ref_value(m->b_datap) > 1) { /* The mblk_t may have been duplicated by the RtpTransport/RtpModifier. We shall consider the underlying buffer * cannot be used anymore */ ortp_warning("The RtpTransport has kept a ref on a mblk_t's underlying buffer. This prevents recycling."); @@ -1940,100 +1955,106 @@ static void rtp_session_recycle_recv_block(RtpSession *session, mblk_t *m){ /* Reset read, write pointers to their original place. Indeed the RtpTransport/RtpModifier may have play * with them before discarding the mblk_t. */ m->b_wptr = m->b_rptr = m->b_datap->db_base; -#if defined(_WIN32) || defined(_WIN32_WCE) +#if defined(_WIN32) || defined(_WIN32_WCE) ortp_mutex_lock(&session->rtp.winrq_lock); #endif - if (session->recv_block_cache == NULL){ + if (session->recv_block_cache == NULL) { session->recv_block_cache = m; -#if defined(_WIN32) || defined(_WIN32_WCE) +#if defined(_WIN32) || defined(_WIN32_WCE) ortp_mutex_unlock(&session->rtp.winrq_lock); - }else{ + } else { ortp_mutex_unlock(&session->rtp.winrq_lock); #else - }else{ + } else { #endif ortp_error("Should not happen"); freeb(m); } } - -void* rtp_session_recvfrom_async(void* obj) { - RtpSession *session = (RtpSession*) obj; +void *rtp_session_recvfrom_async(void *obj) { + RtpSession *session = (RtpSession *)obj; int error; struct sockaddr_storage remaddr; - socklen_t addrlen = sizeof (remaddr); + socklen_t addrlen = sizeof(remaddr); mblk_t *mp; -#if defined(_WIN32) || defined(_WIN32_WCE) +#if defined(_WIN32) || defined(_WIN32_WCE) WSAPOLLFD fdarray = {0}; fdarray.fd = session->rtp.gs.socket; fdarray.events = POLLRDNORM; - if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST)){ + if (!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST)) { ortp_warning("Error rtp recv async thread for windows: SetThreadPriority() failed [%d]\n", (int)GetLastError()); } - while(session->rtp.is_win_thread_running) - { + while (session->rtp.is_win_thread_running) { int ret = WSAPoll(&fdarray, 1, 10); if (ret == SOCKET_ERROR) { ortp_warning("Error rtp recv async thread for windows: error while polling [%i]", WSAGetLastError()); } else if (ret > 0) { #endif - bool_t sock_connected=!!(session->flags & RTP_SOCKET_CONNECTED); + bool_t sock_connected = !!(session->flags & RTP_SOCKET_CONNECTED); mp = rtp_session_alloc_recv_block(session); - if (sock_connected){ + if (sock_connected) { error = rtp_session_recvfrom(session, TRUE, mp, 0, NULL, NULL); - }else if (rtp_session_using_transport(session, rtp)) { - error = (session->rtp.gs.tr->t_recvfrom)(session->rtp.gs.tr, mp, 0, (struct sockaddr *) &remaddr, &addrlen); + } else if (rtp_session_using_transport(session, rtp)) { + error = + (session->rtp.gs.tr->t_recvfrom)(session->rtp.gs.tr, mp, 0, (struct sockaddr *)&remaddr, &addrlen); } else { - error = rtp_session_recvfrom(session, TRUE, mp, 0, (struct sockaddr *) &remaddr, &addrlen); + error = rtp_session_recvfrom(session, TRUE, mp, 0, (struct sockaddr *)&remaddr, &addrlen); } if (error > 0) { - if (mp->timestamp.tv_sec == 0){ - static int warn_once = 1; /*VERY BAD to use a static but there is no context in this function to hold this variable*/ - if (warn_once){ - ortp_warning("The transport layer doesn't implement SO_TIMESTAMP, will use gettimeofday() instead."); + if (mp->timestamp.tv_sec == 0) { + static int warn_once = + 1; /*VERY BAD to use a static but there is no context in this function to hold this variable*/ + if (warn_once) { + ortp_warning( + "The transport layer doesn't implement SO_TIMESTAMP, will use gettimeofday() instead."); warn_once = 0; } bctbx_gettimeofday(&mp->timestamp, NULL); } - mp->b_wptr+=error; + mp->b_wptr += error; -#if defined(_WIN32) || defined(_WIN32_WCE) +#if defined(_WIN32) || defined(_WIN32_WCE) ortp_mutex_lock(&session->rtp.winrq_lock); #endif putq(&session->rtp.winrq, mp); -#if defined(_WIN32) || defined(_WIN32_WCE) +#if defined(_WIN32) || defined(_WIN32_WCE) ortp_mutex_unlock(&session->rtp.winrq_lock); #endif } else { int errnum; - if (error==-1 && !is_would_block_error((errnum=getSocketErrorCode())) ) - { - if (session->on_network_error.count>0){ - rtp_signal_table_emit3(&session->on_network_error,"Error receiving RTP packet",ORTP_INT_TO_POINTER(getSocketErrorCode())); - #ifdef _WIN32 - }else if(errnum!=WSAECONNRESET) ortp_warning("Error receiving RTP packet err num [%i], error [%i]: %s",errnum,error,getSocketError());// Windows spam WSAECONNRESET and is not useful - #else - }else ortp_warning("Error receiving RTP packet err num [%i], error [%i]: %s",errnum,error,getSocketError()); - #endif - #if TARGET_OS_IPHONE + if (error == -1 && !is_would_block_error((errnum = getSocketErrorCode()))) { + if (session->on_network_error.count > 0) { + rtp_signal_table_emit3(&session->on_network_error, "Error receiving RTP packet", + ORTP_INT_TO_POINTER(getSocketErrorCode())); +#ifdef _WIN32 + } else if (errnum != WSAECONNRESET) + ortp_warning("Error receiving RTP packet err num [%i], error [%i]: %s", errnum, error, + getSocketError()); // Windows spam WSAECONNRESET and is not useful +#else + } else + ortp_warning("Error receiving RTP packet err num [%i], error [%i]: %s", errnum, error, + getSocketError()); +#endif +#if TARGET_OS_IPHONE /*hack for iOS and non-working socket because of background mode*/ - if (errnum==ENOTCONN){ + if (errnum == ENOTCONN) { /*re-create new sockets */ - rtp_session_set_local_addr(session,session->rtp.gs.sockfamily==AF_INET ? "0.0.0.0" : "::0",session->rtp.gs.loc_port,session->rtcp.gs.loc_port); + rtp_session_set_local_addr(session, session->rtp.gs.sockfamily == AF_INET ? "0.0.0.0" : "::0", + session->rtp.gs.loc_port, session->rtcp.gs.loc_port); } - #endif +#endif } rtp_session_recycle_recv_block(session, mp); } -#if defined(_WIN32) || defined(_WIN32_WCE) +#if defined(_WIN32) || defined(_WIN32_WCE) } } #endif @@ -2041,24 +2062,25 @@ void* rtp_session_recvfrom_async(void* obj) { return NULL; } -int rtp_session_rtp_recv (RtpSession * session, uint32_t user_ts) { +int rtp_session_rtp_recv(RtpSession *session, uint32_t user_ts) { mblk_t *mp; bool_t more_data = TRUE; RtpBundle *bundle = session->bundle; - if ((session->rtp.gs.socket==(ortp_socket_t)-1) && !rtp_session_using_transport(session, rtp)) return -1; /*session has no sockets for the moment*/ - + if ((session->rtp.gs.socket == (ortp_socket_t)-1) && !rtp_session_using_transport(session, rtp)) + return -1; /*session has no sockets for the moment*/ do { bool_t packet_is_rtp = TRUE; if (!bundle || (bundle && session->is_primary)) { -#if defined(_WIN32) || defined(_WIN32_WCE) +#if defined(_WIN32) || defined(_WIN32_WCE) ortp_mutex_lock(&session->rtp.winthread_lock); if (!session->rtp.is_win_thread_running) { int errnum; session->rtp.is_win_thread_running = TRUE; - if ((errnum = ortp_thread_create(&session->rtp.win_t, NULL, rtp_session_recvfrom_async, (void*)session)) != 0) { + if ((errnum = ortp_thread_create(&session->rtp.win_t, NULL, rtp_session_recvfrom_async, + (void *)session)) != 0) { ortp_warning("Error creating rtp recv async thread for windows: error [%i]", errnum); session->rtp.is_win_thread_running = FALSE; return -1; @@ -2066,32 +2088,32 @@ int rtp_session_rtp_recv (RtpSession * session, uint32_t user_ts) { } ortp_mutex_unlock(&session->rtp.winthread_lock); #else - rtp_session_recvfrom_async((void*)session); + rtp_session_recvfrom_async((void *)session); #endif -#if defined(_WIN32) || defined(_WIN32_WCE) +#if defined(_WIN32) || defined(_WIN32_WCE) ortp_mutex_lock(&session->rtp.winrq_lock); #endif mp = getq(&session->rtp.winrq); -#if defined(_WIN32) || defined(_WIN32_WCE) +#if defined(_WIN32) || defined(_WIN32_WCE) ortp_mutex_unlock(&session->rtp.winrq_lock); #endif - if (mp){ - /* we got a packet from a primary transport. If bundle mode is on, it may be dispatched to another session, or - * may be re-qualified as RTCP (rtcp-mux) */ - if (session->rtcp_mux || bundle){ - if (rtp_get_version(mp) == 2){ + if (mp) { + /* we got a packet from a primary transport. If bundle mode is on, it may be dispatched to another + * session, or may be re-qualified as RTCP (rtcp-mux) */ + if (session->rtcp_mux || bundle) { + if (rtp_get_version(mp) == 2) { int pt = rtp_get_payload_type(mp); - if (pt >= 64 && pt <= 95){ + if (pt >= 64 && pt <= 95) { /*this is assumed to be an RTCP packet*/ packet_is_rtp = FALSE; } } } - if (bundle && rtp_bundle_dispatch(bundle, packet_is_rtp, mp)){ + if (bundle && rtp_bundle_dispatch(bundle, packet_is_rtp, mp)) { /* the packet has been dispatched to another session. */ mp = NULL; } - }else{ + } else { more_data = FALSE; } } else { @@ -2106,60 +2128,61 @@ int rtp_session_rtp_recv (RtpSession * session, uint32_t user_ts) { return -1; } -int rtp_session_rtcp_recv (RtpSession * session) { +int rtp_session_rtcp_recv(RtpSession *session) { int error; struct sockaddr_storage remaddr; - socklen_t addrlen = sizeof (remaddr); + socklen_t addrlen = sizeof(remaddr); mblk_t *mp; - if (session->rtcp.gs.socket==(ortp_socket_t)-1 && !rtp_session_using_transport(session, rtcp)) return -1; /*session has no RTCP sockets for the moment*/ + if (session->rtcp.gs.socket == (ortp_socket_t)-1 && !rtp_session_using_transport(session, rtcp)) + return -1; /*session has no RTCP sockets for the moment*/ /* In bundle mode, rtcp-mux is used. There is nothing that needs to be read on the rtcp socket. * The RTCP packets are received on the RTP socket, and dispatched to the "bundleq" of their corresponding session. * These RTCP packets queued on the bundleq will be processed by rtp_session_rtp_recv(), which has the ability to * manage rtcp-mux. */ - while (1) - { - bool_t sock_connected=!!(session->flags & RTCP_SOCKET_CONNECTED); + while (1) { + bool_t sock_connected = !!(session->flags & RTCP_SOCKET_CONNECTED); mp = NULL; - if (!session->bundle){ + if (!session->bundle) { mp = rtp_session_alloc_recv_block(session); - if (sock_connected){ - error=rtp_session_recvfrom(session, FALSE, mp, 0, NULL, NULL); - }else{ - addrlen=sizeof (remaddr); - - if (rtp_session_using_transport(session, rtcp)){ - error=(session->rtcp.gs.tr->t_recvfrom)(session->rtcp.gs.tr, mp, 0, - (struct sockaddr *) &remaddr, - &addrlen); - }else{ - error=rtp_session_recvfrom(session, FALSE, mp, 0, - (struct sockaddr *) &remaddr, - &addrlen); + if (sock_connected) { + error = rtp_session_recvfrom(session, FALSE, mp, 0, NULL, NULL); + } else { + addrlen = sizeof(remaddr); + + if (rtp_session_using_transport(session, rtcp)) { + error = (session->rtcp.gs.tr->t_recvfrom)(session->rtcp.gs.tr, mp, 0, (struct sockaddr *)&remaddr, + &addrlen); + } else { + error = rtp_session_recvfrom(session, FALSE, mp, 0, (struct sockaddr *)&remaddr, &addrlen); } } - if (error > 0){ + if (error > 0) { mp->b_wptr += error; if (mp->timestamp.tv_sec == 0) bctbx_gettimeofday(&mp->timestamp, NULL); - }else{ + } else { int errnum; - if (error==-1 && !is_would_block_error((errnum=getSocketErrorCode())) ){ - if (session->on_network_error.count>0){ - rtp_signal_table_emit3(&session->on_network_error,"Error receiving RTCP packet",ORTP_INT_TO_POINTER(getSocketErrorCode())); - }else ortp_warning("Error receiving RTCP packet: %s, err num [%i],error [%i]",getSocketError(),errnum,error); - #if TARGET_OS_IPHONE + if (error == -1 && !is_would_block_error((errnum = getSocketErrorCode()))) { + if (session->on_network_error.count > 0) { + rtp_signal_table_emit3(&session->on_network_error, "Error receiving RTCP packet", + ORTP_INT_TO_POINTER(getSocketErrorCode())); + } else + ortp_warning("Error receiving RTCP packet: %s, err num [%i],error [%i]", getSocketError(), + errnum, error); +#if TARGET_OS_IPHONE /*hack for iOS and non-working socket because of background mode*/ - if (errnum==ENOTCONN){ + if (errnum == ENOTCONN) { /*re-create new sockets */ - rtp_session_set_local_addr(session,session->rtcp.gs.sockfamily==AF_INET ? "0.0.0.0" : "::0",session->rtcp.gs.loc_port,session->rtcp.gs.loc_port); + rtp_session_set_local_addr(session, session->rtcp.gs.sockfamily == AF_INET ? "0.0.0.0" : "::0", + session->rtcp.gs.loc_port, session->rtcp.gs.loc_port); } - #endif - session->rtp.recv_errno=errnum; - }else{ +#endif + session->rtp.recv_errno = errnum; + } else { /*EWOULDBLOCK errors or transports returning 0 are ignored.*/ rtp_session_process_incoming(session, NULL, FALSE, session->rtp.rcv_last_app_ts, FALSE); } @@ -2167,30 +2190,29 @@ int rtp_session_rtcp_recv (RtpSession * session) { rtp_session_recycle_recv_block(session, mp); mp = NULL; } - }else if (!session->is_primary){ + } else if (!session->is_primary) { /* case where we are part of a bundle as a secondary session */ ortp_mutex_lock(&session->rtcp.gs.bundleq_lock); mp = getq(&session->rtcp.gs.bundleq); ortp_mutex_unlock(&session->rtcp.gs.bundleq_lock); } - if (mp){ + if (mp) { rtp_session_process_incoming(session, mp, FALSE, session->rtp.rcv_last_app_ts, FALSE); - }else break; + } else break; } return 0; } -int rtp_session_update_remote_sock_addr(RtpSession * session, mblk_t * mp, bool_t is_rtp,bool_t only_at_start) { - struct sockaddr_storage * rem_addr = NULL; +int rtp_session_update_remote_sock_addr(RtpSession *session, mblk_t *mp, bool_t is_rtp, bool_t only_at_start) { + struct sockaddr_storage *rem_addr = NULL; socklen_t *rem_addrlen; - const char* socket_type; + const char *socket_type; bool_t sock_connected; bool_t do_address_change = /*(rtp_get_version(mp) == 2 && */ !only_at_start; - if (!rtp_session_get_symmetric_rtp(session)) - return -1; /*nothing to try if not rtp symetric*/ + if (!rtp_session_get_symmetric_rtp(session)) return -1; /*nothing to try if not rtp symetric*/ - if (session->bundle && !session->is_primary){ + if (session->bundle && !session->is_primary) { /* A session part of a bundle not owning the transport layer shall not update remote address.*/ return -1; } @@ -2199,37 +2221,36 @@ int rtp_session_update_remote_sock_addr(RtpSession * session, mblk_t * mp, bool_ rem_addrlen = &session->rtp.gs.rem_addrlen; socket_type = "rtp"; sock_connected = session->flags & RTP_SOCKET_CONNECTED; - do_address_change = session->rtp.gs.socket != (ortp_socket_t)-1 && ( do_address_change || rtp_session_get_stats(session)->packet_recv == 0); + do_address_change = session->rtp.gs.socket != (ortp_socket_t)-1 && + (do_address_change || rtp_session_get_stats(session)->packet_recv == 0); } else { rem_addr = &session->rtcp.gs.rem_addr; rem_addrlen = &session->rtcp.gs.rem_addrlen; sock_connected = session->flags & RTCP_SOCKET_CONNECTED; socket_type = "rtcp"; - do_address_change = session->rtcp.gs.socket != (ortp_socket_t)-1 && (do_address_change || rtp_session_get_stats(session)->recv_rtcp_packets == 0); - } - - if (do_address_change - && rem_addr - && !sock_connected - && !bctbx_is_multicast_addr((const struct sockaddr*)rem_addr) - && memcmp(rem_addr,&mp->net_addr,mp->net_addrlen) !=0) { - char current_ip_address[64]={0}; - char new_ip_address[64]={0}; - - bctbx_sockaddr_to_printable_ip_address((struct sockaddr *)rem_addr, *rem_addrlen, current_ip_address, sizeof(current_ip_address)); - bctbx_sockaddr_to_printable_ip_address((struct sockaddr *)&mp->net_addr, mp->net_addrlen, new_ip_address, sizeof(new_ip_address)); - ortp_message("Switching %s destination from %s to %s for session [%p]" - , socket_type - , current_ip_address - , new_ip_address - , session); - - memcpy(rem_addr,&mp->net_addr,mp->net_addrlen); + do_address_change = session->rtcp.gs.socket != (ortp_socket_t)-1 && + (do_address_change || rtp_session_get_stats(session)->recv_rtcp_packets == 0); + } + + if (do_address_change && rem_addr && !sock_connected && + !bctbx_is_multicast_addr((const struct sockaddr *)rem_addr) && + memcmp(rem_addr, &mp->net_addr, mp->net_addrlen) != 0) { + char current_ip_address[64] = {0}; + char new_ip_address[64] = {0}; + + bctbx_sockaddr_to_printable_ip_address((struct sockaddr *)rem_addr, *rem_addrlen, current_ip_address, + sizeof(current_ip_address)); + bctbx_sockaddr_to_printable_ip_address((struct sockaddr *)&mp->net_addr, mp->net_addrlen, new_ip_address, + sizeof(new_ip_address)); + ortp_message("Switching %s destination from %s to %s for session [%p]", socket_type, current_ip_address, + new_ip_address, session); + + memcpy(rem_addr, &mp->net_addr, mp->net_addrlen); *rem_addrlen = mp->net_addrlen; #ifdef WIN32 - if (is_rtp){ + if (is_rtp) { /*re-apply dscp settings for the new destination (windows specific).*/ - rtp_session_set_dscp( session, -1 ); + rtp_session_set_dscp(session, -1); } #endif return 0; @@ -2237,27 +2258,26 @@ int rtp_session_update_remote_sock_addr(RtpSession * session, mblk_t * mp, bool_ return -1; } -void rtp_session_use_local_addr(RtpSession * session, const char * rtp_local_addr, const char * rtcp_local_addr) { - struct addrinfo * session_addr_info; - if(rtp_local_addr[0] != '\0') - {// rtp_local_addr should not be NULL - session_addr_info = bctbx_ip_address_to_addrinfo(session->rtp.gs.sockfamily , SOCK_DGRAM ,rtp_local_addr, 0); +void rtp_session_use_local_addr(RtpSession *session, const char *rtp_local_addr, const char *rtcp_local_addr) { + struct addrinfo *session_addr_info; + if (rtp_local_addr[0] != '\0') { // rtp_local_addr should not be NULL + session_addr_info = bctbx_ip_address_to_addrinfo(session->rtp.gs.sockfamily, SOCK_DGRAM, rtp_local_addr, 0); memcpy(&session->rtp.gs.used_loc_addr, session_addr_info->ai_addr, session_addr_info->ai_addrlen); session->rtp.gs.used_loc_addrlen = (socklen_t)session_addr_info->ai_addrlen; bctbx_freeaddrinfo(session_addr_info); - }else { + } else { session->rtp.gs.used_loc_addrlen = 0; - memset(&session->rtp.gs.used_loc_addr, 0, sizeof(session->rtp.gs.used_loc_addr));// To not let tracks on memory + memset(&session->rtp.gs.used_loc_addr, 0, sizeof(session->rtp.gs.used_loc_addr)); // To not let tracks on memory } - if(rtcp_local_addr[0] != '\0') - {// rtcp_local_addr should not be NULL - session_addr_info = bctbx_ip_address_to_addrinfo(session->rtcp.gs.sockfamily , SOCK_DGRAM ,rtcp_local_addr, 0); + if (rtcp_local_addr[0] != '\0') { // rtcp_local_addr should not be NULL + session_addr_info = bctbx_ip_address_to_addrinfo(session->rtcp.gs.sockfamily, SOCK_DGRAM, rtcp_local_addr, 0); memcpy(&session->rtcp.gs.used_loc_addr, session_addr_info->ai_addr, session_addr_info->ai_addrlen); session->rtcp.gs.used_loc_addrlen = (socklen_t)session_addr_info->ai_addrlen; bctbx_freeaddrinfo(session_addr_info); - }else { + } else { session->rtcp.gs.used_loc_addrlen = 0; - memset(&session->rtcp.gs.used_loc_addr, 0, sizeof(session->rtcp.gs.used_loc_addr));// To not let tracks on memory + memset(&session->rtcp.gs.used_loc_addr, 0, + sizeof(session->rtcp.gs.used_loc_addr)); // To not let tracks on memory } - ortp_message("RtpSession set sources to [%s] and [%s]",rtp_local_addr, rtcp_local_addr ); + ortp_message("RtpSession set sources to [%s] and [%s]", rtp_local_addr, rtcp_local_addr); } diff --git a/src/rtpsession_priv.h b/src/rtpsession_priv.h index 83471ee3..d9d27480 100644 --- a/src/rtpsession_priv.h +++ b/src/rtpsession_priv.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -29,52 +29,54 @@ #define RTCP_XR_GMIN 16 /* Recommended value of Gmin from RFC3611, section 4.7.6 */ typedef enum { - RTP_SESSION_RECV_SYNC=1, /* the rtp session is synchronising in the incoming stream */ - RTP_SESSION_FIRST_PACKET_DELIVERED=1<<1, - RTP_SESSION_SCHEDULED=1<<2,/* the scheduler controls this session*/ - RTP_SESSION_BLOCKING_MODE=1<<3, /* in blocking mode */ - RTP_SESSION_RECV_NOT_STARTED=1<<4, /* the application has not started to try to recv */ - RTP_SESSION_SEND_NOT_STARTED=1<<5, /* the application has not started to send something */ - RTP_SESSION_IN_SCHEDULER=1<<6, /* the rtp session is in the scheduler list */ - RTP_SESSION_USING_EXT_SOCKETS=1<<7, /* the session is using externaly supplied sockets */ - RTP_SOCKET_CONNECTED=1<<8, - RTCP_SOCKET_CONNECTED=1<<9, - RTP_SESSION_USING_TRANSPORT=1<<10, - RTCP_OVERRIDE_LOST_PACKETS=1<<11, - RTCP_OVERRIDE_JITTER=1<<12, - RTCP_OVERRIDE_DELAY=1<<13, - RTP_SESSION_RECV_SEQ_INIT=1<<14, - RTP_SESSION_FLUSH=1<<15, - RTP_SESSION_SOCKET_REFRESH_REQUESTED=1<<16 -}RtpSessionFlags; + RTP_SESSION_RECV_SYNC = 1, /* the rtp session is synchronising in the incoming stream */ + RTP_SESSION_FIRST_PACKET_DELIVERED = 1 << 1, + RTP_SESSION_SCHEDULED = 1 << 2, /* the scheduler controls this session*/ + RTP_SESSION_BLOCKING_MODE = 1 << 3, /* in blocking mode */ + RTP_SESSION_RECV_NOT_STARTED = 1 << 4, /* the application has not started to try to recv */ + RTP_SESSION_SEND_NOT_STARTED = 1 << 5, /* the application has not started to send something */ + RTP_SESSION_IN_SCHEDULER = 1 << 6, /* the rtp session is in the scheduler list */ + RTP_SESSION_USING_EXT_SOCKETS = 1 << 7, /* the session is using externaly supplied sockets */ + RTP_SOCKET_CONNECTED = 1 << 8, + RTCP_SOCKET_CONNECTED = 1 << 9, + RTP_SESSION_USING_TRANSPORT = 1 << 10, + RTCP_OVERRIDE_LOST_PACKETS = 1 << 11, + RTCP_OVERRIDE_JITTER = 1 << 12, + RTCP_OVERRIDE_DELAY = 1 << 13, + RTP_SESSION_RECV_SEQ_INIT = 1 << 14, + RTP_SESSION_FLUSH = 1 << 15, + RTP_SESSION_SOCKET_REFRESH_REQUESTED = 1 << 16 +} RtpSessionFlags; #define rtp_session_using_transport(s, stream) (((s)->flags & RTP_SESSION_USING_TRANSPORT) && (s->stream.gs.tr != 0)) -int rtp_session_rtp_recv_abstract(ortp_socket_t socket, mblk_t *msg, int flags, struct sockaddr *from, socklen_t *fromlen); +int rtp_session_rtp_recv_abstract( + ortp_socket_t socket, mblk_t *msg, int flags, struct sockaddr *from, socklen_t *fromlen); -void rtp_session_update_payload_type(RtpSession * session, int pt); +void rtp_session_update_payload_type(RtpSession *session, int pt); int rtp_putq(queue_t *q, mblk_t *mp); -mblk_t * rtp_peekq(queue_t *q, uint32_t ts, int *rejected); -int rtp_session_rtp_recv(RtpSession * session, uint32_t ts); -int rtp_session_rtcp_recv(RtpSession * session); -int rtp_session_rtp_send (RtpSession * session, mblk_t * m); +mblk_t *rtp_peekq(queue_t *q, uint32_t ts, int *rejected); +int rtp_session_rtp_recv(RtpSession *session, uint32_t ts); +int rtp_session_rtcp_recv(RtpSession *session); +int rtp_session_rtp_send(RtpSession *session, mblk_t *m); #define rtp_session_rtcp_send rtp_session_rtcp_sendm_raw -void rtp_session_rtp_parse(RtpSession *session, mblk_t *mp, uint32_t local_str_ts, struct sockaddr *addr, socklen_t addrlen); +void rtp_session_rtp_parse( + RtpSession *session, mblk_t *mp, uint32_t local_str_ts, struct sockaddr *addr, socklen_t addrlen); void rtp_session_run_rtcp_send_scheduler(RtpSession *session); void update_avg_rtcp_size(RtpSession *session, int bytes); -mblk_t * rtp_session_network_simulate(RtpSession *session, mblk_t *input, bool_t *is_rtp_packet); +mblk_t *rtp_session_network_simulate(RtpSession *session, mblk_t *input, bool_t *is_rtp_packet); void ortp_network_simulator_destroy(OrtpNetworkSimulatorCtx *sim); -void rtcp_common_header_init(rtcp_common_header_t *ch, RtpSession *s,int type, int rc, size_t bytes_len); +void rtcp_common_header_init(rtcp_common_header_t *ch, RtpSession *s, int type, int rc, size_t bytes_len); -mblk_t * make_xr_rcvr_rtt(RtpSession *session); -mblk_t * make_xr_dlrr(RtpSession *session); -mblk_t * make_xr_stat_summary(RtpSession *session); -mblk_t * make_xr_voip_metrics(RtpSession *session); +mblk_t *make_xr_rcvr_rtt(RtpSession *session); +mblk_t *make_xr_dlrr(RtpSession *session); +mblk_t *make_xr_stat_summary(RtpSession *session); +mblk_t *make_xr_voip_metrics(RtpSession *session); bool_t rtcp_is_RTPFB_internal(const mblk_t *m); bool_t rtcp_is_PSFB_internal(const mblk_t *m); @@ -96,7 +98,8 @@ void rtp_session_do_splice(RtpSession *session, mblk_t *packet, bool_t is_rtp); /* * Update remote addr in the following case: - * rtp symetric == TRUE && socket not connected && remote addr has changed && ((rtp/rtcp packet && not only at start) or (no rtp/rtcp packets received)) + * rtp symetric == TRUE && socket not connected && remote addr has changed && ((rtp/rtcp packet && not only at start) or + * (no rtp/rtcp packets received)) * @param[in] session on which to perform change * @param[in] mp packet where remote addr is retreived * @param[in] is_rtp true if rtp @@ -104,10 +107,11 @@ void rtp_session_do_splice(RtpSession *session, mblk_t *packet, bool_t is_rtp); * @return 0 if chaged was performed * */ - -int rtp_session_update_remote_sock_addr(RtpSession * session, mblk_t * mp, bool_t is_rtp,bool_t only_at_start); -void rtp_session_process_incoming(RtpSession * session, mblk_t *mp, bool_t is_rtp_packet, uint32_t ts, bool_t received_via_rtcp_mux); +int rtp_session_update_remote_sock_addr(RtpSession *session, mblk_t *mp, bool_t is_rtp, bool_t only_at_start); + +void rtp_session_process_incoming( + RtpSession *session, mblk_t *mp, bool_t is_rtp_packet, uint32_t ts, bool_t received_via_rtcp_mux); void update_sent_bytes(OrtpStream *os, int nbytes); void _rtp_session_apply_socket_sizes(RtpSession *session); @@ -117,5 +121,4 @@ void rtp_session_init_jitter_buffer(RtpSession *session); size_t rtp_session_calculate_packet_header_size(RtpSession *session); - #endif diff --git a/src/rtpsignaltable.c b/src/rtpsignaltable.c index e3cd70f4..6f829453 100644 --- a/src/rtpsignaltable.c +++ b/src/rtpsignaltable.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -22,26 +22,23 @@ #include "ortp-config.h" #endif -#include #include "utils.h" +#include - -void rtp_signal_table_init(RtpSignalTable *table,RtpSession *session, const char *signal_name) -{ - memset(table,0,sizeof(RtpSignalTable)); - table->session=session; - table->signal_name=signal_name; - session->signal_tables=o_list_append(session->signal_tables,(void*)table); +void rtp_signal_table_init(RtpSignalTable *table, RtpSession *session, const char *signal_name) { + memset(table, 0, sizeof(RtpSignalTable)); + table->session = session; + table->signal_name = signal_name; + session->signal_tables = o_list_append(session->signal_tables, (void *)table); } -int rtp_signal_table_add(RtpSignalTable *table,RtpCallback cb, void *user_data) -{ +int rtp_signal_table_add(RtpSignalTable *table, RtpCallback cb, void *user_data) { int i; - for (i=0;icallback[i]==NULL){ - table->callback[i]=cb; - table->user_data[i]=user_data; + for (i = 0; i < RTP_CALLBACK_TABLE_MAX_ENTRIES; i++) { + if (table->callback[i] == NULL) { + table->callback[i] = cb; + table->user_data[i] = user_data; table->count++; return 0; } @@ -49,51 +46,46 @@ int rtp_signal_table_add(RtpSignalTable *table,RtpCallback cb, void *user_data) return -1; } +void rtp_signal_table_emit(RtpSignalTable *table) { + int i, c; -void rtp_signal_table_emit(RtpSignalTable *table) -{ - int i,c; - - for (i=0,c=0;ccount;i++){ - if (table->callback[i]!=NULL){ - c++; /*I like it*/ - table->callback[i](table->session,table->user_data[i],0,0); + for (i = 0, c = 0; c < table->count; i++) { + if (table->callback[i] != NULL) { + c++; /*I like it*/ + table->callback[i](table->session, table->user_data[i], 0, 0); } } } -void rtp_signal_table_emit2(RtpSignalTable *table, void *arg) -{ - int i,c; +void rtp_signal_table_emit2(RtpSignalTable *table, void *arg) { + int i, c; - for (i=0,c=0;ccount;i++){ - if (table->callback[i]!=NULL){ - c++; /*I like it*/ - table->callback[i](table->session,arg,table->user_data[i],0); + for (i = 0, c = 0; c < table->count; i++) { + if (table->callback[i] != NULL) { + c++; /*I like it*/ + table->callback[i](table->session, arg, table->user_data[i], 0); } } } -void rtp_signal_table_emit3(RtpSignalTable *table, void *arg1, void *arg2) -{ - int i,c; +void rtp_signal_table_emit3(RtpSignalTable *table, void *arg1, void *arg2) { + int i, c; - for (i=0,c=0;ccount;i++){ - if (table->callback[i]!=NULL){ - c++; /*I like it*/ - table->callback[i](table->session,arg1,arg2,table->user_data[i]); + for (i = 0, c = 0; c < table->count; i++) { + if (table->callback[i] != NULL) { + c++; /*I like it*/ + table->callback[i](table->session, arg1, arg2, table->user_data[i]); } } } -int rtp_signal_table_remove_by_callback(RtpSignalTable *table,RtpCallback cb) -{ +int rtp_signal_table_remove_by_callback(RtpSignalTable *table, RtpCallback cb) { int i; - for (i=0;icallback[i]==cb){ - table->callback[i]=NULL; - table->user_data[i]=0; + for (i = 0; i < RTP_CALLBACK_TABLE_MAX_ENTRIES; i++) { + if (table->callback[i] == cb) { + table->callback[i] = NULL; + table->user_data[i] = 0; table->count--; return 0; } diff --git a/src/rtptimer.c b/src/rtptimer.c index 495f7ce7..6608c5e1 100644 --- a/src/rtptimer.c +++ b/src/rtptimer.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,17 +18,14 @@ * along with this program. If not, see . */ -#include "ortp/ortp.h" #include "rtptimer.h" +#include "ortp/ortp.h" -void rtp_timer_set_interval(RtpTimer *timer, struct timeval *interval) -{ - if (timer->state==RTP_TIMER_RUNNING){ +void rtp_timer_set_interval(RtpTimer *timer, struct timeval *interval) { + if (timer->state == RTP_TIMER_RUNNING) { ortp_warning("Cannot change timer interval while it is running.\n"); return; } - timer->interval.tv_sec=interval->tv_sec; - timer->interval.tv_usec=interval->tv_usec; + timer->interval.tv_sec = interval->tv_sec; + timer->interval.tv_usec = interval->tv_usec; } - - diff --git a/src/rtptimer.h b/src/rtptimer.h index 30b786fe..5a9f2b85 100644 --- a/src/rtptimer.h +++ b/src/rtptimer.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -21,20 +21,18 @@ #ifndef RTPTIMER_H #define RTPTIMER_H -#if !defined(_WIN32) && !defined(_WIN32_WCE) +#if !defined(_WIN32) && !defined(_WIN32_WCE) #include #else -#include #include "winsock2.h" +#include #endif #include - typedef void (*RtpTimerFunc)(void); - -struct _RtpTimer -{ + +struct _RtpTimer { int state; #define RTP_TIMER_RUNNING 1 #define RTP_TIMER_STOPPED 0 diff --git a/src/scheduler.c b/src/scheduler.c index 5c320706..ec6b179f 100644 --- a/src/scheduler.c +++ b/src/scheduler.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -20,198 +20,179 @@ #ifdef HAVE_CONFIG_H #include "ortp-config.h" #endif -#include -#include "utils.h" -#include "scheduler.h" #include "rtpsession_priv.h" +#include "scheduler.h" +#include "utils.h" +#include // To avoid warning during compile -extern void rtp_session_process (RtpSession * session, uint32_t time, RtpScheduler *sched); - +extern void rtp_session_process(RtpSession *session, uint32_t time, RtpScheduler *sched); -void rtp_scheduler_init(RtpScheduler *sched) -{ - sched->list=0; - sched->time_=0; +void rtp_scheduler_init(RtpScheduler *sched) { + sched->list = 0; + sched->time_ = 0; /* default to the posix timer */ #if !defined(ORTP_WINDOWS_UNIVERSAL) - rtp_scheduler_set_timer(sched,&posix_timer); + rtp_scheduler_set_timer(sched, &posix_timer); #endif - ortp_mutex_init(&sched->lock,NULL); - ortp_cond_init(&sched->unblock_select_cond,NULL); - sched->max_sessions=sizeof(SessionSet)*8; + ortp_mutex_init(&sched->lock, NULL); + ortp_cond_init(&sched->unblock_select_cond, NULL); + sched->max_sessions = sizeof(SessionSet) * 8; session_set_init(&sched->all_sessions); - sched->all_max=0; + sched->all_max = 0; session_set_init(&sched->r_sessions); - sched->r_max=0; + sched->r_max = 0; session_set_init(&sched->w_sessions); - sched->w_max=0; + sched->w_max = 0; session_set_init(&sched->e_sessions); - sched->e_max=0; + sched->e_max = 0; } -RtpScheduler * rtp_scheduler_new() -{ - RtpScheduler *sched=(RtpScheduler *) ortp_malloc(sizeof(RtpScheduler)); - memset(sched,0,sizeof(RtpScheduler)); +RtpScheduler *rtp_scheduler_new() { + RtpScheduler *sched = (RtpScheduler *)ortp_malloc(sizeof(RtpScheduler)); + memset(sched, 0, sizeof(RtpScheduler)); rtp_scheduler_init(sched); return sched; } -void rtp_scheduler_set_timer(RtpScheduler *sched,RtpTimer *timer) -{ - if (sched->thread_running){ +void rtp_scheduler_set_timer(RtpScheduler *sched, RtpTimer *timer) { + if (sched->thread_running) { ortp_warning("Cannot change timer while the scheduler is running !!"); return; } - sched->timer=timer; + sched->timer = timer; /* report the timer increment */ - sched->timer_inc=(timer->interval.tv_usec/1000) + (timer->interval.tv_sec*1000); + sched->timer_inc = (timer->interval.tv_usec / 1000) + (timer->interval.tv_sec * 1000); } -void rtp_scheduler_start(RtpScheduler *sched) -{ - if (sched->thread_running==0){ - sched->thread_running=1; +void rtp_scheduler_start(RtpScheduler *sched) { + if (sched->thread_running == 0) { + sched->thread_running = 1; ortp_mutex_lock(&sched->lock); - ortp_thread_create(&sched->thread, NULL, rtp_scheduler_schedule,(void*)sched); - ortp_cond_wait(&sched->unblock_select_cond,&sched->lock); + ortp_thread_create(&sched->thread, NULL, rtp_scheduler_schedule, (void *)sched); + ortp_cond_wait(&sched->unblock_select_cond, &sched->lock); ortp_mutex_unlock(&sched->lock); - } - else ortp_warning("Scheduler thread already running."); - + } else ortp_warning("Scheduler thread already running."); } -void rtp_scheduler_stop(RtpScheduler *sched) -{ - if (sched->thread_running==1) - { - sched->thread_running=0; +void rtp_scheduler_stop(RtpScheduler *sched) { + if (sched->thread_running == 1) { + sched->thread_running = 0; ortp_thread_join(sched->thread, NULL); - } - else ortp_warning("Scheduler thread is not running."); + } else ortp_warning("Scheduler thread is not running."); } -void rtp_scheduler_destroy(RtpScheduler *sched) -{ +void rtp_scheduler_destroy(RtpScheduler *sched) { if (sched->thread_running) rtp_scheduler_stop(sched); ortp_mutex_destroy(&sched->lock); - //g_mutex_free(sched->unblock_select_mutex); + // g_mutex_free(sched->unblock_select_mutex); ortp_cond_destroy(&sched->unblock_select_cond); ortp_free(sched); } -void * rtp_scheduler_schedule(void * psched) -{ - RtpScheduler *sched=(RtpScheduler*) psched; - RtpTimer *timer=sched->timer; +void *rtp_scheduler_schedule(void *psched) { + RtpScheduler *sched = (RtpScheduler *)psched; + RtpTimer *timer = sched->timer; RtpSession *current; /* take this lock to prevent the thread to start until g_thread_create() returns - because we need sched->thread to be initialized */ + because we need sched->thread to be initialized */ ortp_mutex_lock(&sched->lock); - ortp_cond_signal(&sched->unblock_select_cond); /* unblock the starting thread */ + ortp_cond_signal(&sched->unblock_select_cond); /* unblock the starting thread */ ortp_mutex_unlock(&sched->lock); timer->timer_init(); - while(sched->thread_running) - { + while (sched->thread_running) { /* do the processing here: */ ortp_mutex_lock(&sched->lock); - - current=sched->list; + + current = sched->list; /* processing all scheduled rtp sessions */ - while (current!=NULL) - { - ortp_debug("scheduler: processing session=0x%p.\n",current); - rtp_session_process(current,sched->time_,sched); - current=current->next; + while (current != NULL) { + ortp_debug("scheduler: processing session=0x%p.\n", current); + rtp_session_process(current, sched->time_, sched); + current = current->next; } /* wake up all the threads that are sleeping in _select() */ ortp_cond_broadcast(&sched->unblock_select_cond); ortp_mutex_unlock(&sched->lock); - + /* now while the scheduler is going to sleep, the other threads can compute their result mask and see if they have to leave, or to wait for next tick*/ - //ortp_message("scheduler: sleeping."); + // ortp_message("scheduler: sleeping."); timer->timer_do(); - sched->time_+=sched->timer_inc; + sched->time_ += sched->timer_inc; } /* when leaving the thread, stop the timer */ timer->timer_uninit(); return NULL; } -void rtp_scheduler_add_session(RtpScheduler *sched, RtpSession *session) -{ +void rtp_scheduler_add_session(RtpScheduler *sched, RtpSession *session) { RtpSession *oldfirst; int i; - if (session->flags & RTP_SESSION_IN_SCHEDULER){ + if (session->flags & RTP_SESSION_IN_SCHEDULER) { /* the rtp session is already scheduled, so return silently */ return; } rtp_scheduler_lock(sched); /* enqueue the session to the list of scheduled sessions */ - oldfirst=sched->list; - sched->list=session; - session->next=oldfirst; - if (sched->max_sessions==0){ + oldfirst = sched->list; + sched->list = session; + session->next = oldfirst; + if (sched->max_sessions == 0) { ortp_error("rtp_scheduler_add_session: max_session=0 !"); } /* find a free pos in the session mask*/ - for (i=0;imax_sessions;i++){ - if (!ORTP_FD_ISSET(i,&sched->all_sessions.rtpset)){ - session->mask_pos=i; - session_set_set(&sched->all_sessions,session); + for (i = 0; i < sched->max_sessions; i++) { + if (!ORTP_FD_ISSET(i, &sched->all_sessions.rtpset)) { + session->mask_pos = i; + session_set_set(&sched->all_sessions, session); /* make a new session scheduled not blockable if it has not started*/ - if (session->flags & RTP_SESSION_RECV_NOT_STARTED) - session_set_set(&sched->r_sessions,session); - if (session->flags & RTP_SESSION_SEND_NOT_STARTED) - session_set_set(&sched->w_sessions,session); - if (i>sched->all_max){ - sched->all_max=i; + if (session->flags & RTP_SESSION_RECV_NOT_STARTED) session_set_set(&sched->r_sessions, session); + if (session->flags & RTP_SESSION_SEND_NOT_STARTED) session_set_set(&sched->w_sessions, session); + if (i > sched->all_max) { + sched->all_max = i; } break; } } - - rtp_session_set_flag(session,RTP_SESSION_IN_SCHEDULER); + + rtp_session_set_flag(session, RTP_SESSION_IN_SCHEDULER); rtp_scheduler_unlock(sched); } -void rtp_scheduler_remove_session(RtpScheduler *sched, RtpSession *session) -{ +void rtp_scheduler_remove_session(RtpScheduler *sched, RtpSession *session) { RtpSession *tmp; - int cond=1; - return_if_fail(session!=NULL); - if (!(session->flags & RTP_SESSION_IN_SCHEDULER)){ + int cond = 1; + return_if_fail(session != NULL); + if (!(session->flags & RTP_SESSION_IN_SCHEDULER)) { /* the rtp session is not scheduled, so return silently */ return; } rtp_scheduler_lock(sched); - tmp=sched->list; - if (tmp==session){ - sched->list=tmp->next; - rtp_session_unset_flag(session,RTP_SESSION_IN_SCHEDULER); - session_set_clr(&sched->all_sessions,session); + tmp = sched->list; + if (tmp == session) { + sched->list = tmp->next; + rtp_session_unset_flag(session, RTP_SESSION_IN_SCHEDULER); + session_set_clr(&sched->all_sessions, session); rtp_scheduler_unlock(sched); return; } /* go the position of session in the list */ - while(cond){ - if (tmp!=NULL){ - if (tmp->next==session){ - tmp->next=tmp->next->next; - cond=0; - } - else tmp=tmp->next; - }else { + while (cond) { + if (tmp != NULL) { + if (tmp->next == session) { + tmp->next = tmp->next->next; + cond = 0; + } else tmp = tmp->next; + } else { /* the session was not found ! */ ortp_warning("rtp_scheduler_remove_session: the session was not found in the scheduler list!"); - cond=0; + cond = 0; } } - rtp_session_unset_flag(session,RTP_SESSION_IN_SCHEDULER); + rtp_session_unset_flag(session, RTP_SESSION_IN_SCHEDULER); /* delete the bit in the mask */ - session_set_clr(&sched->all_sessions,session); + session_set_clr(&sched->all_sessions, session); rtp_scheduler_unlock(sched); } diff --git a/src/scheduler.h b/src/scheduler.h index 71c7de7b..7094a58a 100644 --- a/src/scheduler.h +++ b/src/scheduler.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -25,33 +25,32 @@ #include "ortp/sessionset.h" #include "rtptimer.h" - struct _RtpScheduler { - - RtpSession *list; /* list of scheduled sessions*/ - SessionSet all_sessions; /* mask of scheduled sessions */ - int all_max; /* the highest pos in the all mask */ - SessionSet r_sessions; /* mask of sessions that have a recv event */ - int r_max; - SessionSet w_sessions; /* mask of sessions that have a send event */ - int w_max; - SessionSet e_sessions; /* mask of session that have error event */ - int e_max; - int max_sessions; /* the number of position in the masks */ - /* GMutex *unblock_select_mutex; */ - ortp_cond_t unblock_select_cond; - ortp_mutex_t lock; + + RtpSession *list; /* list of scheduled sessions*/ + SessionSet all_sessions; /* mask of scheduled sessions */ + int all_max; /* the highest pos in the all mask */ + SessionSet r_sessions; /* mask of sessions that have a recv event */ + int r_max; + SessionSet w_sessions; /* mask of sessions that have a send event */ + int w_max; + SessionSet e_sessions; /* mask of session that have error event */ + int e_max; + int max_sessions; /* the number of position in the masks */ + /* GMutex *unblock_select_mutex; */ + ortp_cond_t unblock_select_cond; + ortp_mutex_t lock; ortp_thread_t thread; int thread_running; struct _RtpTimer *timer; - uint32_t time_; /*number of miliseconds elapsed since the start of the thread */ - uint32_t timer_inc; /* the timer increment in milisec */ + uint32_t time_; /*number of miliseconds elapsed since the start of the thread */ + uint32_t timer_inc; /* the timer increment in milisec */ }; typedef struct _RtpScheduler RtpScheduler; - -RtpScheduler * rtp_scheduler_new(void); -void rtp_scheduler_set_timer(RtpScheduler *sched,RtpTimer *timer); + +RtpScheduler *rtp_scheduler_new(void); +void rtp_scheduler_set_timer(RtpScheduler *sched, RtpTimer *timer); void rtp_scheduler_start(RtpScheduler *sched); void rtp_scheduler_stop(RtpScheduler *sched); void rtp_scheduler_destroy(RtpScheduler *sched); @@ -59,12 +58,12 @@ void rtp_scheduler_destroy(RtpScheduler *sched); void rtp_scheduler_add_session(RtpScheduler *sched, RtpSession *session); void rtp_scheduler_remove_session(RtpScheduler *sched, RtpSession *session); -void * rtp_scheduler_schedule(void * sched); +void *rtp_scheduler_schedule(void *sched); -#define rtp_scheduler_lock(sched) ortp_mutex_lock(&(sched)->lock) -#define rtp_scheduler_unlock(sched) ortp_mutex_unlock(&(sched)->lock) +#define rtp_scheduler_lock(sched) ortp_mutex_lock(&(sched)->lock) +#define rtp_scheduler_unlock(sched) ortp_mutex_unlock(&(sched)->lock) /* void rtp_scheduler_add_set(RtpScheduler *sched, SessionSet *set); */ -ORTP_PUBLIC RtpScheduler * ortp_get_scheduler(void); +ORTP_PUBLIC RtpScheduler *ortp_get_scheduler(void); #endif diff --git a/src/sessionset.c b/src/sessionset.c index 8caf8f3a..8ecf019f 100644 --- a/src/sessionset.c +++ b/src/sessionset.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,47 +18,41 @@ * along with this program. If not, see . */ +#include "scheduler.h" #include #include -#include "scheduler.h" - /** * Allocates and initialize a new empty session set. * * @return the empty session set. -**/ -SessionSet * session_set_new() -{ - SessionSet *set=(SessionSet *) ortp_malloc(sizeof(SessionSet)); + **/ +SessionSet *session_set_new() { + SessionSet *set = (SessionSet *)ortp_malloc(sizeof(SessionSet)); session_set_init(set); return set; } - /** * Destroys a session set. * -**/ + **/ -void session_set_destroy(SessionSet *set) -{ +void session_set_destroy(SessionSet *set) { ortp_free(set); } -int count_power_items_simple(uint32_t v) -{ - int c = 0,j; - for (j=0;j<32;j++){ - if ( ((v)>>j) & 1){ - ++c; - } +int count_power_items_simple(uint32_t v) { + int c = 0, j; + for (j = 0; j < 32; j++) { + if (((v) >> j) & 1) { + ++c; + } } return c; } -int count_power_items_fast(uint32_t v) -{ +int count_power_items_fast(uint32_t v) { int c = 0; while (v) { c += (v & 1); @@ -67,25 +61,24 @@ int count_power_items_fast(uint32_t v) return c; } -int session_set_and(SessionSet *sched_set, int maxs, SessionSet *user_set, SessionSet *result_set) -{ - uint32_t *mask1,*mask2,*mask3; - int i=0; - int ret=0; - mask1=(uint32_t*)(void*)&sched_set->rtpset; - mask2=(uint32_t*)(void*)&user_set->rtpset; - mask3=(uint32_t*)(void*)&result_set->rtpset; - while(irtpset; + mask2 = (uint32_t *)(void *)&user_set->rtpset; + mask3 = (uint32_t *)(void *)&result_set->rtpset; + while (i < maxs + 1) { + *mask3 = (*mask1) & (*mask2); /* computes the AND between the two masks*/ /* and unset the sessions that have been found from the sched_set */ - *mask1=(*mask1) & (~(*mask3)); + *mask1 = (*mask1) & (~(*mask3)); ret += count_power_items_fast(*mask3); - i+=32; + i += 32; mask1++; mask2++; mask3++; } - //printf("session_set_and: ret=%i\n",ret); + // printf("session_set_and: ret=%i\n",ret); return ret; } @@ -110,68 +103,65 @@ int session_set_and(SessionSet *sched_set, int maxs, SessionSet *user_set, Sessi * @param sends a set of rtp sessions to be watched for write events * @param errors a set of rtp sessions to be watched for errors * @return: the number of sessions on which the selected events happened. -**/ -int session_set_select(SessionSet *recvs, SessionSet *sends, SessionSet *errors) -{ - int ret=0,bits; + **/ +int session_set_select(SessionSet *recvs, SessionSet *sends, SessionSet *errors) { + int ret = 0, bits; SessionSet temp; - RtpScheduler *sched=ortp_get_scheduler(); + RtpScheduler *sched = ortp_get_scheduler(); /*lock the scheduler to not read the masks while they are being modified by the scheduler*/ rtp_scheduler_lock(sched); - while(1){ + while (1) { /* computes the SessionSet intersection (in the other words mask intersection) between the mask given by the user and scheduler masks */ - if (recvs!=NULL){ + if (recvs != NULL) { session_set_init(&temp); - bits=session_set_and(&sched->r_sessions,sched->all_max,recvs,&temp); - ret+=bits; + bits = session_set_and(&sched->r_sessions, sched->all_max, recvs, &temp); + ret += bits; /* copy the result set in the given user set (might be empty) */ - if (ret>0) session_set_copy(recvs,&temp); + if (ret > 0) session_set_copy(recvs, &temp); } - if (sends!=NULL){ + if (sends != NULL) { session_set_init(&temp); - bits=session_set_and(&sched->w_sessions,sched->all_max,sends,&temp); - ret+=bits; - if (ret>0){ + bits = session_set_and(&sched->w_sessions, sched->all_max, sends, &temp); + ret += bits; + if (ret > 0) { /* copy the result set in the given user set (might be empty)*/ - session_set_copy(sends,&temp); + session_set_copy(sends, &temp); } } - if (errors!=NULL){ + if (errors != NULL) { session_set_init(&temp); - bits=session_set_and(&sched->e_sessions,sched->all_max,errors,&temp); - ret+=bits; - if (ret>0){ + bits = session_set_and(&sched->e_sessions, sched->all_max, errors, &temp); + ret += bits; + if (ret > 0) { /* copy the result set in the given user set */ - session_set_copy(errors,&temp); + session_set_copy(errors, &temp); } } - if (ret>0){ + if (ret > 0) { /* there are set file descriptors, return immediately */ - //printf("There are %i sessions set, returning.\n",ret); + // printf("There are %i sessions set, returning.\n",ret); rtp_scheduler_unlock(sched); return ret; } - //printf("There are %i sessions set.\n",ret); + // printf("There are %i sessions set.\n",ret); /* else we wait until the next loop of the scheduler*/ - ortp_cond_wait(&sched->unblock_select_cond,&sched->lock); + ortp_cond_wait(&sched->unblock_select_cond, &sched->lock); } return -1; } -int session_set_timedselect(SessionSet *recvs, SessionSet *sends, SessionSet *errors, struct timeval *timeout) -{ - int ret=0,bits; +int session_set_timedselect(SessionSet *recvs, SessionSet *sends, SessionSet *errors, struct timeval *timeout) { + int ret = 0, bits; int remainingTime; // duration in ms SessionSet temp; RtpScheduler *sched; - if (timeout==NULL) - return session_set_select(recvs, sends, errors); - sched=ortp_get_scheduler(); - remainingTime = timeout->tv_usec/1000 + timeout->tv_sec*1000; + if (timeout == NULL) return session_set_select(recvs, sends, errors); + sched = ortp_get_scheduler(); + remainingTime = timeout->tv_usec / 1000 + timeout->tv_sec * 1000; /*lock the scheduler to not read the masks while they are being modified by the scheduler*/ rtp_scheduler_lock(sched); @@ -179,42 +169,42 @@ int session_set_timedselect(SessionSet *recvs, SessionSet *sends, SessionSet *er do { /* computes the SessionSet intersection (in the other words mask intersection) between the mask given by the user and scheduler masks */ - if (recvs!=NULL){ + if (recvs != NULL) { session_set_init(&temp); - bits=session_set_and(&sched->r_sessions,sched->all_max,recvs,&temp); - ret+=bits; + bits = session_set_and(&sched->r_sessions, sched->all_max, recvs, &temp); + ret += bits; /* copy the result set in the given user set (might be empty) */ - if (ret>0) session_set_copy(recvs,&temp); + if (ret > 0) session_set_copy(recvs, &temp); } - if (sends!=NULL){ + if (sends != NULL) { session_set_init(&temp); - bits=session_set_and(&sched->w_sessions,sched->all_max,sends,&temp); - ret+=bits; - if (ret>0){ + bits = session_set_and(&sched->w_sessions, sched->all_max, sends, &temp); + ret += bits; + if (ret > 0) { /* copy the result set in the given user set (might be empty)*/ - session_set_copy(sends,&temp); + session_set_copy(sends, &temp); } } - if (errors!=NULL){ + if (errors != NULL) { session_set_init(&temp); - bits=session_set_and(&sched->e_sessions,sched->all_max,errors,&temp); - ret+=bits; - if (ret>0){ + bits = session_set_and(&sched->e_sessions, sched->all_max, errors, &temp); + ret += bits; + if (ret > 0) { /* copy the result set in the given user set */ - session_set_copy(errors,&temp); + session_set_copy(errors, &temp); } } - if (ret>0){ + if (ret > 0) { /* there are set file descriptors, return immediately */ - //printf("There are %i sessions set, returning.\n",ret); + // printf("There are %i sessions set, returning.\n",ret); rtp_scheduler_unlock(sched); return ret; } - //printf("There are %i sessions set.\n",ret); + // printf("There are %i sessions set.\n",ret); /* else we wait until the next loop of the scheduler*/ - ortp_cond_wait(&sched->unblock_select_cond,&sched->lock); + ortp_cond_wait(&sched->unblock_select_cond, &sched->lock); remainingTime -= sched->timer_inc; - } while (remainingTime>0); + } while (remainingTime > 0); rtp_scheduler_unlock(sched); return -1; diff --git a/src/str_utils.c b/src/str_utils.c index 15a9b37e..20711ad2 100644 --- a/src/str_utils.c +++ b/src/str_utils.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,6 +18,8 @@ * along with this program. If not, see . */ +#include + #ifdef HAVE_CONFIG_H #include "ortp-config.h" #endif @@ -26,383 +28,369 @@ #include "ortp/str_utils.h" #include "utils.h" - -void qinit(queue_t *q){ +void qinit(queue_t *q) { mblk_init(&q->_q_stopper); - q->_q_stopper.b_next=&q->_q_stopper; - q->_q_stopper.b_prev=&q->_q_stopper; - q->q_mcount=0; + q->_q_stopper.b_next = &q->_q_stopper; + q->_q_stopper.b_prev = &q->_q_stopper; + q->q_mcount = 0; } -void mblk_init(mblk_t *mp) -{ +void mblk_init(mblk_t *mp) { memset(mp, 0, sizeof(mblk_t)); } void mblk_meta_copy(const mblk_t *source, mblk_t *dest) { dest->reserved1 = source->reserved1; dest->reserved2 = source->reserved2; - memcpy(&dest->net_addr,&source->net_addr,source->net_addrlen); + memcpy(&dest->net_addr, &source->net_addr, source->net_addrlen); dest->net_addrlen = source->net_addrlen; dest->timestamp = source->timestamp; dest->ttl_or_hl = source->ttl_or_hl; } -unsigned char * dblk_base(dblk_t *db) { +unsigned char *dblk_base(dblk_t *db) { return db->db_base; } -unsigned char * dblk_lim(dblk_t *db) { +unsigned char *dblk_lim(dblk_t *db) { return db->db_lim; } -mblk_t *allocb(size_t size, int pri) -{ +mblk_t *allocb(size_t size, BCTBX_UNUSED(int pri)) { mblk_t *mp; dblk_t *datab; - mp=(mblk_t *) ortp_malloc0(sizeof(mblk_t)); - datab=dblk_alloc(size); + mp = (mblk_t *)ortp_malloc0(sizeof(mblk_t)); + datab = dblk_alloc(size); - mp->b_datap=datab; - mp->b_rptr=mp->b_wptr = datab->db_base; - mp->b_next=mp->b_prev=mp->b_cont=NULL; + mp->b_datap = datab; + mp->b_rptr = mp->b_wptr = datab->db_base; + mp->b_next = mp->b_prev = mp->b_cont = NULL; return mp; } -mblk_t *esballoc(uint8_t *buf, size_t size, int pri, void (*freefn)(void*) ) -{ +mblk_t *esballoc(uint8_t *buf, size_t size, BCTBX_UNUSED(int pri), void (*freefn)(void *)) { mblk_t *mp; dblk_t *datab; - mp=(mblk_t *) ortp_malloc0(sizeof(mblk_t)); + mp = (mblk_t *)ortp_malloc0(sizeof(mblk_t)); datab = dblk_alloc2(buf, size, freefn); - - mp->b_datap=datab; - mp->b_rptr=mp->b_wptr=buf; - mp->b_next=mp->b_prev=mp->b_cont=NULL; + + mp->b_datap = datab; + mp->b_rptr = mp->b_wptr = buf; + mp->b_next = mp->b_prev = mp->b_cont = NULL; return mp; } - -void freeb(mblk_t *mp) -{ - return_if_fail(mp->b_datap!=NULL); - return_if_fail(mp->b_datap->db_base!=NULL); +void freeb(mblk_t *mp) { + return_if_fail(mp->b_datap != NULL); + return_if_fail(mp->b_datap->db_base != NULL); dblk_unref(mp->b_datap); ortp_free(mp); } -void freemsg(mblk_t *mp) -{ - mblk_t *tmp1,*tmp2; - tmp1=mp; - while(tmp1!=NULL) - { - tmp2=tmp1->b_cont; +void freemsg(mblk_t *mp) { + mblk_t *tmp1, *tmp2; + tmp1 = mp; + while (tmp1 != NULL) { + tmp2 = tmp1->b_cont; freeb(tmp1); - tmp1=tmp2; + tmp1 = tmp2; } } -mblk_t *dupb(mblk_t *mp) -{ +mblk_t *dupb(mblk_t *mp) { mblk_t *newm; - return_val_if_fail(mp->b_datap!=NULL,NULL); - return_val_if_fail(mp->b_datap->db_base!=NULL,NULL); + return_val_if_fail(mp->b_datap != NULL, NULL); + return_val_if_fail(mp->b_datap->db_base != NULL, NULL); dblk_ref(mp->b_datap); - newm=(mblk_t *) ortp_malloc0(sizeof(mblk_t)); + newm = (mblk_t *)ortp_malloc0(sizeof(mblk_t)); mblk_meta_copy(mp, newm); - newm->b_datap=mp->b_datap; - newm->b_rptr=mp->b_rptr; - newm->b_wptr=mp->b_wptr; + newm->b_datap = mp->b_datap; + newm->b_rptr = mp->b_rptr; + newm->b_wptr = mp->b_wptr; return newm; } /* duplicates a complex mblk_t */ -mblk_t *dupmsg(mblk_t* m) -{ - mblk_t *newm=NULL,*mp,*prev; - prev=newm=dupb(m); - m=m->b_cont; - while (m!=NULL){ - mp=dupb(m); - prev->b_cont=mp; - prev=mp; - m=m->b_cont; +mblk_t *dupmsg(mblk_t *m) { + mblk_t *newm = NULL, *mp, *prev; + prev = newm = dupb(m); + m = m->b_cont; + while (m != NULL) { + mp = dupb(m); + prev->b_cont = mp; + prev = mp; + m = m->b_cont; } return newm; } -void putq(queue_t *q,mblk_t *mp) -{ - q->_q_stopper.b_prev->b_next=mp; - mp->b_prev=q->_q_stopper.b_prev; - mp->b_next=&q->_q_stopper; - q->_q_stopper.b_prev=mp; +void putq(queue_t *q, mblk_t *mp) { + q->_q_stopper.b_prev->b_next = mp; + mp->b_prev = q->_q_stopper.b_prev; + mp->b_next = &q->_q_stopper; + q->_q_stopper.b_prev = mp; q->q_mcount++; } -mblk_t *getq(queue_t *q) -{ +mblk_t *getq(queue_t *q) { mblk_t *tmp; - tmp=q->_q_stopper.b_next; - if (tmp==&q->_q_stopper) return NULL; - q->_q_stopper.b_next=tmp->b_next; - tmp->b_next->b_prev=&q->_q_stopper; - tmp->b_prev=NULL; - tmp->b_next=NULL; + tmp = q->_q_stopper.b_next; + if (tmp == &q->_q_stopper) return NULL; + q->_q_stopper.b_next = tmp->b_next; + tmp->b_next->b_prev = &q->_q_stopper; + tmp->b_prev = NULL; + tmp->b_next = NULL; q->q_mcount--; return tmp; } -mblk_t * peekq(queue_t *q){ +mblk_t *peekq(queue_t *q) { mblk_t *tmp; - tmp=q->_q_stopper.b_next; - if (tmp==&q->_q_stopper) return NULL; + tmp = q->_q_stopper.b_next; + if (tmp == &q->_q_stopper) return NULL; return tmp; } /* insert mp in q just before emp */ -void insq(queue_t *q,mblk_t *emp, mblk_t *mp) -{ - if (emp==NULL){ - putq(q,mp); +void insq(queue_t *q, mblk_t *emp, mblk_t *mp) { + if (emp == NULL) { + putq(q, mp); return; } q->q_mcount++; - emp->b_prev->b_next=mp; - mp->b_prev=emp->b_prev; - emp->b_prev=mp; - mp->b_next=emp; + emp->b_prev->b_next = mp; + mp->b_prev = emp->b_prev; + emp->b_prev = mp; + mp->b_next = emp; } -void remq(queue_t *q, mblk_t *mp){ +void remq(queue_t *q, mblk_t *mp) { q->q_mcount--; - mp->b_prev->b_next=mp->b_next; - mp->b_next->b_prev=mp->b_prev; - mp->b_next=NULL; - mp->b_prev=NULL; + mp->b_prev->b_next = mp->b_next; + mp->b_next->b_prev = mp->b_prev; + mp->b_next = NULL; + mp->b_prev = NULL; } /* remove and free all messages in the q */ -void flushq(queue_t *q, int how) -{ +void flushq(queue_t *q, BCTBX_UNUSED(int how)) { mblk_t *mp; - while ((mp=getq(q))!=NULL) - { + while ((mp = getq(q)) != NULL) { freemsg(mp); } } -size_t msgdsize(const mblk_t *mp) -{ - size_t msgsize=0; - while(mp!=NULL){ - msgsize+=(size_t) (mp->b_wptr-mp->b_rptr); - mp=mp->b_cont; +size_t msgdsize(const mblk_t *mp) { + size_t msgsize = 0; + while (mp != NULL) { + msgsize += (size_t)(mp->b_wptr - mp->b_rptr); + mp = mp->b_cont; } return msgsize; } -void msgpullup(mblk_t *mp, size_t len){ - mblk_t *firstm=mp; +void msgpullup(mblk_t *mp, size_t len) { + mblk_t *firstm = mp; dblk_t *db; - size_t wlen=0; - unsigned char * base; + size_t wlen = 0; + unsigned char *base; - if (mp->b_cont == NULL){ + if (mp->b_cont == NULL) { /* Special case optimisations */ - if (len == (size_t)-1) return; /*nothing to do, message is not fragmented. */ - if (mp->b_datap->db_base + len <= mp->b_datap->db_lim){ + if (len == (size_t)-1) return; /*nothing to do, message is not fragmented. */ + if (mp->b_datap->db_base + len <= mp->b_datap->db_lim) { /* The underlying data block is larger than the requested size, nothing to do. */ return; } } - - if (len==(size_t)-1) len=msgdsize(mp); - db=dblk_alloc(len); + if (len == (size_t)-1) len = msgdsize(mp); + db = dblk_alloc(len); base = db->db_base; - while(wlenb_wptr-mp->b_rptr); - if (mlen<=remain){ - memcpy(&base[wlen],mp->b_rptr,mlen); - wlen+=mlen; - mp=mp->b_cont; - }else{ - memcpy(&base[wlen],mp->b_rptr,remain); - wlen+=remain; + while (wlen < len && mp != NULL) { + int remain = (int)(len - wlen); + int mlen = (int)(mp->b_wptr - mp->b_rptr); + if (mlen <= remain) { + memcpy(&base[wlen], mp->b_rptr, mlen); + wlen += mlen; + mp = mp->b_cont; + } else { + memcpy(&base[wlen], mp->b_rptr, remain); + wlen += remain; } } /*set firstm to point to the new datab */ freemsg(firstm->b_cont); - firstm->b_cont=NULL; + firstm->b_cont = NULL; dblk_unref(firstm->b_datap); - firstm->b_datap=db; - firstm->b_rptr=db->db_base; - firstm->b_wptr=firstm->b_rptr+wlen; + firstm->b_datap = db; + firstm->b_rptr = db->db_base; + firstm->b_wptr = firstm->b_rptr + wlen; } /* pullup message but insert an insert_size zeroised buffer at offset */ /* final size will be current size + insert size * b->w_bptr is set at the end of the message even if the insertion if performed at the end of the message */ void msgpullup_with_insert(mblk_t *mp, size_t offset, size_t insert_size) { - mblk_t *firstm=mp; + mblk_t *firstm = mp; dblk_t *db; - size_t wlen=0; + size_t wlen = 0; size_t len = msgdsize(mp); - if (offset>=len) { - msgpullup(mp, len+insert_size); /* we want to insert it at the end, that's what regular pullup does */ - mp->b_wptr+=offset-len+insert_size; + if (offset >= len) { + msgpullup(mp, len + insert_size); /* we want to insert it at the end, that's what regular pullup does */ + mp->b_wptr += offset - len + insert_size; return; } len += insert_size; db = dblk_alloc(len); - while(mp!=NULL){ /* copy the whole original content, we do not crop as in regular pullup */ - int mlen=(int)(mp->b_wptr-mp->b_rptr); - if (wlen+mlen<=offset || wlen>offset){ /* this whole chunk fit before the blank insert or we already made the insert */ - memcpy(&db->db_base[wlen],mp->b_rptr,mlen); - wlen+=mlen; - }else{ + while (mp != NULL) { /* copy the whole original content, we do not crop as in regular pullup */ + int mlen = (int)(mp->b_wptr - mp->b_rptr); + if (wlen + mlen <= offset || + wlen > offset) { /* this whole chunk fit before the blank insert or we already made the insert */ + memcpy(&db->db_base[wlen], mp->b_rptr, mlen); + wlen += mlen; + } else { /* split this chunk */ - memcpy(&db->db_base[wlen], mp->b_rptr, offset-wlen); /* write up to offset */ - memset(&db->db_base[offset], 0, insert_size); /* zeroise the inserted part */ - memcpy(&db->db_base[offset+insert_size], mp->b_rptr + offset-wlen, wlen+mlen-offset); /* copy the rest of this chunk */ - wlen+=mlen+insert_size; + memcpy(&db->db_base[wlen], mp->b_rptr, offset - wlen); /* write up to offset */ + memset(&db->db_base[offset], 0, insert_size); /* zeroise the inserted part */ + memcpy(&db->db_base[offset + insert_size], mp->b_rptr + offset - wlen, + wlen + mlen - offset); /* copy the rest of this chunk */ + wlen += mlen + insert_size; } - mp=mp->b_cont; + mp = mp->b_cont; } freemsg(firstm->b_cont); - firstm->b_cont=NULL; + firstm->b_cont = NULL; dblk_unref(firstm->b_datap); - firstm->b_datap=db; - firstm->b_rptr=db->db_base; - firstm->b_wptr=firstm->b_rptr+wlen; + firstm->b_datap = db; + firstm->b_rptr = db->db_base; + firstm->b_wptr = firstm->b_rptr + wlen; } -mblk_t *copyb(const mblk_t *mp) -{ +mblk_t *copyb(const mblk_t *mp) { mblk_t *newm; - int len=(int) (mp->b_wptr-mp->b_rptr); - newm=allocb(len,BPRI_MED); - memcpy(newm->b_wptr,mp->b_rptr,len); - newm->b_wptr+=len; - memcpy(&newm->recv_addr,&mp->recv_addr,sizeof(newm->recv_addr)); + int len = (int)(mp->b_wptr - mp->b_rptr); + newm = allocb(len, BPRI_MED); + memcpy(newm->b_wptr, mp->b_rptr, len); + newm->b_wptr += len; + memcpy(&newm->recv_addr, &mp->recv_addr, sizeof(newm->recv_addr)); return newm; } -mblk_t *copymsg(const mblk_t *mp) -{ - mblk_t *newm=0,*m; - m=newm=copyb(mp); - mp=mp->b_cont; - while(mp!=NULL){ - m->b_cont=copyb(mp); - m=m->b_cont; - mp=mp->b_cont; +mblk_t *copymsg(const mblk_t *mp) { + mblk_t *newm = 0, *m; + m = newm = copyb(mp); + mp = mp->b_cont; + while (mp != NULL) { + m->b_cont = copyb(mp); + m = m->b_cont; + mp = mp->b_cont; } return newm; } -mblk_t * appendb(mblk_t *mp, const char *data, size_t size, bool_t pad){ - size_t padcnt=0; +mblk_t *appendb(mblk_t *mp, const char *data, size_t size, bool_t pad) { + size_t padcnt = 0; size_t i; - unsigned char * lim; - if (pad){ + unsigned char *lim; + if (pad) { padcnt = (size_t)(4 - ((((intptr_t)mp->b_wptr) + size) % 4)) % 4; } lim = mp->b_datap->db_lim; - if ((mp->b_wptr + size +padcnt) > lim){ + if ((mp->b_wptr + size + padcnt) > lim) { /* buffer is not large enough: append a new block (with the same size ?)*/ - size_t plen=(size_t)((char*)lim - (char*) mp->b_datap->db_base); - mp->b_cont=allocb(MAX(plen,size),0); - mp=mp->b_cont; + size_t plen = (size_t)((char *)lim - (char *)mp->b_datap->db_base); + mp->b_cont = allocb(MAX(plen, size), 0); + mp = mp->b_cont; } - if (size) memcpy(mp->b_wptr,data,size); - mp->b_wptr+=size; - for (i=0;ib_wptr[0]=0; + if (size) memcpy(mp->b_wptr, data, size); + mp->b_wptr += size; + for (i = 0; i < padcnt; i++) { + mp->b_wptr[0] = 0; mp->b_wptr++; } return mp; } -void msgappend(mblk_t *mp, const char *data, size_t size, bool_t pad){ - while(mp->b_cont!=NULL) mp=mp->b_cont; - appendb(mp,data,size,pad); +void msgappend(mblk_t *mp, const char *data, size_t size, bool_t pad) { + while (mp->b_cont != NULL) + mp = mp->b_cont; + appendb(mp, data, size, pad); } -mblk_t *concatb(mblk_t *mp, mblk_t *newm){ - while (mp->b_cont!=NULL) mp=mp->b_cont; - mp->b_cont=newm; - while(newm->b_cont!=NULL) newm=newm->b_cont; +mblk_t *concatb(mblk_t *mp, mblk_t *newm) { + while (mp->b_cont != NULL) + mp = mp->b_cont; + mp->b_cont = newm; + while (newm->b_cont != NULL) + newm = newm->b_cont; return newm; } -void msgb_allocator_init(msgb_allocator_t *a){ +void msgb_allocator_init(msgb_allocator_t *a) { qinit(&a->q); a->max_blocks = 0; /* no limit */ } -void msgb_allocator_set_max_blocks(msgb_allocator_t *pa, int max_blocks){ +void msgb_allocator_set_max_blocks(msgb_allocator_t *pa, int max_blocks) { pa->max_blocks = max_blocks; } -static void msgb_allocator_free_db(void *unused){ +static void msgb_allocator_free_db(BCTBX_UNUSED(void *unused)) { } -mblk_t *msgb_allocator_alloc(msgb_allocator_t *a, size_t size){ - queue_t *q=&a->q; - mblk_t *m,*found=NULL; +mblk_t *msgb_allocator_alloc(msgb_allocator_t *a, size_t size) { + queue_t *q = &a->q; + mblk_t *m, *found = NULL; int busy_blocks = 0; /*lookup for an unused msgb (data block with ref count ==1)*/ - for(m=qbegin(q);!qend(q,m);m=qnext(q,m)){ - if ((size_t)(m->b_datap->db_lim - m->b_datap->db_base) >= size){ - if (dblk_ref_value(m->b_datap) == 1){ - found=m; + for (m = qbegin(q); !qend(q, m); m = qnext(q, m)) { + if ((size_t)(m->b_datap->db_lim - m->b_datap->db_base) >= size) { + if (dblk_ref_value(m->b_datap) == 1) { + found = m; break; - }else{ + } else { busy_blocks++; } } } - if (a->max_blocks !=0 && busy_blocks >= a->max_blocks){ + if (a->max_blocks != 0 && busy_blocks >= a->max_blocks) { return NULL; } - if (found==NULL){ - found=allocb(size,0); + if (found == NULL) { + found = allocb(size, 0); /*Hack: we put a special freefn impletation to be able to recognize mblk_t allocated by the msgb_allocator_t */ found->b_datap->db_freefn = msgb_allocator_free_db; - putq(q,found); + putq(q, found); } return dupb(found); } -void msgb_allocator_uninit(msgb_allocator_t *a){ - flushq(&a->q,-1); +void msgb_allocator_uninit(msgb_allocator_t *a) { + flushq(&a->q, -1); } /*Same as ownb(), but invoke it for each mblk_t of the chain*/ -mblk_t * msgown(mblk_t *mp){ - int single_owner_ref = ( mp->b_datap->db_freefn == msgb_allocator_free_db) ? 2 : 1; - - if ( dblk_ref_value(mp->b_datap) > single_owner_ref){ - //ortp_message("msgown(): datab copied db_ref=%i single_owner_ref=%i", dblk_ref_value(mp->b_datap), single_owner_ref); +mblk_t *msgown(mblk_t *mp) { + int single_owner_ref = (mp->b_datap->db_freefn == msgb_allocator_free_db) ? 2 : 1; + + if (dblk_ref_value(mp->b_datap) > single_owner_ref) { + // ortp_message("msgown(): datab copied db_ref=%i single_owner_ref=%i", dblk_ref_value(mp->b_datap), + // single_owner_ref); msgpullup(mp, msgdsize(mp)); } return mp; } - void ortp_recvaddr_to_sockaddr(ortp_recv_addr_t *recvaddr, struct sockaddr *addr, socklen_t *socklen) { if (recvaddr->family == AF_INET) { struct sockaddr_in *addr_in = (struct sockaddr_in *)addr; @@ -416,18 +404,18 @@ void ortp_recvaddr_to_sockaddr(ortp_recv_addr_t *recvaddr, struct sockaddr *addr addr_in6->sin6_port = recvaddr->port; memcpy(&addr_in6->sin6_addr, &recvaddr->addr.ipi6_addr, sizeof(recvaddr->addr.ipi6_addr)); *socklen = sizeof(struct sockaddr_in6); - }else{ + } else { *socklen = 0; } } -void ortp_sockaddr_to_recvaddr(const struct sockaddr * addr, ortp_recv_addr_t * recvaddr) { - if( addr->sa_family == AF_INET) { - struct sockaddr_in * addr_in = (struct sockaddr_in *)addr; +void ortp_sockaddr_to_recvaddr(const struct sockaddr *addr, ortp_recv_addr_t *recvaddr) { + if (addr->sa_family == AF_INET) { + struct sockaddr_in *addr_in = (struct sockaddr_in *)addr; recvaddr->family = AF_INET; recvaddr->port = addr_in->sin_port; recvaddr->addr.ipi_addr = addr_in->sin_addr; - }else if( addr->sa_family == AF_INET6) { - struct sockaddr_in6 * addr_in6 = (struct sockaddr_in6 *)addr; + } else if (addr->sa_family == AF_INET6) { + struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)addr; recvaddr->family = AF_INET6; recvaddr->port = addr_in6->sin6_port; memcpy(&recvaddr->addr.ipi6_addr, &addr_in6->sin6_addr, sizeof(addr_in6->sin6_addr)); diff --git a/src/telephonyevents.c b/src/telephonyevents.c index 8a4527a8..3fda15f7 100644 --- a/src/telephonyevents.c +++ b/src/telephonyevents.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -17,26 +17,29 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ + +#include + #ifdef HAVE_CONFIG_H #include "ortp-config.h" #endif -#include -#include "utils.h" -#include "rtpsession_priv.h" #include "ortp/str_utils.h" -#include +#include "rtpsession_priv.h" +#include "utils.h" #include +#include +#include -PayloadType payload_type_telephone_event={ - PAYLOAD_AUDIO_PACKETIZED, /*type */ - 8000, /*clock rate */ - 0, /* bytes per sample N/A */ - NULL, /* zero pattern N/A*/ - 0, /*pattern_length N/A */ - 0, /* normal_bitrate */ - "telephone-event", /* MIME subtype */ - 1, /* Audio Channels */ - 0 /*flags */ +PayloadType payload_type_telephone_event = { + PAYLOAD_AUDIO_PACKETIZED, /*type */ + 8000, /*clock rate */ + 0, /* bytes per sample N/A */ + NULL, /* zero pattern N/A*/ + 0, /*pattern_length N/A */ + 0, /* normal_bitrate */ + "telephone-event", /* MIME subtype */ + 1, /* Audio Channels */ + 0 /*flags */ }; /** @@ -45,30 +48,27 @@ PayloadType payload_type_telephone_event={ * @param session a rtp session * * @return the payload type number used for telephony events if found, -1 if not found. -**/ -int rtp_session_telephone_events_supported(RtpSession *session) -{ + **/ +int rtp_session_telephone_events_supported(RtpSession *session) { /* search for a telephony event payload in the current profile */ - return rtp_profile_get_payload_number_from_mime(session->snd.profile,"telephone-event"); + return rtp_profile_get_payload_number_from_mime(session->snd.profile, "telephone-event"); } -bool_t rtp_profile_is_telephone_event(const RtpProfile *prof, int pt_num){ - PayloadType *pt=rtp_profile_get_payload(prof, pt_num); - return pt && strcasecmp(pt->mime_type,"telephone-event")==0; +bool_t rtp_profile_is_telephone_event(const RtpProfile *prof, int pt_num) { + PayloadType *pt = rtp_profile_get_payload(prof, pt_num); + return pt && strcasecmp(pt->mime_type, "telephone-event") == 0; } - /** * Tells whether telephone event payload type is supported for send within the * context of the rtp session. * @param session a rtp session * * @return the payload type number used for telephony events if found, -1 if not found. -**/ -int rtp_session_send_telephone_events_supported(RtpSession *session) -{ + **/ +int rtp_session_send_telephone_events_supported(RtpSession *session) { /* search for a telephony event payload in the current profile */ - return rtp_profile_get_payload_number_from_mime(session->snd.profile,"telephone-event"); + return rtp_profile_get_payload_number_from_mime(session->snd.profile, "telephone-event"); } /** @@ -77,13 +77,12 @@ int rtp_session_send_telephone_events_supported(RtpSession *session) * @param session a rtp session * * @return the payload type number used for telephony events if found, -1 if not found. -**/int rtp_session_recv_telephone_events_supported(RtpSession *session) -{ + **/ +int rtp_session_recv_telephone_events_supported(RtpSession *session) { /* search for a telephony event payload in the current profile */ - return rtp_profile_get_payload_number_from_mime(session->rcv.profile,"telephone-event"); + return rtp_profile_get_payload_number_from_mime(session->rcv.profile, "telephone-event"); } - /** * Allocates a new rtp packet to be used to add named telephony events. The application can use * then rtp_session_add_telephone_event() to add named events to the packet. @@ -95,35 +94,36 @@ int rtp_session_send_telephone_events_supported(RtpSession *session) * @return a message block containing the rtp packet if successfull, NULL if the rtp session * cannot support telephony event (because the rtp profile it is bound to does not include * a telephony event payload type). -**/ -mblk_t *rtp_session_create_telephone_event_packet(RtpSession *session, int start) -{ + **/ +mblk_t *rtp_session_create_telephone_event_packet(RtpSession *session, int start) { mblk_t *mp; rtp_header_t *rtp; - PayloadType *cur_pt=rtp_profile_get_payload(session->snd.profile, rtp_session_get_send_payload_type(session)); + PayloadType *cur_pt = rtp_profile_get_payload(session->snd.profile, rtp_session_get_send_payload_type(session)); int tev_pt = session->tev_send_pt; - if (tev_pt != -1){ - PayloadType *cur_tev_pt=rtp_profile_get_payload(session->snd.profile, tev_pt); - if (!cur_tev_pt){ + if (tev_pt != -1) { + PayloadType *cur_tev_pt = rtp_profile_get_payload(session->snd.profile, tev_pt); + if (!cur_tev_pt) { ortp_error("Undefined telephone-event payload type %i choosen for sending telephone event", tev_pt); tev_pt = -1; - }else if (cur_pt && cur_tev_pt->clock_rate != cur_pt->clock_rate){ - ortp_warning("Telephone-event payload type %i has clockrate %i while main audio codec has clockrate %i: this is not permitted.", - tev_pt, cur_tev_pt->clock_rate, cur_pt->clock_rate); + } else if (cur_pt && cur_tev_pt->clock_rate != cur_pt->clock_rate) { + ortp_warning("Telephone-event payload type %i has clockrate %i while main audio codec has clockrate %i: " + "this is not permitted.", + tev_pt, cur_tev_pt->clock_rate, cur_pt->clock_rate); } } - if (tev_pt == -1){ - tev_pt = rtp_profile_find_payload_number(session->snd.profile, "telephone-event", cur_pt ? cur_pt->clock_rate : 8000, 1); + if (tev_pt == -1) { + tev_pt = rtp_profile_find_payload_number(session->snd.profile, "telephone-event", + cur_pt ? cur_pt->clock_rate : 8000, 1); } - return_val_if_fail(tev_pt!=-1,NULL); + return_val_if_fail(tev_pt != -1, NULL); - mp=allocb(RTP_FIXED_HEADER_SIZE+TELEPHONY_EVENTS_ALLOCATED_SIZE,BPRI_MED); - if (mp==NULL) return NULL; - rtp=(rtp_header_t*)mp->b_rptr; + mp = allocb(RTP_FIXED_HEADER_SIZE + TELEPHONY_EVENTS_ALLOCATED_SIZE, BPRI_MED); + if (mp == NULL) return NULL; + rtp = (rtp_header_t *)mp->b_rptr; rtp->version = 2; - rtp->markbit=start; + rtp->markbit = start; rtp->padbit = 0; rtp->extbit = 0; rtp->cc = 0; @@ -132,14 +132,13 @@ mblk_t *rtp_session_create_telephone_event_packet(RtpSession *session, int start /*seq number set later, when packet is sended */ /*set the payload type */ - rtp->paytype=tev_pt; + rtp->paytype = tev_pt; /*copy the payload */ - mp->b_wptr+=RTP_FIXED_HEADER_SIZE; + mp->b_wptr += RTP_FIXED_HEADER_SIZE; return mp; } - /** *@param session a rtp session. *@param packet a rtp packet as a mblk_t @@ -152,30 +151,29 @@ mblk_t *rtp_session_create_telephone_event_packet(RtpSession *session, int start * rtp_session_create_telephone_event_packet(). * *@return 0 on success. -**/ -int rtp_session_add_telephone_event(RtpSession *session, - mblk_t *packet, uint8_t event, int end, uint8_t volume, uint16_t duration) -{ - mblk_t *mp=packet; + **/ +int rtp_session_add_telephone_event( + BCTBX_UNUSED(RtpSession *session), mblk_t *packet, uint8_t event, int end, uint8_t volume, uint16_t duration) { + mblk_t *mp = packet; telephone_event_t *event_hdr; - /* find the place where to add the new telephony event to the packet */ - while(mp->b_cont!=NULL) mp=mp->b_cont; + while (mp->b_cont != NULL) + mp = mp->b_cont; /* see if we need to allocate a new mblk_t */ - if ( ( mp->b_wptr) >= mp->b_datap->db_lim){ - mblk_t *newm=allocb(TELEPHONY_EVENTS_ALLOCATED_SIZE,BPRI_MED); - mp->b_cont=newm; - mp=mp->b_cont; + if ((mp->b_wptr) >= mp->b_datap->db_lim) { + mblk_t *newm = allocb(TELEPHONY_EVENTS_ALLOCATED_SIZE, BPRI_MED); + mp->b_cont = newm; + mp = mp->b_cont; } - if (mp==NULL) return -1; - event_hdr=(telephone_event_t*)mp->b_wptr; - event_hdr->event=event; - event_hdr->R=0; - event_hdr->E=end; - event_hdr->volume=volume; - event_hdr->duration=htons(duration); - mp->b_wptr+=sizeof(telephone_event_t); + if (mp == NULL) return -1; + event_hdr = (telephone_event_t *)mp->b_wptr; + event_hdr->event = event; + event_hdr->R = 0; + event_hdr->E = end; + event_hdr->volume = volume; + event_hdr->duration = htons(duration); + mp->b_wptr += sizeof(telephone_event_t); return 0; } /** @@ -187,11 +185,11 @@ int rtp_session_add_telephone_event(RtpSession *session, * @param session a rtp session * @param dtmf a character meaning the dtmf (ex: '1', '#' , '9' ...) * @param userts the timestamp - * @return 0 if successfull, -1 if the session cannot support telephony events or if the dtmf given as argument is not valid. -**/ -int rtp_session_send_dtmf(RtpSession *session, char dtmf, uint32_t userts) -{ - return rtp_session_send_dtmf2(session, dtmf, userts, 480); + * @return 0 if successfull, -1 if the session cannot support telephony events or if the dtmf given as argument is not + *valid. + **/ +int rtp_session_send_dtmf(RtpSession *session, char dtmf, uint32_t userts) { + return rtp_session_send_dtmf2(session, dtmf, userts, 480); } /** @@ -201,117 +199,114 @@ int rtp_session_send_dtmf(RtpSession *session, char dtmf, uint32_t userts) * @param dtmf a character meaning the dtmf (ex: '1', '#' , '9' ...) * @param userts the timestamp * @param duration duration of the dtmf in timestamp units - * @return 0 if successfull, -1 if the session cannot support telephony events or if the dtmf given as argument is not valid. -**/ -int rtp_session_send_dtmf2(RtpSession *session, char dtmf, uint32_t userts, int duration) -{ - mblk_t *m1,*m2,*m3; + * @return 0 if successfull, -1 if the session cannot support telephony events or if the dtmf given as argument is not + *valid. + **/ +int rtp_session_send_dtmf2(RtpSession *session, char dtmf, uint32_t userts, int duration) { + mblk_t *m1, *m2, *m3; int tev_type; - int durationtier = duration/3; + int durationtier = duration / 3; /* create the first telephony event packet */ - switch (dtmf){ + switch (dtmf) { case '1': - tev_type=TEV_DTMF_1; - break; + tev_type = TEV_DTMF_1; + break; case '2': - tev_type=TEV_DTMF_2; - break; + tev_type = TEV_DTMF_2; + break; case '3': - tev_type=TEV_DTMF_3; - break; + tev_type = TEV_DTMF_3; + break; case '4': - tev_type=TEV_DTMF_4; - break; + tev_type = TEV_DTMF_4; + break; case '5': - tev_type=TEV_DTMF_5; - break; + tev_type = TEV_DTMF_5; + break; case '6': - tev_type=TEV_DTMF_6; - break; + tev_type = TEV_DTMF_6; + break; case '7': - tev_type=TEV_DTMF_7; - break; + tev_type = TEV_DTMF_7; + break; case '8': - tev_type=TEV_DTMF_8; - break; + tev_type = TEV_DTMF_8; + break; case '9': - tev_type=TEV_DTMF_9; - break; + tev_type = TEV_DTMF_9; + break; case '*': - tev_type=TEV_DTMF_STAR; - break; + tev_type = TEV_DTMF_STAR; + break; case '0': - tev_type=TEV_DTMF_0; - break; + tev_type = TEV_DTMF_0; + break; case '#': - tev_type=TEV_DTMF_POUND; - break; + tev_type = TEV_DTMF_POUND; + break; case 'A': case 'a': - tev_type=TEV_DTMF_A; - break; - + tev_type = TEV_DTMF_A; + break; case 'B': case 'b': - tev_type=TEV_DTMF_B; - break; + tev_type = TEV_DTMF_B; + break; case 'C': case 'c': - tev_type=TEV_DTMF_C; - break; + tev_type = TEV_DTMF_C; + break; case 'D': case 'd': - tev_type=TEV_DTMF_D; - break; + tev_type = TEV_DTMF_D; + break; case '!': - tev_type=TEV_FLASH; - break; - + tev_type = TEV_FLASH; + break; default: - ortp_warning("Bad dtmf: %c.",dtmf); - return -1; + ortp_warning("Bad dtmf: %c.", dtmf); + return -1; } - m1=rtp_session_create_telephone_event_packet(session,1); - if (m1==NULL) return -1; - rtp_session_add_telephone_event(session,m1,tev_type,0,10,durationtier); + m1 = rtp_session_create_telephone_event_packet(session, 1); + if (m1 == NULL) return -1; + rtp_session_add_telephone_event(session, m1, tev_type, 0, 10, durationtier); /* create a second packet */ - m2=rtp_session_create_telephone_event_packet(session,0); - if (m2==NULL) return -1; - rtp_session_add_telephone_event(session,m2,tev_type,0,10, durationtier+durationtier); + m2 = rtp_session_create_telephone_event_packet(session, 0); + if (m2 == NULL) return -1; + rtp_session_add_telephone_event(session, m2, tev_type, 0, 10, durationtier + durationtier); /* create a third and final packet */ - m3=rtp_session_create_telephone_event_packet(session,0); - if (m3==NULL) return -1; - rtp_session_add_telephone_event(session,m3,tev_type,1,10,duration); + m3 = rtp_session_create_telephone_event_packet(session, 0); + if (m3 == NULL) return -1; + rtp_session_add_telephone_event(session, m3, tev_type, 1, 10, duration); /* and now sends them */ - rtp_session_sendm_with_ts(session,m1,userts); - rtp_session_sendm_with_ts(session,m2,userts); + rtp_session_sendm_with_ts(session, m1, userts); + rtp_session_sendm_with_ts(session, m2, userts); /* the last packet is sent three times in order to improve reliability*/ - m1=copymsg(m3); - m2=copymsg(m3); + m1 = copymsg(m3); + m2 = copymsg(m3); /* NOTE: */ /* we need to copymsg() instead of dupmsg() because the buffers are modified when the packet is sended because of the host-to-network conversion of timestamp,ssrc, csrc, and seq number. */ - rtp_session_sendm_with_ts(session,m3,userts); + rtp_session_sendm_with_ts(session, m3, userts); session->rtp.snd_seq--; - rtp_session_sendm_with_ts(session,m1,userts); + rtp_session_sendm_with_ts(session, m1, userts); session->rtp.snd_seq--; - rtp_session_sendm_with_ts(session,m2,userts); + rtp_session_sendm_with_ts(session, m2, userts); return 0; } - /** * Reads telephony events from a rtp packet. \a *tab points to the beginning of the event buffer. * @@ -319,120 +314,107 @@ int rtp_session_send_dtmf2(RtpSession *session, char dtmf, uint32_t userts, int * @param packet a rtp packet as a mblk_t. * @param tab the address of a pointer. * @return the number of events in the packet if successfull, 0 if the packet did not contain telephony events. -**/ -int rtp_session_read_telephone_event(RtpSession *session, - mblk_t *packet,telephone_event_t **tab) -{ + **/ +int rtp_session_read_telephone_event(RtpSession *session, mblk_t *packet, telephone_event_t **tab) { int datasize; int num; int i; telephone_event_t *tev; - rtp_header_t *hdr=(rtp_header_t*)packet->b_rptr; + rtp_header_t *hdr = (rtp_header_t *)packet->b_rptr; unsigned char *payload; - if (!rtp_profile_is_telephone_event(session->rcv.profile, hdr->paytype)) return 0; /* this is not tel ev.*/ - datasize=rtp_get_payload(packet,&payload); - tev=*tab=(telephone_event_t*)payload; + if (!rtp_profile_is_telephone_event(session->rcv.profile, hdr->paytype)) return 0; /* this is not tel ev.*/ + datasize = rtp_get_payload(packet, &payload); + tev = *tab = (telephone_event_t *)payload; /* convert from network to host order what should be */ - num=datasize/sizeof(telephone_event_t); - for (i=0;ion_telephone_event,ORTP_INT_TO_POINTER(event[0].event)); - if (session->eventqs!=NULL){ - ev=ortp_event_new(ORTP_EVENT_TELEPHONE_EVENT); - evd=ortp_event_get_data(ev); - evd->packet=dupmsg(session->current_tev); - evd->info.telephone_event=event[0].event; - rtp_session_dispatch_event(session,ev); + rtp_signal_table_emit2(&session->on_telephone_event, ORTP_INT_TO_POINTER(event[0].event)); + if (session->eventqs != NULL) { + ev = ortp_event_new(ORTP_EVENT_TELEPHONE_EVENT); + evd = ortp_event_get_data(ev); + evd->packet = dupmsg(session->current_tev); + evd->info.telephone_event = event[0].event; + rtp_session_dispatch_event(session, ev); } } -static void notify_events_ended(RtpSession *session, telephone_event_t *events, int num){ +static void notify_events_ended(RtpSession *session, telephone_event_t *events, int num) { int i; - for (i=0;ib_rptr; - - datasize=rtp_get_payload(m0,&payload); + hdr = (rtp_header_t *)m0->b_rptr; - num=datasize/sizeof(telephone_event_t); - events=(telephone_event_t*)payload; + datasize = rtp_get_payload(m0, &payload); + num = datasize / sizeof(telephone_event_t); + events = (telephone_event_t *)payload; - if (hdr->markbit==1) - { + if (hdr->markbit == 1) { /* this is a start of new events. Store the event buffer for later use*/ - if (session->current_tev!=NULL) { + if (session->current_tev != NULL) { freemsg(session->current_tev); - session->current_tev=NULL; + session->current_tev = NULL; } - session->current_tev=copymsg(m0); + session->current_tev = copymsg(m0); /* handle the case where the events are short enough to end within the packet that has the marker bit*/ - notify_events_ended(session,events,num); + notify_events_ended(session, events, num); } /* whatever there is a markbit set or not, we parse the packet and compare it to previously received one */ - cur_tev=session->current_tev; - if (cur_tev!=NULL) - { + cur_tev = session->current_tev; + if (cur_tev != NULL) { /* first compare timestamp, they must be identical */ if (rtp_get_timestamp(cur_tev) == rtp_get_timestamp(m0)) { - datasize=rtp_get_payload(cur_tev,&payload); - num2=datasize/sizeof(telephone_event_t); - evbuf=(telephone_event_t*)payload; - for (i=0;icurrent_tev!=NULL) { + if (session->current_tev != NULL) { freemsg(session->current_tev); - session->current_tev=NULL; + session->current_tev = NULL; } - session->current_tev=copymsg(m0); - notify_events_ended(session,events,num); + session->current_tev = copymsg(m0); + notify_events_ended(session, events, num); } - } - else - { + } else { /* there is no pending events, but we did not received marked bit packet either the sending implementation is not compliant, either it has been lost, we must deal with it anyway.*/ - session->current_tev=copymsg(m0); + session->current_tev = copymsg(m0); /* inform the application if there are tone ends */ - notify_events_ended(session,events,num); + notify_events_ended(session, events, num); } } diff --git a/src/tests/fmtpparse.c b/src/tests/fmtpparse.c index dc90b12f..39df7998 100644 --- a/src/tests/fmtpparse.c +++ b/src/tests/fmtpparse.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,19 +18,18 @@ * along with this program. If not, see . */ - #include -int main(int argc, char *argv[]){ - char value[256]={0}; - if (argc<3){ - fprintf(stderr,"%s \n", argv[0]); +int main(int argc, char *argv[]) { + char value[256] = {0}; + if (argc < 3) { + fprintf(stderr, "%s \n", argv[0]); return -1; } - if (fmtp_get_value(argv[1],argv[2],value,sizeof(value))){ + if (fmtp_get_value(argv[1], argv[2], value, sizeof(value))) { printf("%s\n", value); - }else{ - fprintf(stderr,"No such parameter\n"); + } else { + fprintf(stderr, "No such parameter\n"); } return 0; } diff --git a/src/tests/mrtprecv.c b/src/tests/mrtprecv.c index 9fb00b65..9a07ce99 100644 --- a/src/tests/mrtprecv.c +++ b/src/tests/mrtprecv.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,136 +18,131 @@ * along with this program. If not, see . */ -/* this program shows how to receive streams in paralel using the SessionSet api - and two threads only. */ +/* this program shows how to receive streams in paralel using the SessionSet api + and two threads only. */ +#include +#include #include #include #include #include -#include -#include #ifndef _WIN32 #include -#include -#include #include +#include +#include #endif -int runcond=1; +int runcond = 1; -void stophandler(int signum) -{ - runcond=0; +void stophandler(int signum) { + runcond = 0; } -static char *help="usage: mrtprecv file_prefix local_port number_of_streams \n" - "Receives multiples rtp streams on local_port+2*k, k={0..number_of_streams}\n"; +static char *help = "usage: mrtprecv file_prefix local_port number_of_streams \n" + "Receives multiples rtp streams on local_port+2*k, k={0..number_of_streams}\n"; #define STREAMS_COUNT 1000 /* malloc'd in order to detect buffer overflows with efence */ -static uint8_t* recvbuf=0; - -int rtp2disk(RtpSession *session,uint32_t ts, int fd) -{ - int err,havemore=1; - while (havemore){ - err=rtp_session_recv_with_ts(session,recvbuf,160,ts,&havemore); - if (havemore) printf("warning: havemore=%i!\n",havemore); - if (err>0){ - rtp_session_set_data(session,(void*)1); +static uint8_t *recvbuf = 0; + +int rtp2disk(RtpSession *session, uint32_t ts, int fd) { + int err, havemore = 1; + while (havemore) { + err = rtp_session_recv_with_ts(session, recvbuf, 160, ts, &havemore); + if (havemore) printf("warning: havemore=%i!\n", havemore); + if (err > 0) { + rtp_session_set_data(session, (void *)1); /* to indicate that (for the application) the stream has started, so we can start recording on disk */ } if (session->user_data != NULL) { - size_t ret = write(fd,recvbuf,err); - assert( ret == err ); + size_t ret = write(fd, recvbuf, err); + assert(ret == err); } } return 0; } - -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { RtpSession *session[STREAMS_COUNT]; int i; int filefd[STREAMS_COUNT]; int port; - uint32_t user_ts=0; + uint32_t user_ts = 0; int channels; SessionSet *set; char *filename; - - if (argc<4){ - printf("%s",help); + + if (argc < 4) { + printf("%s", help); return -1; } - - channels=atoi(argv[3]); - if (channels==0){ - printf("%s",help); + + channels = atoi(argv[3]); + if (channels == 0) { + printf("%s", help); return -1; } - + ortp_init(); ortp_scheduler_init(); - - port=atoi(argv[2]); - recvbuf=ortp_malloc(160); - - for (i=0;i. */ -/* this program shows how to send streams in paralel using the SessionSet api - and two threads only. */ +/* this program shows how to send streams in paralel using the SessionSet api + and two threads only. */ #include #include -#include #include +#include -#ifndef _WIN32 -#include +#ifndef _WIN32 #include +#include #endif +int runcond = 1; -int runcond=1; - -void stophandler(int signum) -{ - runcond=0; +void stophandler(int signum) { + runcond = 0; } -static char *help="usage: mrtpsend filename ip port nstreams [--packet-size size] [--ts-inc value]\n"; +static char *help = "usage: mrtpsend filename ip port nstreams [--packet-size size] [--ts-inc value]\n"; #define STREAMS_COUNT 1000 - - -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { RtpSession *session[STREAMS_COUNT]; unsigned char *buffer; - int packet_size=160; - int ts_inc=160; + int packet_size = 160; + int ts_inc = 160; int i; FILE *infile; char *ssrc; int port; - uint32_t user_ts=0; + uint32_t user_ts = 0; int channels; SessionSet *set; - - if (argc<5){ - printf("%s",help); + + if (argc < 5) { + printf("%s", help); return -1; } - - channels=atoi(argv[4]); - if (channels==0){ - printf("%s",help); + + channels = atoi(argv[4]); + if (channels == 0) { + printf("%s", help); return -1; } - + /* look at command line options */ - for (i=5;i0) && (runcond) ) - { + set = session_set_new(); + while (((i = fread(buffer, 1, packet_size, infile)) > 0) && (runcond)) { int k; - //ortp_message("Sending packet."); - for (k=0;k. */ -/* this program shows how to receive streams in paralel using the SessionSet api - and two threads only. */ +/* this program shows how to receive streams in paralel using the SessionSet api + and two threads only. */ +#include #include -#include #include -#include +#include #ifndef _WIN32 +#include #include -#include +#include #include +#include #include -#include -#include #else //#include #endif -int runcond=1; +int runcond = 1; -void stophandler(int signum) -{ - runcond=0; +void stophandler(int signum) { + runcond = 0; } -static char *help="usage: mrtprecv file_prefix local_port number_of_streams \n" - "Receives multiples rtp streams on local_port+2*k, k={0..number_of_streams}\n"; +static char *help = "usage: mrtprecv file_prefix local_port number_of_streams \n" + "Receives multiples rtp streams on local_port+2*k, k={0..number_of_streams}\n"; #define STREAMS_COUNT 1000 -int rtp2disk(RtpSession *session,uint32_t ts, int fd) -{ +int rtp2disk(RtpSession *session, uint32_t ts, int fd) { unsigned char buffer[160]; - int err,havemore=1; - while (havemore){ - err=rtp_session_recv_with_ts(session,buffer,160,ts,&havemore); - if (err>0){ - rtp_session_set_data(session,(void*)1); + int err, havemore = 1; + while (havemore) { + err = rtp_session_recv_with_ts(session, buffer, 160, ts, &havemore); + if (err > 0) { + rtp_session_set_data(session, (void *)1); /* to indicate that (for the application) the stream has started, so we can start recording on disk */ } if (session->user_data != NULL) { - size_t ret = write(fd,buffer,err); - assert( ret == err ); + size_t ret = write(fd, buffer, err); + assert(ret == err); } } return 0; } - -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { RtpSession *session[STREAMS_COUNT]; int i; int filefd[STREAMS_COUNT]; int port; - uint32_t user_ts=0; + uint32_t user_ts = 0; int channels; SessionSet *set; char *filename; - argc=4; - argv[1]="/tmp/output"; - argv[2]="8000"; - argv[3]="100"; + argc = 4; + argv[1] = "/tmp/output"; + argv[2] = "8000"; + argv[3] = "100"; - if (argc<4){ - printf("%s",help); + if (argc < 4) { + printf("%s", help); return -1; } - channels=atoi(argv[3]); - if (channels==0){ - printf("%s",help); + channels = atoi(argv[3]); + if (channels == 0) { + printf("%s", help); return -1; } ortp_init(); ortp_scheduler_init(); - port=atoi(argv[2]); - for (i=0;isetflags=%i\n",session[k]->setflags); + session_set_set(set, session[k]); + // printf("session[k]->setflags=%i\n",session[k]->setflags); } /* and then suspend the process by selecting() */ - session_set_select(set,NULL,NULL); - for (k=0;k. */ - -#include #include +#include #include #include #ifndef _WIN32 -#include #include #include +#include #endif -int cond=1; +int cond = 1; -void stop_handler(int signum) -{ - cond=0; +void stop_handler(int signum) { + cond = 0; } -void ssrc_cb(RtpSession *session) -{ +void ssrc_cb(RtpSession *session) { printf("hey, the ssrc has changed !\n"); } -static char *help="usage: rtprecv filename loc_port [--format format] [--soundcard] [--noadapt] [--with-jitter ]\n"; +static char *help = + "usage: rtprecv filename loc_port [--format format] [--soundcard] [--noadapt] [--with-jitter ]\n"; #define MULAW 0 #define ALAW 1 @@ -50,137 +48,127 @@ static char *help="usage: rtprecv filename loc_port [--format format] [--soundc #include -int sound_init(int format) -{ +int sound_init(int format) { int fd; - fd=open("/dev/audio",O_WRONLY); - if (fd<0){ + fd = open("/dev/audio", O_WRONLY); + if (fd < 0) { perror("Can't open /dev/audio"); return -1; } - ioctl(fd,AUDIO_RESET,0); - ioctl(fd,AUDIO_SET_SAMPLE_RATE,8000); - ioctl(fd,AUDIO_SET_CHANNELS,1); - if (format==MULAW) - ioctl(fd,AUDIO_SET_DATA_FORMAT,AUDIO_FORMAT_ULAW); - else ioctl(fd,AUDIO_SET_DATA_FORMAT,AUDIO_FORMAT_ALAW); - return fd; + ioctl(fd, AUDIO_RESET, 0); + ioctl(fd, AUDIO_SET_SAMPLE_RATE, 8000); + ioctl(fd, AUDIO_SET_CHANNELS, 1); + if (format == MULAW) ioctl(fd, AUDIO_SET_DATA_FORMAT, AUDIO_FORMAT_ULAW); + else ioctl(fd, AUDIO_SET_DATA_FORMAT, AUDIO_FORMAT_ALAW); + return fd; } #else -int sound_init(int format) -{ +int sound_init(int format) { return -1; } #endif -int main(int argc, char*argv[]) -{ +int main(int argc, char *argv[]) { RtpSession *session; unsigned char buffer[160]; int err; - uint32_t ts=0; - int stream_received=0; + uint32_t ts = 0; + int stream_received = 0; FILE *outfile; int local_port; int have_more; int i; - int format=0; - int soundcard=0; - int sound_fd=0; - int jittcomp=40; - bool_t adapt=TRUE; - + int format = 0; + int soundcard = 0; + int sound_fd = 0; + int jittcomp = 40; + bool_t adapt = TRUE; + /* init the lib */ - if (argc<3){ - printf("%s",help); + if (argc < 3) { + printf("%s", help); return -1; } - local_port=atoi(argv[2]); - if (local_port<=0) { - printf("%s",help); + local_port = atoi(argv[2]); + if (local_port <= 0) { + printf("%s", help); return -1; } - for (i=3;i0) stream_received=1; - /* this is to avoid to write to disk some silence before the first RTP packet is returned*/ - if ((stream_received) && (err>0)) { - size_t ret = fwrite(buffer,1,err,outfile); - if (sound_fd>0){ - ret = write(sound_fd,buffer,err); - if (ret==-1){ - fprintf(stderr,"write to sound card failed (%s)",strerror(errno)); + ortp_set_log_level_mask(NULL, ORTP_DEBUG | ORTP_MESSAGE | ORTP_WARNING | ORTP_ERROR); + signal(SIGINT, stop_handler); + session = rtp_session_new(RTP_SESSION_RECVONLY); + rtp_session_set_scheduling_mode(session, 1); + rtp_session_set_blocking_mode(session, 1); + rtp_session_set_local_addr(session, "0.0.0.0", atoi(argv[2]), -1); + rtp_session_set_connected_mode(session, TRUE); + rtp_session_set_symmetric_rtp(session, TRUE); + rtp_session_enable_adaptive_jitter_compensation(session, adapt); + rtp_session_set_jitter_compensation(session, jittcomp); + rtp_session_set_payload_type(session, 0); + rtp_session_signal_connect(session, "ssrc_changed", (RtpCallback)ssrc_cb, 0); + rtp_session_signal_connect(session, "ssrc_changed", (RtpCallback)rtp_session_reset, 0); + + while (cond) { + have_more = 1; + while (have_more) { + err = rtp_session_recv_with_ts(session, buffer, 160, ts, &have_more); + if (err > 0) stream_received = 1; + /* this is to avoid to write to disk some silence before the first RTP packet is returned*/ + if ((stream_received) && (err > 0)) { + size_t ret = fwrite(buffer, 1, err, outfile); + if (sound_fd > 0) { + ret = write(sound_fd, buffer, err); + if (ret == -1) { + fprintf(stderr, "write to sound card failed (%s)", strerror(errno)); } } } } - ts+=160; - //ortp_message("Receiving packet."); + ts += 160; + // ortp_message("Receiving packet."); } - + rtp_session_destroy(session); ortp_exit(); - + ortp_global_stats_display(); - + return 0; } diff --git a/src/tests/rtpsend.c b/src/tests/rtpsend.c index bfd489d8..7df9dcc5 100644 --- a/src/tests/rtpsend.c +++ b/src/tests/rtpsend.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -23,94 +23,92 @@ #include #ifndef _WIN32 -#include -#include #include +#include +#include #endif -int runcond=1; +int runcond = 1; -void stophandler(int signum) -{ - runcond=0; +void stophandler(int signum) { + runcond = 0; } -static const char *help="usage: rtpsend filename dest_ip4addr dest_port [ --with-clockslide ] [ --with-jitter ]\n"; +static const char *help = + "usage: rtpsend filename dest_ip4addr dest_port [ --with-clockslide ] [ --with-jitter ]\n"; -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { RtpSession *session; unsigned char buffer[160]; int i; FILE *infile; char *ssrc; - uint32_t user_ts=0; - int clockslide=0; - int jitter=0; - if (argc<4){ + uint32_t user_ts = 0; + int clockslide = 0; + int jitter = 0; + if (argc < 4) { printf("%s", help); return -1; } - for(i=4;i=argc) { + if (i >= argc) { printf("%s", help); return -1; } - clockslide=atoi(argv[i]); - ortp_message("Using clockslide of %i milisecond every 50 packets.",clockslide); - }else if (strcmp(argv[i],"--with-jitter")==0){ + clockslide = atoi(argv[i]); + ortp_message("Using clockslide of %i milisecond every 50 packets.", clockslide); + } else if (strcmp(argv[i], "--with-jitter") == 0) { ortp_message("Jitter will be added to outgoing stream."); i++; - if (i>=argc) { + if (i >= argc) { printf("%s", help); return -1; } - jitter=atoi(argv[i]); + jitter = atoi(argv[i]); } } ortp_init(); ortp_scheduler_init(); - ortp_set_log_level_mask(NULL, ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR); - session=rtp_session_new(RTP_SESSION_SENDONLY); + ortp_set_log_level_mask(NULL, ORTP_MESSAGE | ORTP_WARNING | ORTP_ERROR); + session = rtp_session_new(RTP_SESSION_SENDONLY); - rtp_session_set_scheduling_mode(session,1); - rtp_session_set_blocking_mode(session,1); - rtp_session_set_connected_mode(session,TRUE); - rtp_session_set_remote_addr(session,argv[2],atoi(argv[3])); - rtp_session_set_payload_type(session,0); + rtp_session_set_scheduling_mode(session, 1); + rtp_session_set_blocking_mode(session, 1); + rtp_session_set_connected_mode(session, TRUE); + rtp_session_set_remote_addr(session, argv[2], atoi(argv[3])); + rtp_session_set_payload_type(session, 0); - ssrc=getenv("SSRC"); - if (ssrc!=NULL) { - printf("using SSRC=%i.\n",atoi(ssrc)); - rtp_session_set_ssrc(session,atoi(ssrc)); + ssrc = getenv("SSRC"); + if (ssrc != NULL) { + printf("using SSRC=%i.\n", atoi(ssrc)); + rtp_session_set_ssrc(session, atoi(ssrc)); } - #ifndef _WIN32 - infile=fopen(argv[1],"r"); - #else - infile=fopen(argv[1],"rb"); - #endif +#ifndef _WIN32 + infile = fopen(argv[1], "r"); +#else + infile = fopen(argv[1], "rb"); +#endif - if (infile==NULL) { + if (infile == NULL) { perror("Cannot open file"); return -1; } - signal(SIGINT,stophandler); - while( ((i=fread(buffer,1,160,infile))>0) && (runcond) ) - { - rtp_session_send_with_ts(session,buffer,i,user_ts); - user_ts+=160; - if (clockslide!=0 && user_ts%(160*50)==0){ - ortp_message("Clock sliding of %i miliseconds now",clockslide); - rtp_session_make_time_distorsion(session,clockslide); + signal(SIGINT, stophandler); + while (((i = fread(buffer, 1, 160, infile)) > 0) && (runcond)) { + rtp_session_send_with_ts(session, buffer, i, user_ts); + user_ts += 160; + if (clockslide != 0 && user_ts % (160 * 50) == 0) { + ortp_message("Clock sliding of %i miliseconds now", clockslide); + rtp_session_make_time_distorsion(session, clockslide); } /*this will simulate a burst of late packets */ - if (jitter && (user_ts%(8000)==0)) { - ortp_message("Simulating late packets now (%i milliseconds)",jitter); + if (jitter && (user_ts % (8000) == 0)) { + ortp_message("Simulating late packets now (%i milliseconds)", jitter); bctbx_sleep_ms(jitter); } } diff --git a/src/tests/rtpsend_stupid.c b/src/tests/rtpsend_stupid.c index 1fce8e8b..e4f4c50b 100644 --- a/src/tests/rtpsend_stupid.c +++ b/src/tests/rtpsend_stupid.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -22,99 +22,98 @@ #include #include -#ifndef _WIN32 -#include -#include +#ifndef _WIN32 #include +#include +#include #endif /*defined in library, but not declared in public headers (this method is only useful for tests)*/ -ORTP_PUBLIC extern int __rtp_session_sendm_with_ts(RtpSession *session, mblk_t *packet, uint32_t packet_ts, uint32_t send_ts); +ORTP_PUBLIC extern int +__rtp_session_sendm_with_ts(RtpSession *session, mblk_t *packet, uint32_t packet_ts, uint32_t send_ts); -int runcond=1; +int runcond = 1; -void stophandler(int signum) -{ - runcond=0; +void stophandler(int signum) { + runcond = 0; } -static char *help="usage: rtpsend filename dest_ip4addr dest_port [ --with-clockslide ] [ --with-ptime ]\n"; +static char *help = + "usage: rtpsend filename dest_ip4addr dest_port [ --with-clockslide ] [ --with-ptime ]\n"; -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { RtpSession *session; unsigned char buffer[160]; int i; FILE *infile; char *ssrc; - uint32_t packet_ts=0,send_ts=0; - uint32_t send_ts_inc=160; - int clockslide=0; - int jitter=0; - if (argc<4){ - printf("%s",help); + uint32_t packet_ts = 0, send_ts = 0; + uint32_t send_ts_inc = 160; + int clockslide = 0; + int jitter = 0; + if (argc < 4) { + printf("%s", help); return -1; } - for(i=4;i=argc) { - printf("%s",help); + if (i >= argc) { + printf("%s", help); return -1; } - clockslide=atoi(argv[i]); - ortp_message("Using clockslide of %i milisecond every 50 packets.",clockslide); - }else if (strcmp(argv[i],"--with-ptime")==0){ + clockslide = atoi(argv[i]); + ortp_message("Using clockslide of %i milisecond every 50 packets.", clockslide); + } else if (strcmp(argv[i], "--with-ptime") == 0) { ortp_message("Ptime related jitter will be added to outgoing stream."); i++; - if (i>=argc) { - printf("%s",help); + if (i >= argc) { + printf("%s", help); return -1; } - jitter=atoi(argv[i]); - send_ts_inc=jitter*8; + jitter = atoi(argv[i]); + send_ts_inc = jitter * 8; } } - + ortp_init(); ortp_scheduler_init(); - ortp_set_log_level_mask(NULL, ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR); - session=rtp_session_new(RTP_SESSION_SENDONLY); - - rtp_session_set_scheduling_mode(session,1); - rtp_session_set_blocking_mode(session,1); - rtp_session_set_connected_mode(session,TRUE); - rtp_session_set_remote_addr(session,argv[2],atoi(argv[3])); - rtp_session_set_payload_type(session,0); - - ssrc=getenv("SSRC"); - if (ssrc!=NULL) { - printf("using SSRC=%i.\n",atoi(ssrc)); - rtp_session_set_ssrc(session,atoi(ssrc)); + ortp_set_log_level_mask(NULL, ORTP_MESSAGE | ORTP_WARNING | ORTP_ERROR); + session = rtp_session_new(RTP_SESSION_SENDONLY); + + rtp_session_set_scheduling_mode(session, 1); + rtp_session_set_blocking_mode(session, 1); + rtp_session_set_connected_mode(session, TRUE); + rtp_session_set_remote_addr(session, argv[2], atoi(argv[3])); + rtp_session_set_payload_type(session, 0); + + ssrc = getenv("SSRC"); + if (ssrc != NULL) { + printf("using SSRC=%i.\n", atoi(ssrc)); + rtp_session_set_ssrc(session, atoi(ssrc)); } - - #ifndef _WIN32 - infile=fopen(argv[1],"r"); - #else - infile=fopen(argv[1],"rb"); - #endif - if (infile==NULL) { +#ifndef _WIN32 + infile = fopen(argv[1], "r"); +#else + infile = fopen(argv[1], "rb"); +#endif + + if (infile == NULL) { perror("Cannot open file"); return -1; } - signal(SIGINT,stophandler); - while( ((i=fread(buffer,1,160,infile))>0) && (runcond) ) - { - mblk_t *m=rtp_session_create_packet(session,RTP_FIXED_HEADER_SIZE,buffer,i); - __rtp_session_sendm_with_ts(session,m,packet_ts,send_ts); - packet_ts+=160; - if ((send_ts+send_ts_inc)<=packet_ts){ - send_ts+=send_ts_inc; + signal(SIGINT, stophandler); + while (((i = fread(buffer, 1, 160, infile)) > 0) && (runcond)) { + mblk_t *m = rtp_session_create_packet(session, RTP_FIXED_HEADER_SIZE, buffer, i); + __rtp_session_sendm_with_ts(session, m, packet_ts, send_ts); + packet_ts += 160; + if ((send_ts + send_ts_inc) <= packet_ts) { + send_ts += send_ts_inc; } - if (clockslide!=0 && send_ts%(160*50)==0){ - ortp_message("Clock sliding of %i miliseconds now",clockslide); - rtp_session_make_time_distorsion(session,clockslide); + if (clockslide != 0 && send_ts % (160 * 50) == 0) { + ortp_message("Clock sliding of %i miliseconds now", clockslide); + rtp_session_make_time_distorsion(session, clockslide); } } diff --git a/src/tests/test_timer.c b/src/tests/test_timer.c index be8e14af..ace8b353 100644 --- a/src/tests/test_timer.c +++ b/src/tests/test_timer.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,24 +18,21 @@ * along with this program. If not, see . */ - #include "../rtptimer.h" #include -int main(int argc, char *argv[]) -{ - RtpTimer *timer=&posix_timer; +int main(int argc, char *argv[]) { + RtpTimer *timer = &posix_timer; int i; struct timeval interval; - - interval.tv_sec=0; - interval.tv_usec=500000; - - rtp_timer_set_interval(timer,&interval); - + + interval.tv_sec = 0; + interval.tv_usec = 500000; + + rtp_timer_set_interval(timer, &interval); + timer->timer_init(); - for (i=0;i<10;i++) - { + for (i = 0; i < 10; i++) { printf("doing something...\n"); timer->timer_do(); } diff --git a/src/tests/tevmrtprecv.c b/src/tests/tevmrtprecv.c index 318fd2f7..fc8aa743 100644 --- a/src/tests/tevmrtprecv.c +++ b/src/tests/tevmrtprecv.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,21 +18,21 @@ * along with this program. If not, see . */ -/* this program shows how to receive streams in paralel using the SessionSet api - and two threads only. */ +/* this program shows how to receive streams in paralel using the SessionSet api + and two threads only. */ +#include #include -#include #include -#include +#include #ifndef _WIN32 +#include #include -#include +#include #include +#include #include -#include -#include #else //#include @@ -40,130 +40,123 @@ #include -int runcond=1; +int runcond = 1; -void stophandler(int signum) -{ - runcond=0; +void stophandler(int signum) { + runcond = 0; } -static int dtmf_tab[16]={'0','1','2','3','4','5','6','7','8','9','*','#','A','B','C','D'}; +static int dtmf_tab[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '#', 'A', 'B', 'C', 'D'}; static int *p_channel_id; -int dtmf_count=0; +int dtmf_count = 0; -static char *help="usage: tevmrtprecv file_prefix local_port number_of_streams \n" - "Receives multiples rtp streams with telephone events on local_port+2*k, k={0..number_of_streams}\n"; +static char *help = + "usage: tevmrtprecv file_prefix local_port number_of_streams \n" + "Receives multiples rtp streams with telephone events on local_port+2*k, k={0..number_of_streams}\n"; #define STREAMS_COUNT 1000 - -void recv_tev_cb(RtpSession *session,unsigned long type, unsigned long dummy, void* user_data) -{ - //printf("Receiving telephony event:%i\n",type); - if (type<16) printf("This is dtmf %c on channel %d\n",dtmf_tab[type],*(int *)user_data); - dtmf_count++; +void recv_tev_cb(RtpSession *session, unsigned long type, unsigned long dummy, void *user_data) { + // printf("Receiving telephony event:%i\n",type); + if (type < 16) printf("This is dtmf %c on channel %d\n", dtmf_tab[type], *(int *)user_data); + dtmf_count++; } -int rtp2disk(RtpSession *session,uint32_t ts, int fd) -{ +int rtp2disk(RtpSession *session, uint32_t ts, int fd) { unsigned char buffer[160]; - int err,havemore=1; - while (havemore){ - err=rtp_session_recv_with_ts(session,buffer,160,ts,&havemore); - if (err>0){ - rtp_session_set_data(session,(void*)1); + int err, havemore = 1; + while (havemore) { + err = rtp_session_recv_with_ts(session, buffer, 160, ts, &havemore); + if (err > 0) { + rtp_session_set_data(session, (void *)1); /* to indicate that (for the application) the stream has started, so we can start recording on disk */ } if (session->user_data != NULL) { - size_t ret = write(fd,buffer,err); - assert( ret == err ); + size_t ret = write(fd, buffer, err); + assert(ret == err); } } return 0; } - -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { RtpSession *session[STREAMS_COUNT]; int i; int filefd[STREAMS_COUNT]; int port; - uint32_t user_ts=0; + uint32_t user_ts = 0; int channels; SessionSet *set; char *filename; - if (argc<4){ - printf("%s",help); + if (argc < 4) { + printf("%s", help); return -1; } - - channels=atoi(argv[3]); - if (channels==0){ - printf("%s",help); + + channels = atoi(argv[3]); + if (channels == 0) { + printf("%s", help); return -1; } - + ortp_init(); ortp_scheduler_init(); - - /* set the telephony event payload type to 96 in the av profile.*/ - rtp_profile_set_payload(&av_profile,96,&payload_type_telephone_event); - port=atoi(argv[2]); - p_channel_id = (int *)ortp_malloc(channels*sizeof(int)); - for (i=0;i. */ +#include #include #include #include #include -#include #include #ifndef _WIN32 #include @@ -31,37 +31,34 @@ #endif #include -int runcond=1; +int runcond = 1; -static int dtmf_tab[16]={'0','1','2','3','4','5','6','7','8','9','*','#','A','B','C','D'}; +static int dtmf_tab[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '#', 'A', 'B', 'C', 'D'}; -void stophandler(int signum) -{ - runcond=0; +void stophandler(int signum) { + runcond = 0; } -static char *help="usage: test_tevrecv filename loc_port\n"; +static char *help = "usage: test_tevrecv filename loc_port\n"; -int dtmf_count=0; +int dtmf_count = 0; -void recv_tev_cb(RtpSession *session,unsigned long type, unsigned long dummy, void* user_data) -{ - printf("Receiving telephony event:%lu\n",type); - if (type<16) printf("This is dtmf %c\n",dtmf_tab[type]); +void recv_tev_cb(RtpSession *session, unsigned long type, unsigned long dummy, void *user_data) { + printf("Receiving telephony event:%lu\n", type); + if (type < 16) printf("This is dtmf %c\n", dtmf_tab[type]); dtmf_count++; } -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { RtpSession *session; unsigned char buffer[160]; int err; FILE *outfile; - uint32_t ts=0; + uint32_t ts = 0; int have_more; - if (argc<3){ - printf("%s",help); + if (argc < 3) { + printf("%s", help); return -1; } @@ -69,40 +66,39 @@ int main(int argc, char *argv[]) ortp_scheduler_init(); /* set the telephony event payload type to 96 in the av profile.*/ - rtp_profile_set_payload(&av_profile,96,&payload_type_telephone_event); + rtp_profile_set_payload(&av_profile, 96, &payload_type_telephone_event); - session=rtp_session_new(RTP_SESSION_RECVONLY); + session = rtp_session_new(RTP_SESSION_RECVONLY); - rtp_session_set_scheduling_mode(session,1); - rtp_session_set_blocking_mode(session,1); - rtp_session_set_local_addr(session,"0.0.0.0",atoi(argv[2]),-1); - rtp_session_set_payload_type(session,0); + rtp_session_set_scheduling_mode(session, 1); + rtp_session_set_blocking_mode(session, 1); + rtp_session_set_local_addr(session, "0.0.0.0", atoi(argv[2]), -1); + rtp_session_set_payload_type(session, 0); /* register for telephony events */ - rtp_session_signal_connect(session,"telephone-event",(RtpCallback)recv_tev_cb,0); + rtp_session_signal_connect(session, "telephone-event", (RtpCallback)recv_tev_cb, 0); - outfile=fopen(argv[1],"wb"); - if (outfile==NULL) { + outfile = fopen(argv[1], "wb"); + if (outfile == NULL) { perror("Cannot open file"); return -1; } - signal(SIGINT,stophandler); - while(runcond) - { - have_more=1; - while (have_more){ - err=rtp_session_recv_with_ts(session,buffer,160,ts,&have_more); - if (err>0) { - assert(fwrite(buffer,1,err,outfile) == err ); + signal(SIGINT, stophandler); + while (runcond) { + have_more = 1; + while (have_more) { + err = rtp_session_recv_with_ts(session, buffer, 160, ts, &have_more); + if (err > 0) { + assert(fwrite(buffer, 1, err, outfile) == err); } } - ts+=160; - //ortp_message("Receiving packet."); + ts += 160; + // ortp_message("Receiving packet."); } fclose(outfile); rtp_session_destroy(session); ortp_exit(); ortp_global_stats_display(); - printf("Total dtmf events received: %i\n",dtmf_count); + printf("Total dtmf events received: %i\n", dtmf_count); return 0; } diff --git a/src/tests/tevrtpsend.c b/src/tests/tevrtpsend.c index fd3276e3..78fa2b33 100644 --- a/src/tests/tevrtpsend.c +++ b/src/tests/tevrtpsend.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -30,66 +30,63 @@ #endif #include -int runcond=1; +int runcond = 1; -void stophandler(int signum) -{ - runcond=0; +void stophandler(int signum) { + runcond = 0; } -static char *help="usage: test_tevsend filename dest_ip4addr dest_port\n"; +static char *help = "usage: test_tevsend filename dest_ip4addr dest_port\n"; -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { RtpSession *session; unsigned char buffer[160]; int i; FILE *infile; char *ssrc; - uint32_t user_ts=0; - int tel=0; - - if (argc<4){ - printf("%s",help); + uint32_t user_ts = 0; + int tel = 0; + + if (argc < 4) { + printf("%s", help); return -1; } - + ortp_init(); ortp_scheduler_init(); - + /* set the telephony event payload type to 96 in the av profile.*/ - rtp_profile_set_payload(&av_profile,96,&payload_type_telephone_event); - - session=rtp_session_new(RTP_SESSION_SENDONLY); - - rtp_session_set_scheduling_mode(session,1); - rtp_session_set_blocking_mode(session,1); - rtp_session_set_remote_addr(session,argv[2],atoi(argv[3])); - rtp_session_set_send_payload_type(session,0); - - ssrc=getenv("SSRC"); - if (ssrc!=NULL) { - printf("using SSRC=%i.\n",atoi(ssrc)); - rtp_session_set_ssrc(session,atoi(ssrc)); + rtp_profile_set_payload(&av_profile, 96, &payload_type_telephone_event); + + session = rtp_session_new(RTP_SESSION_SENDONLY); + + rtp_session_set_scheduling_mode(session, 1); + rtp_session_set_blocking_mode(session, 1); + rtp_session_set_remote_addr(session, argv[2], atoi(argv[3])); + rtp_session_set_send_payload_type(session, 0); + + ssrc = getenv("SSRC"); + if (ssrc != NULL) { + printf("using SSRC=%i.\n", atoi(ssrc)); + rtp_session_set_ssrc(session, atoi(ssrc)); } - - infile=fopen(argv[1],"rb"); - if (infile==NULL) { + + infile = fopen(argv[1], "rb"); + if (infile == NULL) { perror("Cannot open file"); return -1; } - signal(SIGINT,stophandler); - while( ((i=fread(buffer,1,160,infile))>0) && (runcond) ) - { - //ortp_message("Sending packet."); - rtp_session_send_with_ts(session,buffer,i,user_ts); - user_ts+=160; + signal(SIGINT, stophandler); + while (((i = fread(buffer, 1, 160, infile)) > 0) && (runcond)) { + // ortp_message("Sending packet."); + rtp_session_send_with_ts(session, buffer, i, user_ts); + user_ts += 160; tel++; - if (tel==50){ - tel=0; + if (tel == 50) { + tel = 0; ortp_message("Sending telephony event packet."); - rtp_session_send_dtmf(session,'*',user_ts); - user_ts+=160+160+160; /* the duration of the dtmf */ + rtp_session_send_dtmf(session, '*', user_ts); + user_ts += 160 + 160 + 160; /* the duration of the dtmf */ } } fclose(infile); diff --git a/src/tests/win_receiver/RTPReceiver.cpp b/src/tests/win_receiver/RTPReceiver.cpp index 39ca20f4..dad46ef3 100644 --- a/src/tests/win_receiver/RTPReceiver.cpp +++ b/src/tests/win_receiver/RTPReceiver.cpp @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -17,123 +17,111 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ +#include #include #include #include #include -#include #include #define STREAMS_COUNT 1000 -BOOL m_bExit = FALSE; - -static char *help="usage: mrtprecv file_prefix local_port number_of_streams \n" - "Receives multiples rtp streams on local_port+2*k, k={0..number_of_streams}\n"; +BOOL m_bExit = FALSE; +static char *help = "usage: mrtprecv file_prefix local_port number_of_streams \n" + "Receives multiples rtp streams on local_port+2*k, k={0..number_of_streams}\n"; -void ProductVersion() -{ - char strBuffer[255]; +void ProductVersion() { + char strBuffer[255]; printf("====================================\n"); printf("Author : Simon Morlat =\n"); printf("Porting : Yann STEPHAN =\n"); - printf("====================================\n"); - + printf("====================================\n"); + memset(&strBuffer, 0x0, sizeof(strBuffer)); - sprintf((char *) &strBuffer, "= RTPReceiver V1.0 - Date : %s - %s\n", __DATE__, __TIME__); - printf(strBuffer); - - printf("====================================\n"); -} - -BOOL ctrlHandlerFunction(DWORD fdwCtrlType) -{ - switch (fdwCtrlType) - { - // Handle the CTRL+C signal. - // CTRL+CLOSE: confirm that the user wants to exit. - case CTRL_C_EVENT: - case CTRL_CLOSE_EVENT: - case CTRL_BREAK_EVENT: - case CTRL_LOGOFF_EVENT: - case CTRL_SHUTDOWN_EVENT: + sprintf((char *)&strBuffer, "= RTPReceiver V1.0 - Date : %s - %s\n", __DATE__, __TIME__); + printf(strBuffer); + + printf("====================================\n"); +} + +BOOL ctrlHandlerFunction(DWORD fdwCtrlType) { + switch (fdwCtrlType) { + // Handle the CTRL+C signal. + // CTRL+CLOSE: confirm that the user wants to exit. + case CTRL_C_EVENT: + case CTRL_CLOSE_EVENT: + case CTRL_BREAK_EVENT: + case CTRL_LOGOFF_EVENT: + case CTRL_SHUTDOWN_EVENT: m_bExit = TRUE; - return TRUE; + return TRUE; - default: - return FALSE; - } -} + default: + return FALSE; + } +} -int rtp2disk(RtpSession *session,uint32_t ts, FILE * fd) -{ +int rtp2disk(RtpSession *session, uint32_t ts, FILE *fd) { char buffer[160]; - int err,havemore=1; - - while (havemore) - { - err=rtp_session_recv_with_ts(session,buffer,160,ts,&havemore); - - if (havemore) - printf("==> Warning: havemore=1!\n"); - - if (err>0) - { - rtp_session_set_data(session,(void*)1); + int err, havemore = 1; + + while (havemore) { + err = rtp_session_recv_with_ts(session, buffer, 160, ts, &havemore); + + if (havemore) printf("==> Warning: havemore=1!\n"); + + if (err > 0) { + rtp_session_set_data(session, (void *)1); /* to indicate that (for the application) the stream has started, so we can start recording on disk */ } - if (session->user_data != NULL) - { - fwrite(&buffer,1,160, fd); + if (session->user_data != NULL) { + fwrite(&buffer, 1, 160, fd); } } return 0; } -int GetSystemInformation() -{ - SYSTEM_INFO SystemInfo; +int GetSystemInformation() { + SYSTEM_INFO SystemInfo; GetSystemInfo(&SystemInfo); return SystemInfo.dwNumberOfProcessors; } -int __cdecl main(int argc, char *argv[]) -{ - RtpSession * session[STREAMS_COUNT]; - FILE * filefd[STREAMS_COUNT]; - SessionSet * set; +int __cdecl main(int argc, char *argv[]) { + RtpSession *session[STREAMS_COUNT]; + FILE *filefd[STREAMS_COUNT]; + SessionSet *set; + + uint32_t user_ts = 0; - uint32_t user_ts = 0; + int port = 0; + int channels = 0; + int i = 0; + int nCPUCount = 0; + int nSchedulerCPU = 2; - int port = 0; - int channels = 0; - int i = 0; - int nCPUCount = 0; - int nSchedulerCPU = 2; + char strFilename[MAX_PATH]; - char strFilename[MAX_PATH]; - ProductVersion(); - if (argc<4) - { + if (argc < 4) { printf(help); return -1; } - - channels=atoi(argv[3]); - if (channels==0){ + + channels = atoi(argv[3]); + if (channels == 0) { printf(help); return -1; } - + // Now it's time to use the power of multiple CPUs nCPUCount = GetSystemInformation(); @@ -141,98 +129,86 @@ int __cdecl main(int argc, char *argv[]) ortp_init(); ortp_scheduler_init(); - - if (nCPUCount > 1) - { - if (nCPUCount > 2) - { - nSchedulerCPU = 3; - } -/* if (ortp_bind_scheduler_to_cpu(nSchedulerCPU) != -1) - { - printf("==> Scheduler has been binded to CPU %d\n", nSchedulerCPU); + if (nCPUCount > 1) { + if (nCPUCount > 2) { + nSchedulerCPU = 3; } - else - { - printf("==> Scheduler still binded to CPU 1\n"); - } -*/ + + /* if (ortp_bind_scheduler_to_cpu(nSchedulerCPU) != -1) + { + printf("==> Scheduler has been binded to CPU %d\n", nSchedulerCPU); + } + else + { + printf("==> Scheduler still binded to CPU 1\n"); + } + */ } - port=atoi(argv[2]); + port = atoi(argv[2]); - for (i=0;i Cannot handle the CTRL-C...\n"); } /* create a set */ - set=session_set_new(); + set = session_set_new(); printf("==> RTP Receiver started\n"); - while(m_bExit == FALSE) - { + while (m_bExit == FALSE) { int k; - - for (k=0;k Warning: session_set_select() is returning 0...\n"); } - for (k=0;k Session_set_is_set %d\n", k); - } - else - { - //printf("warning: session %i is not set !\n",k); + for (k = 0; k < channels; k++) { + if (session_set_is_set(set, session[k])) { + rtp2disk(session[k], user_ts, filefd[k]); + // printf("==> Session_set_is_set %d\n", k); + } else { + // printf("warning: session %i is not set !\n",k); } } - user_ts+=160; + user_ts += 160; } printf("==> Exiting\n"); - for (i=0;i Sorry dude...\n"); Sleep(1000); return -1; @@ -165,95 +146,83 @@ int __cdecl main(int argc, char *argv[]) printf("==> Starting the RTP Sender test\n"); - // =============== INSTALL THE CONTROL HANDLER =============== - if (SetConsoleCtrlHandler( (PHANDLER_ROUTINE) ctrlHandlerFunction, TRUE) == 0) - { + if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)ctrlHandlerFunction, TRUE) == 0) { printf("==> Cannot handle the CTRL-C...\n"); } + printf("==> Timestamp increment will be %i\n", m_nTimestamp_Inc); + printf("==> Packet size will be %i\n", m_nPacket_Size); - printf("==> Timestamp increment will be %i\n" , m_nTimestamp_Inc); - printf("==> Packet size will be %i\n" , m_nPacket_Size); - - m_pBuffer = (char *) ortp_malloc(m_nPacket_Size); + m_pBuffer = (char *)ortp_malloc(m_nPacket_Size); ortp_init(); ortp_scheduler_init(); printf("==> Scheduler initialized\n"); - m_SSRC = getenv("SSRC"); - m_nPort = atoi(argv[3]); + m_SSRC = getenv("SSRC"); + m_nPort = atoi(argv[3]); + + for (nCounter = 0; nCounter < m_nChannels; nCounter++) { + // printf("==> Channel [#%d]\n", nCounter); - for (nCounter=0; nCounter < m_nChannels; nCounter++) - { - //printf("==> Channel [#%d]\n", nCounter); + m_Session[nCounter] = rtp_session_new(RTP_SESSION_SENDONLY); - m_Session[nCounter] = rtp_session_new(RTP_SESSION_SENDONLY); + rtp_session_set_scheduling_mode(m_Session[nCounter], 1); + rtp_session_set_blocking_mode(m_Session[nCounter], 0); + rtp_session_set_remote_addr(m_Session[nCounter], argv[2], m_nPort); + rtp_session_set_send_payload_type(m_Session[nCounter], 0); - rtp_session_set_scheduling_mode(m_Session[nCounter],1); - rtp_session_set_blocking_mode(m_Session[nCounter],0); - rtp_session_set_remote_addr(m_Session[nCounter],argv[2], m_nPort); - rtp_session_set_send_payload_type(m_Session[nCounter],0); - - if (m_SSRC != NULL) - { - rtp_session_set_ssrc(m_Session[nCounter],atoi(m_SSRC)); + if (m_SSRC != NULL) { + rtp_session_set_ssrc(m_Session[nCounter], atoi(m_SSRC)); } - m_nPort+=2; + m_nPort += 2; } - infile=fopen(argv[1],"rb"); + infile = fopen(argv[1], "rb"); - if (infile==NULL) - { + if (infile == NULL) { printf("==> Cannot open file !!!!"); Sleep(1000); return -1; } -// printf("==> Open file\n"); - + // printf("==> Open file\n"); + /* Create a set */ pSessionSet = session_set_new(); -// printf("==> Session set\n"); + // printf("==> Session set\n"); - while( ((nCounter= (int) fread(m_pBuffer,1,m_nPacket_Size,infile))>0) && (m_bExit == FALSE) ) - { + while (((nCounter = (int)fread(m_pBuffer, 1, m_nPacket_Size, infile)) > 0) && (m_bExit == FALSE)) { int k; - //g_message("Sending packet."); - for (k=0;k Session set set %d\n", k); + session_set_set(pSessionSet, m_Session[k]); + // printf("==> Session set set %d\n", k); } /* and then suspend the process by selecting() */ - session_set_select(NULL,pSessionSet,NULL); - //printf("==> Session set select\n"); + session_set_select(NULL, pSessionSet, NULL); + // printf("==> Session set select\n"); - for (k=0;k Session set is set %d\n", k); - rtp_session_send_with_ts(m_Session[k],m_pBuffer,nCounter,m_nUser_Timestamp); - //g_message("packet sended !"); + if (session_set_is_set(pSessionSet, m_Session[k])) { + // printf("==> Session set is set %d\n", k); + rtp_session_send_with_ts(m_Session[k], m_pBuffer, nCounter, m_nUser_Timestamp); + // g_message("packet sended !"); } } - m_nUser_Timestamp+=m_nTimestamp_Inc; + m_nUser_Timestamp += m_nTimestamp_Inc; } fclose(infile); printf("==> Close file\n"); - - - for(nCounter=0;nCounter Remove the CTRL-C handler...\n"); - SetConsoleCtrlHandler( (PHANDLER_ROUTINE) ctrlHandlerFunction, FALSE); + SetConsoleCtrlHandler((PHANDLER_ROUTINE)ctrlHandlerFunction, FALSE); // Wait for an input key printf("Waiting for exit : "); - for (nCounter = 0; nCounter < 4*5; nCounter++) - { + for (nCounter = 0; nCounter < 4 * 5; nCounter++) { printf("."); Sleep(250); } return 0; } - diff --git a/src/utils.c b/src/utils.c index 746f3af5..27a323cb 100644 --- a/src/utils.c +++ b/src/utils.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -20,47 +20,45 @@ #ifdef HAVE_CONFIG_H #include "ortp-config.h" #endif -#include "ortp/port.h" +#include "math.h" #include "ortp/logging.h" +#include "ortp/port.h" #include "utils.h" -#include "math.h" - -uint64_t ortp_timeval_to_ntp(const struct timeval *tv){ +uint64_t ortp_timeval_to_ntp(const struct timeval *tv) { uint64_t msw; uint64_t lsw; - msw=tv->tv_sec + 0x83AA7E80; /* 0x83AA7E80 is the number of seconds from 1900 to 1970 */ - lsw=(uint32_t)((double)tv->tv_usec*(double)(((uint64_t)1)<<32)*1.0e-6); - return msw<<32 | lsw; + msw = tv->tv_sec + 0x83AA7E80; /* 0x83AA7E80 is the number of seconds from 1900 to 1970 */ + lsw = (uint32_t)((double)tv->tv_usec * (double)(((uint64_t)1) << 32) * 1.0e-6); + return msw << 32 | lsw; } - -void ortp_bw_estimator_init(OrtpBwEstimator *obj, float alpha, float step){ +void ortp_bw_estimator_init(OrtpBwEstimator *obj, float alpha, float step) { obj->one_minus_alpha = 1.0f - alpha; - obj->inv_step = 1.0f/step; + obj->inv_step = 1.0f / step; obj->exp_constant = logf(alpha) * obj->inv_step; obj->last_packet_recv.tv_sec = 0; obj->last_packet_recv.tv_usec = 0; obj->value = 0; } -void ortp_bw_estimator_packet_received (OrtpBwEstimator *obj, size_t bytes, const struct timeval *recv_time){ +void ortp_bw_estimator_packet_received(OrtpBwEstimator *obj, size_t bytes, const struct timeval *recv_time) { float diff_time; - - if (obj->last_packet_recv.tv_sec == 0){ - diff_time = 1.0f/obj->inv_step; + + if (obj->last_packet_recv.tv_sec == 0) { + diff_time = 1.0f / obj->inv_step; ortp_message("First estimation"); - }else{ - diff_time = (float)(recv_time->tv_sec - obj->last_packet_recv.tv_sec) + 1e-6f*(recv_time->tv_usec - obj->last_packet_recv.tv_usec); + } else { + diff_time = (float)(recv_time->tv_sec - obj->last_packet_recv.tv_sec) + + 1e-6f * (recv_time->tv_usec - obj->last_packet_recv.tv_usec); } - obj->value = ((float)bytes * obj->one_minus_alpha) + expf(diff_time * obj->exp_constant)*obj->value; + obj->value = ((float)bytes * obj->one_minus_alpha) + expf(diff_time * obj->exp_constant) * obj->value; obj->last_packet_recv = *recv_time; } -float ortp_bw_estimator_get_value(OrtpBwEstimator *obj){ +float ortp_bw_estimator_get_value(OrtpBwEstimator *obj) { struct timeval current; bctbx_gettimeofday(¤t, NULL); ortp_bw_estimator_packet_received(obj, 0, ¤t); return obj->value * 8.0f * obj->inv_step; } - diff --git a/src/utils.h b/src/utils.h index 5f87475c..0d9db401 100644 --- a/src/utils.h +++ b/src/utils.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -29,7 +29,6 @@ void ortp_uninit_logger(void); #define OList bctbx_list_t - #define o_list_next(elem) ((elem)->next) #define o_list_prev(elem) ((elem)->prev) @@ -39,13 +38,12 @@ void ortp_uninit_logger(void); #define o_list_free bctbx_list_free #define o_list_remove_link bctbx_list_erase_link #define o_list_free_with_data bctbx_list_free_with_data -#define o_list_insert_sorted bctbx_list_insert_sorted +#define o_list_insert_sorted bctbx_list_insert_sorted #define ORTP_POINTER_TO_INT(p) ((int)(intptr_t)(p)) #define ORTP_INT_TO_POINTER(i) ((void *)(intptr_t)(i)) - -typedef struct _dwsplit_t{ +typedef struct _dwsplit_t { #ifdef ORTP_BIGENDIAN uint16_t hi; uint16_t lo; @@ -55,7 +53,7 @@ typedef struct _dwsplit_t{ #endif } dwsplit_t; -typedef union{ +typedef union { dwsplit_t split; uint32_t one; } poly32_t; @@ -63,14 +61,14 @@ typedef union{ #ifdef ORTP_BIGENDIAN #define hton24(x) (x) #else -#define hton24(x) ((( (x) & 0x00ff0000) >>16) | (( (x) & 0x000000ff) <<16) | ( (x) & 0x0000ff00) ) +#define hton24(x) ((((x)&0x00ff0000) >> 16) | (((x)&0x000000ff) << 16) | ((x)&0x0000ff00)) #endif #define ntoh24(x) hton24(x) #if defined(_WIN32) || defined(_WIN32_WCE) -#define is_would_block_error(errnum) (errnum==WSAEWOULDBLOCK) +#define is_would_block_error(errnum) (errnum == WSAEWOULDBLOCK) #else -#define is_would_block_error(errnum) (errnum==EWOULDBLOCK || errnum==EAGAIN) +#define is_would_block_error(errnum) (errnum == EWOULDBLOCK || errnum == EAGAIN) #endif void ortp_ev_queue_put(OrtpEvQueue *q, OrtpEvent *ev); diff --git a/src/videobandwidthestimator.c b/src/videobandwidthestimator.c index 3f9adf1a..710288a8 100644 --- a/src/videobandwidthestimator.c +++ b/src/videobandwidthestimator.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -19,58 +19,58 @@ */ #include "videobandwidthestimator.h" -#include #include +#include #include #define MIN_DIFFTIME 0.00001f -OrtpVideoBandwidthEstimator * ortp_video_bandwidth_estimator_new(RtpSession *session) { - OrtpVideoBandwidthEstimator *vbe = (OrtpVideoBandwidthEstimator*)ortp_malloc0(sizeof(OrtpVideoBandwidthEstimator)); +OrtpVideoBandwidthEstimator *ortp_video_bandwidth_estimator_new(RtpSession *session) { + OrtpVideoBandwidthEstimator *vbe = (OrtpVideoBandwidthEstimator *)ortp_malloc0(sizeof(OrtpVideoBandwidthEstimator)); vbe->session = session; vbe->packet_count_min = 5; vbe->packets_size_max = 30; vbe->trust_percentage = 90; - vbe->nb_packets_computed = 0; - vbe->packets = NULL; - vbe->last_packet = NULL; + vbe->nb_packets_computed = 0; + vbe->packets = NULL; + vbe->last_packet = NULL; return vbe; } -void ortp_video_bandwidth_estimator_destroy(OrtpVideoBandwidthEstimator *vbe){ - ortp_video_bandwidth_estimator_reset(vbe); - ortp_free(vbe); +void ortp_video_bandwidth_estimator_destroy(OrtpVideoBandwidthEstimator *vbe) { + ortp_video_bandwidth_estimator_reset(vbe); + ortp_free(vbe); } void ortp_video_bandwidth_estimator_reset(OrtpVideoBandwidthEstimator *vbe) { ortp_free(vbe->last_packet); - vbe->last_packet = NULL; - vbe->nb_packets_computed = 0; + vbe->last_packet = NULL; + vbe->nb_packets_computed = 0; vbe->packets = bctbx_list_free_with_data(vbe->packets, ortp_free); } void ortp_video_bandwidth_estimator_set_packets_count_min(OrtpVideoBandwidthEstimator *vbe, unsigned int value) { - vbe->packet_count_min = value; + vbe->packet_count_min = value; } void ortp_video_bandwidth_estimator_set_history_max_size(OrtpVideoBandwidthEstimator *vbe, unsigned int value) { - vbe->packets_size_max = value; + vbe->packets_size_max = value; } void ortp_video_bandwidth_estimator_set_trust(OrtpVideoBandwidthEstimator *vbe, unsigned int value) { - vbe->trust_percentage = value; + vbe->trust_percentage = value; } unsigned int ortp_video_bandwidth_estimator_get_packets_count_min(OrtpVideoBandwidthEstimator *vbe) { - return vbe->packet_count_min; + return vbe->packet_count_min; } unsigned int ortp_video_bandwidth_estimator_get_history_max_size(OrtpVideoBandwidthEstimator *vbe) { - return vbe->packets_size_max; + return vbe->packets_size_max; } unsigned int ortp_video_bandwidth_estimator_get_trust(OrtpVideoBandwidthEstimator *vbe) { - return vbe->trust_percentage; + return vbe->trust_percentage; } static int compare_float(const float *v1, const float *v2) { @@ -80,26 +80,28 @@ static int compare_float(const float *v1, const float *v2) { } float ortp_video_bandwidth_estimator_get_estimated_available_bandwidth(OrtpVideoBandwidthEstimator *vbe) { - bctbx_list_t *bitrate_sorted = NULL; - bctbx_list_t *elem; - float *result = NULL; - int index = (int)(vbe->trust_percentage * vbe->packets_size_max / 100); - for(elem = vbe->packets; elem != NULL; elem = bctbx_list_next(elem)) { - OrtpVideoBandwidthEstimatorPacket *packet = (OrtpVideoBandwidthEstimatorPacket *)bctbx_list_get_data(elem); - bitrate_sorted = bctbx_list_insert_sorted(bitrate_sorted, &packet->bitrate, (bctbx_compare_func)compare_float); - } - result = (float *)bctbx_list_nth_data(bitrate_sorted, index); - bctbx_list_free(bitrate_sorted); - return (float)*result; + bctbx_list_t *bitrate_sorted = NULL; + bctbx_list_t *elem; + float *result = NULL; + int index = (int)(vbe->trust_percentage * vbe->packets_size_max / 100); + for (elem = vbe->packets; elem != NULL; elem = bctbx_list_next(elem)) { + OrtpVideoBandwidthEstimatorPacket *packet = (OrtpVideoBandwidthEstimatorPacket *)bctbx_list_get_data(elem); + bitrate_sorted = bctbx_list_insert_sorted(bitrate_sorted, &packet->bitrate, (bctbx_compare_func)compare_float); + } + result = (float *)bctbx_list_nth_data(bitrate_sorted, index); + bctbx_list_free(bitrate_sorted); + return (float)*result; } -static void compute_bitrate_add_to_list_and_remove_oldest_value(OrtpVideoBandwidthEstimator *vbe, OrtpVideoBandwidthEstimatorPacket *packet) { - float difftime = (float)(packet->recv_last_timestamp.tv_sec - packet->recv_first_timestamp.tv_sec) - + 1e-6f*(packet->recv_last_timestamp.tv_usec - packet->recv_first_timestamp.tv_usec); - +static void compute_bitrate_add_to_list_and_remove_oldest_value(OrtpVideoBandwidthEstimator *vbe, + OrtpVideoBandwidthEstimatorPacket *packet) { + float difftime = (float)(packet->recv_last_timestamp.tv_sec - packet->recv_first_timestamp.tv_sec) + + 1e-6f * (packet->recv_last_timestamp.tv_usec - packet->recv_first_timestamp.tv_usec); + if (difftime > MIN_DIFFTIME) { packet->bitrate = (packet->bytes * 8 / difftime); - ortp_debug("[VBE] Bitrate is %f kbits/s computed using %f timedif and %u size", packet->bitrate / 1000, difftime, packet->bytes); + ortp_debug("[VBE] Bitrate is %f kbits/s computed using %f timedif and %u size", packet->bitrate / 1000, + difftime, packet->bytes); vbe->nb_packets_computed += 1; vbe->packets = bctbx_list_prepend(vbe->packets, packet); @@ -114,7 +116,9 @@ static void compute_bitrate_add_to_list_and_remove_oldest_value(OrtpVideoBandwid OrtpEvent *ev = ortp_event_new(ORTP_EVENT_NEW_VIDEO_BANDWIDTH_ESTIMATION_AVAILABLE); OrtpEventData *ed = ortp_event_get_data(ev); ed->info.video_bandwidth_available = ortp_video_bandwidth_estimator_get_estimated_available_bandwidth(vbe); - ortp_debug("[VBE] Dispatching event ORTP_EVENT_NEW_VIDEO_BANDWIDTH_ESTIMATION_AVAILABLE with value %f kbits/s", ed->info.video_bandwidth_available / 1000); + ortp_debug( + "[VBE] Dispatching event ORTP_EVENT_NEW_VIDEO_BANDWIDTH_ESTIMATION_AVAILABLE with value %f kbits/s", + ed->info.video_bandwidth_available / 1000); rtp_session_dispatch_event(vbe->session, ev); } } else { @@ -122,7 +126,11 @@ static void compute_bitrate_add_to_list_and_remove_oldest_value(OrtpVideoBandwid } } -void ortp_video_bandwidth_estimator_process_packet(OrtpVideoBandwidthEstimator *vbe, uint32_t sent_timestamp, const struct timeval *recv_timestamp, int msgsize, bool_t is_last) { +void ortp_video_bandwidth_estimator_process_packet(OrtpVideoBandwidthEstimator *vbe, + uint32_t sent_timestamp, + const struct timeval *recv_timestamp, + int msgsize, + bool_t is_last) { OrtpVideoBandwidthEstimatorPacket *last_packet = vbe->last_packet; OrtpVideoBandwidthEstimatorPacket *current_packet = NULL; @@ -141,7 +149,8 @@ void ortp_video_bandwidth_estimator_process_packet(OrtpVideoBandwidthEstimator * } else { // This can happen even if it's probability is quite low if (last_packet->count >= vbe->packet_count_min) { - ortp_warning("[VBE] Last packet not complete but enough packet received (%u), add to packets list", last_packet->count); + ortp_warning("[VBE] Last packet not complete but enough packet received (%u), add to packets list", + last_packet->count); compute_bitrate_add_to_list_and_remove_oldest_value(vbe, last_packet); } else { ortp_free(vbe->last_packet); @@ -151,7 +160,7 @@ void ortp_video_bandwidth_estimator_process_packet(OrtpVideoBandwidthEstimator * } if (!current_packet) { - current_packet = (OrtpVideoBandwidthEstimatorPacket*)ortp_malloc0(sizeof(OrtpVideoBandwidthEstimatorPacket)); + current_packet = (OrtpVideoBandwidthEstimatorPacket *)ortp_malloc0(sizeof(OrtpVideoBandwidthEstimatorPacket)); current_packet->count = 1; current_packet->bytes = msgsize; current_packet->sent_timestamp = sent_timestamp; diff --git a/src/videobandwidthestimator.h b/src/videobandwidthestimator.h index 2cd10fda..45e67433 100644 --- a/src/videobandwidthestimator.h +++ b/src/videobandwidthestimator.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,24 +18,23 @@ * along with this program. If not, see . */ - #ifndef VIDEOBANDWIDTHESTIMATOR_H #define VIDEOBANDWIDTHESTIMATOR_H +#include #include #include -#include -typedef struct _OrtpVideoBandwidthEstimatorPacket{ +typedef struct _OrtpVideoBandwidthEstimatorPacket { uint32_t sent_timestamp; struct timeval recv_first_timestamp; struct timeval recv_last_timestamp; unsigned int bytes; unsigned int count; float bitrate; -}OrtpVideoBandwidthEstimatorPacket; +} OrtpVideoBandwidthEstimatorPacket; -typedef struct _OrtpVideoBandwidthEstimator{ +typedef struct _OrtpVideoBandwidthEstimator { struct _RtpSession *session; unsigned int packet_count_min; unsigned int packets_size_max; @@ -43,10 +42,10 @@ typedef struct _OrtpVideoBandwidthEstimator{ OrtpVideoBandwidthEstimatorPacket *last_packet; bctbx_list_t *packets; uint32_t last_computed; - int nb_packets_computed; -}OrtpVideoBandwidthEstimator; + int nb_packets_computed; +} OrtpVideoBandwidthEstimator; -OrtpVideoBandwidthEstimator * ortp_video_bandwidth_estimator_new(struct _RtpSession *session); +OrtpVideoBandwidthEstimator *ortp_video_bandwidth_estimator_new(struct _RtpSession *session); void ortp_video_bandwidth_estimator_destroy(OrtpVideoBandwidthEstimator *vbe); @@ -90,7 +89,11 @@ unsigned int ortp_video_bandwidth_estimator_get_history_max_size(OrtpVideoBandwi */ unsigned int ortp_video_bandwidth_estimator_get_trust(OrtpVideoBandwidthEstimator *vbe); -void ortp_video_bandwidth_estimator_process_packet(OrtpVideoBandwidthEstimator *vbe, uint32_t sent_timestamp, const struct timeval *recv_timestamp, int msgsize, bool_t is_last); +void ortp_video_bandwidth_estimator_process_packet(OrtpVideoBandwidthEstimator *vbe, + uint32_t sent_timestamp, + const struct timeval *recv_timestamp, + int msgsize, + bool_t is_last); float ortp_video_bandwidth_estimator_get_estimated_available_bandwidth(OrtpVideoBandwidthEstimator *vbe); diff --git a/src/winrttimer.cpp b/src/winrttimer.cpp index 0c0b03d0..4ac164ef 100644 --- a/src/winrttimer.cpp +++ b/src/winrttimer.cpp @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -19,55 +19,49 @@ */ #include -#include "winrttimer.h" #include "ortp/logging.h" +#include "winrttimer.h" #ifndef ORTP_WINDOWS_DESKTOP #ifdef ORTP_WINDOWS_PHONE -#using +#using < Windows.winmd> #endif using namespace Windows::Foundation; using namespace Windows::System::Threading; -class WinRTTimer -{ +class WinRTTimer { public: WinRTTimer(); ~WinRTTimer(); void run(); + private: - ThreadPoolTimer^ PeriodicTimer; + ThreadPoolTimer ^ PeriodicTimer; HANDLE SleepEvent; ULONGLONG LateTicks; ULONGLONG PosixTimerTime; ULONGLONG OffsetTime; }; - -WinRTTimer::WinRTTimer() - : LateTicks(0), PosixTimerTime(0), OffsetTime(GetTickCount64()) -{ +WinRTTimer::WinRTTimer() : LateTicks(0), PosixTimerTime(0), OffsetTime(GetTickCount64()) { TimeSpan period; period.Duration = TIME_INTERVAL * 10000; SleepEvent = CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS); - PeriodicTimer = ThreadPoolTimer::CreatePeriodicTimer( - ref new TimerElapsedHandler([this](ThreadPoolTimer^ source) - { - if (source == PeriodicTimer) { - PosixTimerTime += TIME_INTERVAL; - } - }), period); + PeriodicTimer = ThreadPoolTimer::CreatePeriodicTimer(ref new TimerElapsedHandler([this](ThreadPoolTimer ^ source) { + if (source == PeriodicTimer) { + PosixTimerTime += TIME_INTERVAL; + } + }), + period); } -WinRTTimer::~WinRTTimer() -{ +WinRTTimer::~WinRTTimer() { PeriodicTimer->Cancel(); } -void WinRTTimer::run() -{ +void WinRTTimer::run() { // If timer have expired while we where out of this method // Try to run after lost time. if (LateTicks > 0) { @@ -88,18 +82,15 @@ void WinRTTimer::run() static WinRTTimer *timer; -void winrt_timer_init(void) -{ +void winrt_timer_init(void) { timer = new WinRTTimer(); } -void winrt_timer_do(void) -{ +void winrt_timer_do(void) { timer->run(); } -void winrt_timer_close(void) -{ +void winrt_timer_close(void) { delete timer; } diff --git a/src/winrttimer.h b/src/winrttimer.h index bf886d41..ce51a6da 100644 --- a/src/winrttimer.h +++ b/src/winrttimer.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -23,13 +23,13 @@ extern "C" { #endif - void winrt_timer_init(void); - void winrt_timer_do(void); - void winrt_timer_close(void); +void winrt_timer_init(void); +void winrt_timer_do(void); +void winrt_timer_close(void); #ifdef __cplusplus }; #endif -#define TIME_INTERVAL 50 -#define TIME_TIMEOUT 100 +#define TIME_INTERVAL 50 +#define TIME_TIMEOUT 100 diff --git a/tester/extension_header_tester.c b/tester/extension_header_tester.c index 0ca36827..4b1c7c89 100644 --- a/tester/extension_header_tester.c +++ b/tester/extension_header_tester.c @@ -17,6 +17,8 @@ * along with this program. If not, see . */ +#include + #include "ortp_tester.h" #include @@ -532,7 +534,8 @@ static void insert_mixer_to_client_into_packet_with_payload_in_bundled_session_u insert_mixer_to_client_into_packet_base(TRUE, TRUE, bundled_session); } -static void insert_frame_marking_into_packet_base(bool_t with_payload, RtpSession *test_session) { +static void insert_frame_marking_into_packet_base(BCTBX_UNUSED(bool_t with_payload), + BCTBX_UNUSED(RtpSession *test_session)) { size_t size; int ret; uint8_t result; diff --git a/tester/fec_tester.cc b/tester/fec_tester.cc index eddb9311..c31aa5ca 100644 --- a/tester/fec_tester.cc +++ b/tester/fec_tester.cc @@ -13,22 +13,22 @@ static FecParameters *newFecParams(int L, int D, int repairWindow) { return params; } /* static void fillEncoder(FecEncoder &encoder) { - for (int i = 0; i < encoder.getSize(); i++) { - Bitstring bs = generateBitstring(160 * i, 150 + i, 'a' + i); - encoder.add(bs); - } + for (int i = 0; i < encoder.getSize(); i++) { + Bitstring bs = generateBitstring(160 * i, 150 + i, 'a' + i); + encoder.add(bs); + } } static mblk_t *new_packet(struct _RtpSession *session, int seqnum, uint32_t timestamp, uint8_t *payload, size_t packet_size) { mblk_t *packet = NULL; - packet = rtp_session_create_packet(session, RTP_FIXED_HEADER_SIZE, payload, packet_size); - rtp_set_seqnumber(packet, seqnum); - rtp_set_timestamp(packet, timestamp); - return packet; + packet = rtp_session_create_packet(session, RTP_FIXED_HEADER_SIZE, payload, packet_size); + rtp_set_seqnumber(packet, seqnum); + rtp_set_timestamp(packet, timestamp); + return packet; }*/ -static mblk_t *newPacketWithLetter(struct _RtpSession *session, int seqnum, uint32_t timestamp, uint8_t car, - size_t packet_size) { +static mblk_t * +newPacketWithLetter(struct _RtpSession *session, int seqnum, uint32_t timestamp, uint8_t car, size_t packet_size) { mblk_t *packet = NULL; packet = rtp_session_create_packet_header(session, packet_size); // reserve packet_size after the header memset(packet->b_wptr, car, packet_size); @@ -49,17 +49,15 @@ static bool_t compare_header_fields(mblk_t *ma, mblk_t *mb) { uint16_t ext = rtp_get_extbit(ma); return (rtp_get_version(ma) == rtp_get_version(mb)) && (rtp_get_padbit(ma) == rtp_get_padbit(mb)) && - (cc == rtp_get_cc(mb)) && (ext == rtp_get_extbit(mb)) && (rtp_get_markbit(ma) == rtp_get_markbit(mb)) && - (rtp_get_payload_type(ma) == rtp_get_payload_type(mb)) && (rtp_get_seqnumber(ma) == rtp_get_seqnumber(mb)) && - (rtp_get_ssrc(ma) == rtp_get_ssrc(ma)); + (cc == rtp_get_cc(mb)) && (ext == rtp_get_extbit(mb)) && (rtp_get_markbit(ma) == rtp_get_markbit(mb)) && + (rtp_get_payload_type(ma) == rtp_get_payload_type(mb)) && (rtp_get_seqnumber(ma) == rtp_get_seqnumber(mb)) && + (rtp_get_ssrc(ma) == rtp_get_ssrc(ma)); } static bool_t compare_csrc_fields(mblk_t *ma, mblk_t *mb) { uint16_t cc = rtp_get_cc(ma); - if (cc != rtp_get_cc(mb)) - return FALSE; + if (cc != rtp_get_cc(mb)) return FALSE; for (uint8_t i = 0; i < cc; i++) { - if (rtp_get_csrc(ma, i) != rtp_get_csrc(mb, i)) - return FALSE; + if (rtp_get_csrc(ma, i) != rtp_get_csrc(mb, i)) return FALSE; } return TRUE; } @@ -73,15 +71,12 @@ static bool_t compare_ext_headers(mblk_t *ma, mblk_t *mb) { if (ext) { - if (ext != rtp_get_extbit(mb)) - return FALSE; + if (ext != rtp_get_extbit(mb)) return FALSE; size_ext_a = rtp_get_extheader(ma, &profile_ext_a, &data_ext_a); size_ext_b = rtp_get_extheader(mb, &profile_ext_b, &data_ext_b); - if (size_ext_a != size_ext_b) - return FALSE; - if (!((profile_ext_a == profile_ext_b) && (memcmp(data_ext_a, data_ext_b, size_ext_a) == 0))) - return FALSE; + if (size_ext_a != size_ext_b) return FALSE; + if (!((profile_ext_a == profile_ext_b) && (memcmp(data_ext_a, data_ext_b, size_ext_a) == 0))) return FALSE; } return TRUE; } @@ -92,24 +87,17 @@ static bool_t compare_payloads(mblk_t *ma, mblk_t *mb) { size_payload_a = rtp_get_payload(ma, &payload_a); size_payload_b = rtp_get_payload(mb, &payload_b); - if (size_payload_a != size_payload_b) - return FALSE; - if (memcmp(payload_a, payload_b, size_payload_a) != 0) - return FALSE; + if (size_payload_a != size_payload_b) return FALSE; + if (memcmp(payload_a, payload_b, size_payload_a) != 0) return FALSE; return TRUE; } static bool_t packets_are_equals(mblk_t *ma, mblk_t *mb) { - if (!compare_sizes(ma, mb)) - return FALSE; - if (!compare_header_fields(ma, mb)) - return FALSE; - if (!compare_csrc_fields(ma, mb)) - return FALSE; - if (!compare_ext_headers(ma, mb)) - return FALSE; - if (!compare_payloads(ma, mb)) - return FALSE; + if (!compare_sizes(ma, mb)) return FALSE; + if (!compare_header_fields(ma, mb)) return FALSE; + if (!compare_csrc_fields(ma, mb)) return FALSE; + if (!compare_ext_headers(ma, mb)) return FALSE; + if (!compare_payloads(ma, mb)) return FALSE; return TRUE; } @@ -127,8 +115,6 @@ static void bitstring_add_test(void) { BC_ASSERT_EQUAL(bsA.getLength(), 150, uint32_t, "%u"); BC_ASSERT_EQUAL(bsB.getLength(), 160, uint32_t, "%u"); - - bsA.add(bsB); uint16_t header = bsA.getHeader(); uint16_t expectedHeader = 0; @@ -138,7 +124,7 @@ static void bitstring_add_test(void) { BC_ASSERT_EQUAL(header, expectedHeader, uint16_t, "%d"); BC_ASSERT_EQUAL(bsA.getLength(), expectedLength, int, "%d"); BC_ASSERT_EQUAL(bsA.getTimestamp(), expectedTs, int, "%d"); - + freemsg(packetA); freemsg(packetB); rtp_session_destroy(session); @@ -219,10 +205,8 @@ static void source_packet_add_payload_test3(void) { pA.addPayload(pB); uint8_t expectedPayload[180] = {0}; for (int i = 0; i < 180; i++) { - if (i < 120) - expectedPayload[i] = 'a' ^ 'b'; - else - expectedPayload[i] = 'a'; + if (i < 120) expectedPayload[i] = 'a' ^ 'b'; + else expectedPayload[i] = 'a'; } size_t sizeA = pA.getPayloadBuffer(&rptr); @@ -260,7 +244,7 @@ static void repair_packet_add_payload1(void) { mblk_t *packetA = newPacketWithLetter(session, 0, 123456, 'a', 150); FecSourcePacket sourceA(packetA); - FecRepairPacket repair(session,session, 0, 5, 1); + FecRepairPacket repair(session, session, 0, 5, 1); repair.addPayload(sourceA); uint8_t *expectedBuffer = NULL; @@ -304,7 +288,7 @@ static void encoder_init1D_test(void) { RtpSession *session = rtp_session_new(RTP_SESSION_SENDRECV); FecParameters *params = newFecParams(10, 0, 200000); FecEncoder cluster(params); - cluster.init(session,session); + cluster.init(session, session); auto rowRepair = cluster.getRowRepair(); auto colRepair = cluster.getColRepair(); @@ -325,7 +309,7 @@ static void encoder_init2D_test(void) { RtpSession *session = rtp_session_new(RTP_SESSION_SENDRECV); FecParameters *params = newFecParams(10, 10, 200000); FecEncoder cluster(params); - cluster.init(session,session); + cluster.init(session, session); auto rowRepair = cluster.getRowRepair(); auto colRepair = cluster.getColRepair(); @@ -371,7 +355,7 @@ static void encoder_add2D_test(void) { RtpSession *session = rtp_session_new(RTP_SESSION_SENDRECV); FecParameters *params = newFecParams(5, 5, 200000); FecEncoder cluster(params); - cluster.init(session,session); + cluster.init(session, session); uint8_t *sourcePayload = NULL; uint8_t *rowRepairPayload = NULL; @@ -406,16 +390,14 @@ static void encoder_areFull_test(void) { RtpSession *session = rtp_session_new(RTP_SESSION_SENDRECV); FecParameters *params = newFecParams(5, 5, 200000); FecEncoder cluster(params); - cluster.init(session,session); + cluster.init(session, session); mblk_t *packet = NULL; for (int i = 0; i < cluster.getSize(); i++) { packet = newPacketWithLetter(session, i, i * 60, 'a' + i, 150 + i); FecSourcePacket source(packet); cluster.add(source); - if (((i % cluster.getColumns()) == (cluster.getColumns()))) - BC_ASSERT_TRUE(cluster.isRowFull()); - if (i >= 20 && i < 25) - BC_ASSERT_TRUE(cluster.isColFull()); + if (((i % cluster.getColumns()) == (cluster.getColumns()))) BC_ASSERT_TRUE(cluster.isRowFull()); + if (i >= 20 && i < 25) BC_ASSERT_TRUE(cluster.isColFull()); freemsg(packet); } BC_ASSERT_TRUE(cluster.isFull()); @@ -429,7 +411,7 @@ static void encoder_fill_test(void) { RtpSession *session = rtp_session_new(RTP_SESSION_SENDRECV); FecParameters *params = newFecParams(5, 3, 200000); FecEncoder encoder(params); - encoder.init(session,session); + encoder.init(session, session); for (int i = 0; i < 15; i++) { @@ -457,7 +439,7 @@ static void encoder_reset(void) { RtpSession *session = rtp_session_new(RTP_SESSION_SENDRECV); FecParameters *params = newFecParams(5, 0, 200000); FecEncoder encoder(params); - encoder.init(session,session); + encoder.init(session, session); mblk_t *expected = encoder.getRowRepairMblk(0); @@ -508,7 +490,7 @@ static void recieve_cluster_repairOne_test(void) { int L = 5; int missing = 1; auto cluster = RecieveCluster(session, 200); - std::shared_ptr repair(new FecRepairPacket(session,session, 0, L, 0)); + std::shared_ptr repair(new FecRepairPacket(session, session, 0, L, 0)); std::vector> base; mblk_t *packet = NULL; @@ -517,8 +499,7 @@ static void recieve_cluster_repairOne_test(void) { std::shared_ptr source(new FecSourcePacket(packet)); base.push_back(source); repair->add(*source); - if (i != missing) - cluster.add(i, source); + if (i != missing) cluster.add(i, source); freemsg(packet); } cluster.repairOne(*repair); @@ -543,8 +524,7 @@ static void recieve_cluster_repair1DNonInterleaved_test(void) { std::shared_ptr source(new FecSourcePacket(packet)); base.push_back(source); repair->add(*source); - if (i != missing) - cluster.add(i, source); + if (i != missing) cluster.add(i, source); freemsg(packet); } cluster.add(repair); @@ -573,8 +553,7 @@ static void recieve_cluster_repair1DInterleaved_test(void) { std::shared_ptr source(new FecSourcePacket(packet)); base.push_back(source); repair->add(*source); - if (i != missing) - cluster.add(i, source); + if (i != missing) cluster.add(i, source); freemsg(packet); } cluster.add(repair); @@ -592,7 +571,7 @@ static void encode_decode_test(void) { RtpSession *session = rtp_session_new(RTP_SESSION_SENDRECV); FecParameters *params = newFecParams(5, 5, 200000); FecEncoder encoder(params); - encoder.init(session,session); + encoder.init(session, session); RecieveCluster cluster(session, 500); mblk_t *packet = NULL; int missing = 12; @@ -637,11 +616,11 @@ static void encode_decode_2D_test(void) { RtpSession *session = rtp_session_new(RTP_SESSION_SENDRECV); FecParameters *params = newFecParams(5, 5, 200000); FecEncoder encoder(params); - encoder.init(session,session); + encoder.init(session, session); RecieveCluster cluster(session, 500); mblk_t *packet = NULL; - int missing[25] = {1,0,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,1,1,1}; - std::vector > missed; + int missing[25] = {1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1}; + std::vector> missed; for (int i = 0; i < 25; i++) { packet = newPacketWithLetter(session, i, i * 5, ('a' + i) % 26, 1000); @@ -668,21 +647,19 @@ static void encode_decode_2D_test(void) { } freemsg(packet); } - for(int i = 0; i<25; i++){ - - if(!missing[i]) continue; + for (int i = 0; i < 25; i++) { + + if (!missing[i]) continue; auto find = cluster.getSourcePacket(i); BC_ASSERT_PTR_NULL(find); - } cluster.repair2D(); int miss = 0; - for(int i = 0; i<25; i++){ - if(!missing[i]) continue; + for (int i = 0; i < 25; i++) { + if (!missing[i]) continue; auto find = cluster.getSourcePacket(i); BC_ASSERT_PTR_NOT_NULL(find); - if(find) - BC_ASSERT_TRUE(packets_are_equals(missed[miss]->getPacket(), find->getPacket())); + if (find) BC_ASSERT_TRUE(packets_are_equals(missed[miss]->getPacket(), find->getPacket())); miss++; } rtp_session_destroy(session); @@ -691,39 +668,39 @@ static void encode_decode_2D_test(void) { static test_t tests[] = { - TEST_NO_TAG("bitstring add", bitstring_add_test), - TEST_NO_TAG("source_packet_get_payload", source_packet_get_payload_test), - TEST_NO_TAG("source_packet_add_payload same size", source_packet_add_payload_test1), - TEST_NO_TAG("source_packet_add_payload bigger", source_packet_add_payload_test2), - TEST_NO_TAG("source_packet_add_payload smaller", source_packet_add_payload_test3), - TEST_NO_TAG("repair_packet_bitstring", repair_packet_bitstring_test), - TEST_NO_TAG("repair_packet_add Payload", repair_packet_add_payload1), - TEST_NO_TAG("repair packet seqnum list non interleaved", repair_packet_seqnumListNonInterleaved_test), - TEST_NO_TAG("repair packet seqnum list interleaved", repair_packet_seqnumListInterleaved_test), - - TEST_NO_TAG("encoder init1D", encoder_init1D_test), - TEST_NO_TAG("encoder init2D", encoder_init2D_test), - TEST_NO_TAG("encoder add1D", encoder_add1D_test), - TEST_NO_TAG("encoder add2D", encoder_add2D_test), - TEST_NO_TAG("encoder fill", encoder_fill_test), - - TEST_NO_TAG("encoder reset", encoder_reset), - TEST_NO_TAG("encoder are full", encoder_areFull_test), - TEST_NO_TAG("recieve cluster add", recieve_cluster_add_test), - - TEST_NO_TAG("recieve cluster repair one", recieve_cluster_repairOne_test), - TEST_NO_TAG("recieve cluster repair 1D non interleaved", recieve_cluster_repair1DNonInterleaved_test), - TEST_NO_TAG("recieve cluster repair 1D interleaved", recieve_cluster_repair1DInterleaved_test), - TEST_NO_TAG("encode decode", encode_decode_test), - TEST_NO_TAG("encode decode 2D", encode_decode_2D_test), + TEST_NO_TAG("bitstring add", bitstring_add_test), + TEST_NO_TAG("source_packet_get_payload", source_packet_get_payload_test), + TEST_NO_TAG("source_packet_add_payload same size", source_packet_add_payload_test1), + TEST_NO_TAG("source_packet_add_payload bigger", source_packet_add_payload_test2), + TEST_NO_TAG("source_packet_add_payload smaller", source_packet_add_payload_test3), + TEST_NO_TAG("repair_packet_bitstring", repair_packet_bitstring_test), + TEST_NO_TAG("repair_packet_add Payload", repair_packet_add_payload1), + TEST_NO_TAG("repair packet seqnum list non interleaved", repair_packet_seqnumListNonInterleaved_test), + TEST_NO_TAG("repair packet seqnum list interleaved", repair_packet_seqnumListInterleaved_test), + + TEST_NO_TAG("encoder init1D", encoder_init1D_test), + TEST_NO_TAG("encoder init2D", encoder_init2D_test), + TEST_NO_TAG("encoder add1D", encoder_add1D_test), + TEST_NO_TAG("encoder add2D", encoder_add2D_test), + TEST_NO_TAG("encoder fill", encoder_fill_test), + + TEST_NO_TAG("encoder reset", encoder_reset), + TEST_NO_TAG("encoder are full", encoder_areFull_test), + TEST_NO_TAG("recieve cluster add", recieve_cluster_add_test), + + TEST_NO_TAG("recieve cluster repair one", recieve_cluster_repairOne_test), + TEST_NO_TAG("recieve cluster repair 1D non interleaved", recieve_cluster_repair1DNonInterleaved_test), + TEST_NO_TAG("recieve cluster repair 1D interleaved", recieve_cluster_repair1DInterleaved_test), + TEST_NO_TAG("encode decode", encode_decode_test), + TEST_NO_TAG("encode decode 2D", encode_decode_2D_test), }; test_suite_t fec_test_suite = { - "FEC", // Name of test suite - NULL, // Before all callback - NULL, // After all callback - NULL, // Before each callback - NULL, // After each callback - sizeof(tests) / sizeof(tests[0]), // Size of test table - tests // Table of test suite + "FEC", // Name of test suite + NULL, // Before all callback + NULL, // After all callback + NULL, // Before each callback + NULL, // After each callback + sizeof(tests) / sizeof(tests[0]), // Size of test table + tests // Table of test suite }; diff --git a/tester/ortp_tester.c b/tester/ortp_tester.c index dfa07f88..1d0c1298 100644 --- a/tester/ortp_tester.c +++ b/tester/ortp_tester.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -18,9 +18,11 @@ * along with this program. If not, see . */ +#include + #include "ortp_tester.h" -static FILE * log_file = NULL; +static FILE *log_file = NULL; static void log_handler(int lev, const char *fmt, va_list args) { #ifdef _WIN32 @@ -69,13 +71,13 @@ int ortp_tester_set_log_file(const char *filename) { return 0; } -int silent_arg_func(const char *arg) { +int silent_arg_func(BCTBX_UNUSED(const char *arg)) { bctbx_set_log_level("ortp", BCTBX_LOG_ERROR); bctbx_set_log_level(BCTBX_LOG_DOMAIN, BCTBX_LOG_ERROR); return 0; } -int verbose_arg_func(const char *arg) { +int verbose_arg_func(BCTBX_UNUSED(const char *arg)) { bctbx_set_log_level("ortp", BCTBX_LOG_DEBUG); bctbx_set_log_level(BCTBX_LOG_DOMAIN, BCTBX_LOG_DEBUG); return 0; @@ -102,7 +104,6 @@ void ortp_tester_uninit() { bc_tester_uninit(); } - #if defined(_WIN32) && !defined(MS2_WINDOWS_DESKTOP) #define BUILD_ENTRY_POINT 0 #else @@ -110,7 +111,7 @@ void ortp_tester_uninit() { #endif #if BUILD_ENTRY_POINT -int main (int argc, char *argv[]) { +int main(int argc, char *argv[]) { int i, ret; silent_arg_func(NULL); diff --git a/tester/ortp_tester.h b/tester/ortp_tester.h index aefe12bb..4c207c3f 100644 --- a/tester/ortp_tester.h +++ b/tester/ortp_tester.h @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify diff --git a/tester/rtp_tester.c b/tester/rtp_tester.c index 97d05f73..c523e2b9 100644 --- a/tester/rtp_tester.c +++ b/tester/rtp_tester.c @@ -1,7 +1,7 @@ /* * Copyright (c) 2010-2022 Belledonne Communications SARL. * - * This file is part of oRTP + * This file is part of oRTP * (see https://gitlab.linphone.org/BC/public/ortp). * * This program is free software: you can redistribute it and/or modify @@ -81,18 +81,18 @@ static void send_packets_through_tranfer_session(void) { rtcp_port = rtp_session_get_local_rtcp_port(session); rtp_session_set_remote_addr_full(transfer_session, "127.0.0.1", rtp_port, "127.0.0.1", rtcp_port); - while(((len = fread(buffer, 1, 160, infile)) > 0) && !error) { + while (((len = fread(buffer, 1, 160, infile)) > 0) && !error) { mblk_t *transfered_packet; mblk_t *received_packet; int size = 0; // Send a packet through the "normal" session and retrieve it with the transfer session - mblk_t *sent_packet = rtp_session_create_packet_header(session, len); // make a non fragmented packet, so ask for len bytes allocated after the header. - // This is needed to be able to compare directly the received packet with the sent one + mblk_t *sent_packet = rtp_session_create_packet_header( + session, len); // make a non fragmented packet, so ask for len bytes allocated after the header. + // This is needed to be able to compare directly the received packet with the sent one memcpy(sent_packet->b_wptr, (uint8_t *)buffer, len); sent_packet->b_wptr += len; - size = rtp_session_sendm_with_ts(session, copymsg(sent_packet), user_ts); BC_ASSERT_GREATER(size, 0, int, "%d"); @@ -100,17 +100,23 @@ static void send_packets_through_tranfer_session(void) { if (!BC_ASSERT_PTR_NOT_NULL(transfered_packet)) { error = TRUE; } else { - // We cannot compare bytes by bytes here as sent_packet has been modified by rtp_session_sendm_with_ts before sending - // So we check the parts that this function didn't change which is everything but timestamp + // We cannot compare bytes by bytes here as sent_packet has been modified by rtp_session_sendm_with_ts + // before sending So we check the parts that this function didn't change which is everything but timestamp BC_ASSERT_EQUAL(rtp_get_version(transfered_packet), rtp_get_version(sent_packet), uint16_t, "%hu"); BC_ASSERT_EQUAL(rtp_get_padbit(transfered_packet), rtp_get_padbit(sent_packet), uint16_t, "%hu"); BC_ASSERT_EQUAL(rtp_get_markbit(transfered_packet), rtp_get_markbit(sent_packet), uint16_t, "%hu"); BC_ASSERT_EQUAL(rtp_get_extbit(transfered_packet), rtp_get_extbit(sent_packet), uint16_t, "%hu"); - BC_ASSERT_TRUE(rtp_get_seqnumber(transfered_packet) == rtp_get_seqnumber(sent_packet)); // BC_ASSERT_EQUAL here doesn't want to compile on some platforms - BC_ASSERT_EQUAL(rtp_get_payload_type(transfered_packet), rtp_get_payload_type(sent_packet), uint16_t, "%hu"); + BC_ASSERT_TRUE( + rtp_get_seqnumber(transfered_packet) == + rtp_get_seqnumber(sent_packet)); // BC_ASSERT_EQUAL here doesn't want to compile on some platforms + BC_ASSERT_EQUAL(rtp_get_payload_type(transfered_packet), rtp_get_payload_type(sent_packet), uint16_t, + "%hu"); BC_ASSERT_TRUE(rtp_get_ssrc(transfered_packet) == rtp_get_ssrc(sent_packet)); // Same here BC_ASSERT_EQUAL(rtp_get_cc(transfered_packet), rtp_get_cc(sent_packet), uint16_t, "%hu"); - BC_ASSERT_EQUAL(memcmp(transfered_packet->b_rptr + RTP_FIXED_HEADER_SIZE, sent_packet->b_rptr + RTP_FIXED_HEADER_SIZE, msgdsize(transfered_packet) - RTP_FIXED_HEADER_SIZE), 0, int, "%d"); + BC_ASSERT_EQUAL(memcmp(transfered_packet->b_rptr + RTP_FIXED_HEADER_SIZE, + sent_packet->b_rptr + RTP_FIXED_HEADER_SIZE, + msgdsize(transfered_packet) - RTP_FIXED_HEADER_SIZE), + 0, int, "%d"); // Send it again via the transfer session and retrieve it with the "normal" session size = rtp_session_sendm_with_ts(transfer_session, copymsg(transfered_packet), user_ts); @@ -120,8 +126,10 @@ static void send_packets_through_tranfer_session(void) { if (!BC_ASSERT_PTR_NOT_NULL(received_packet)) { error = TRUE; } else { - // Check that the packet received is the same as the transfered one as the "transfer" session shouldn't modify it's content - BC_ASSERT_EQUAL(memcmp(received_packet->b_rptr, transfered_packet->b_rptr, msgdsize(received_packet)), 0, int, "%d"); + // Check that the packet received is the same as the transfered one as the "transfer" session shouldn't + // modify it's content + BC_ASSERT_EQUAL(memcmp(received_packet->b_rptr, transfered_packet->b_rptr, msgdsize(received_packet)), + 0, int, "%d"); freemsg(received_packet); } @@ -141,16 +149,14 @@ static void send_packets_through_tranfer_session(void) { rtp_session_destroy(transfer_session); } -static test_t tests[] = { - TEST_NO_TAG("Send packets through a transfer session", send_packets_through_tranfer_session) -}; +static test_t tests[] = {TEST_NO_TAG("Send packets through a transfer session", send_packets_through_tranfer_session)}; test_suite_t rtp_test_suite = { - "Rtp", // Name of test suite - tester_before_all, // Before all callback - tester_after_all, // After all callback - NULL, // Before each callback - NULL, // After each callback - sizeof(tests) / sizeof(tests[0]), // Size of test table - tests // Table of test suite + "Rtp", // Name of test suite + tester_before_all, // Before all callback + tester_after_all, // After all callback + NULL, // Before each callback + NULL, // After each callback + sizeof(tests) / sizeof(tests[0]), // Size of test table + tests // Table of test suite };