From 360eba2c6879f6ecbef95a3829f7e2f2ab46fdf2 Mon Sep 17 00:00:00 2001 From: zqsong Date: Tue, 30 Jul 2019 19:26:38 +0800 Subject: [PATCH 01/30] =?UTF-8?q?MP4=E5=BD=95=E5=88=B6=E6=B7=BB=E5=8A=A0H2?= =?UTF-8?q?65=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CMakeLists.txt | 22 + src/Extension/Factory.cpp | 8 +- src/Extension/SPSParser.c | 1180 ++++++++++++++++++++++++++++++++++++ src/Extension/SPSParser.h | 253 ++++++++ src/MediaFile/Mp4Maker.cpp | 317 ++++++++-- src/MediaFile/Mp4Maker.h | 35 +- tests/test_server.cpp | 23 +- 7 files changed, 1773 insertions(+), 65 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index eec4257c..84e7383a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -36,6 +36,7 @@ set(ENABLE_MYSQL true) set(ENABLE_MP4V2 true) set(ENABLE_FAAC true) set(ENABLE_X264 true) +set(MP4_H265RECORD true) #添加两个静态库 if(ENABLE_HLS) @@ -47,6 +48,12 @@ else() set(LINK_LIB_LIST zlmediakit zltoolkit) endif() +if(MP4_H265RECORD) + message(STATUS "MP4_H265RECORD defined") + add_definitions(-DMP4_H265RECORD) + set(MediaServer_Root ${CMAKE_SOURCE_DIR}/3rdpart/media-server) + list(APPEND LINK_LIB_LIST mov flv) +endif() #查找openssl是否安装 find_package(OpenSSL QUIET) if (OPENSSL_FOUND AND ENABLE_OPENSSL) @@ -111,6 +118,21 @@ if(ENABLE_HLS) endif(WIN32) endif() +if(MP4_H265RECORD) + aux_source_directory(${MediaServer_Root}/libmov/include src_mov) + aux_source_directory(${MediaServer_Root}/libmov/source src_mov) + include_directories(${MediaServer_Root}/libmov/include) + aux_source_directory(${MediaServer_Root}/libflv/include src_flv) + aux_source_directory(${MediaServer_Root}/libflv/source src_flv) + include_directories(${MediaServer_Root}/libflv/include) + add_library(mov STATIC ${src_mov}) + add_library(flv STATIC ${src_flv}) + if(WIN32) + set_target_properties(mov flv PROPERTIES COMPILE_FLAGS ${VS_FALGS} ) + endif(WIN32) +endif() + + if (WIN32) list(APPEND LINK_LIB_LIST WS2_32 Iphlpapi shlwapi) set_target_properties(zltoolkit PROPERTIES COMPILE_FLAGS ${VS_FALGS} ) diff --git a/src/Extension/Factory.cpp b/src/Extension/Factory.cpp index ced72b6e..afc278a7 100644 --- a/src/Extension/Factory.cpp +++ b/src/Extension/Factory.cpp @@ -76,8 +76,14 @@ Track::Ptr Factory::getTrackBySdp(const SdpTrack::Ptr &track) { if (strcasecmp(track->_codec.data(), "h265") == 0) { //a=fmtp:96 sprop-sps=QgEBAWAAAAMAsAAAAwAAAwBdoAKAgC0WNrkky/AIAAADAAgAAAMBlQg=; sprop-pps=RAHA8vA8kAA= - int pt; + int pt, id; char sprop_vps[128] = {0},sprop_sps[128] = {0},sprop_pps[128] = {0}; + if (5 == sscanf(track->_fmtp.data(), "%d profile-id=%d; sprop-sps=%127[^;]; sprop-pps=%127[^;]; sprop-vps=%127[^;]", &pt, &id, sprop_sps,sprop_pps, sprop_vps)) { + auto vps = decodeBase64(sprop_vps); + auto sps = decodeBase64(sprop_sps); + auto pps = decodeBase64(sprop_pps); + return std::make_shared(vps,sps,pps,0,0,0); + } if (4 == sscanf(track->_fmtp.data(), "%d sprop-vps=%127[^;]; sprop-sps=%127[^;]; sprop-pps=%127[^;]", &pt, sprop_vps,sprop_sps, sprop_pps)) { auto vps = decodeBase64(sprop_vps); auto sps = decodeBase64(sprop_sps); diff --git a/src/Extension/SPSParser.c b/src/Extension/SPSParser.c index 13898161..375af389 100644 --- a/src/Extension/SPSParser.c +++ b/src/Extension/SPSParser.c @@ -23,6 +23,13 @@ #define INT_MAX 65535 #endif //INT_MAX +#ifndef FFMIN +#define FFMIN(a,b) ((a) > (b) ? (b) : (a)) +#endif +#ifndef FFMAX +#define FFMAX(a,b) ((a) > (b) ? (a) : (b)) +#endif + /* report level */ #define RPT_ERR (1) // error, system error #define RPT_WRN (2) // warning, maybe wrong, maybe OK @@ -122,6 +129,108 @@ const uint8_t g_au8FfZigzagDirect[64] = { }; +static const uint8_t hevc_sub_width_c[] = { + 1, 2, 2, 1 +}; + +static const uint8_t hevc_sub_height_c[] = { + 1, 2, 1, 1 +}; + +static const uint8_t default_scaling_list_intra[] = { + 16, 16, 16, 16, 17, 18, 21, 24, + 16, 16, 16, 16, 17, 19, 22, 25, + 16, 16, 17, 18, 20, 22, 25, 29, + 16, 16, 18, 21, 24, 27, 31, 36, + 17, 17, 20, 24, 30, 35, 41, 47, + 18, 19, 22, 27, 35, 44, 54, 65, + 21, 22, 25, 31, 41, 54, 70, 88, + 24, 25, 29, 36, 47, 65, 88, 115 +}; + +static const uint8_t default_scaling_list_inter[] = { + 16, 16, 16, 16, 17, 18, 20, 24, + 16, 16, 16, 17, 18, 20, 24, 25, + 16, 16, 17, 18, 20, 24, 25, 28, + 16, 17, 18, 20, 24, 25, 28, 33, + 17, 18, 20, 24, 25, 28, 33, 41, + 18, 20, 24, 25, 28, 33, 41, 54, + 20, 24, 25, 28, 33, 41, 54, 71, + 24, 25, 28, 33, 41, 54, 71, 91 +}; + + +const uint8_t ff_hevc_diag_scan4x4_x[16] = { + 0, 0, 1, 0, + 1, 2, 0, 1, + 2, 3, 1, 2, + 3, 2, 3, 3, +}; + +const uint8_t ff_hevc_diag_scan4x4_y[16] = { + 0, 1, 0, 2, + 1, 0, 3, 2, + 1, 0, 3, 2, + 1, 3, 2, 3, +}; + +const uint8_t ff_hevc_diag_scan8x8_x[64] = { + 0, 0, 1, 0, + 1, 2, 0, 1, + 2, 3, 0, 1, + 2, 3, 4, 0, + 1, 2, 3, 4, + 5, 0, 1, 2, + 3, 4, 5, 6, + 0, 1, 2, 3, + 4, 5, 6, 7, + 1, 2, 3, 4, + 5, 6, 7, 2, + 3, 4, 5, 6, + 7, 3, 4, 5, + 6, 7, 4, 5, + 6, 7, 5, 6, + 7, 6, 7, 7, +}; + +const uint8_t ff_hevc_diag_scan8x8_y[64] = { + 0, 1, 0, 2, + 1, 0, 3, 2, + 1, 0, 4, 3, + 2, 1, 0, 5, + 4, 3, 2, 1, + 0, 6, 5, 4, + 3, 2, 1, 0, + 7, 6, 5, 4, + 3, 2, 1, 0, + 7, 6, 5, 4, + 3, 2, 1, 7, + 6, 5, 4, 3, + 2, 7, 6, 5, + 4, 3, 7, 6, + 5, 4, 7, 6, + 5, 7, 6, 7, +}; + +static const T_AVRational vui_sar[] = { + { 0, 1 }, + { 1, 1 }, + { 12, 11 }, + { 10, 11 }, + { 16, 11 }, + { 40, 33 }, + { 24, 11 }, + { 20, 11 }, + { 32, 11 }, + { 80, 33 }, + { 18, 11 }, + { 15, 11 }, + { 64, 33 }, + { 160, 99 }, + { 4, 3 }, + { 3, 2 }, + { 2, 1 }, +}; static inline int getBitsLeft(void *pvHandle) { @@ -253,6 +362,87 @@ exit: } +/** + * Show 1-25 bits. + */ +static inline unsigned int showBits(void *pvHandle, int iN) +{ + T_GetBitContext *ptPtr = (T_GetBitContext *)pvHandle; + uint8_t au8Temp[5] = {0}; + uint8_t *pu8CurChar = NULL; + uint8_t u8Nbyte; + uint8_t u8Shift; + uint32_t u32Result = 0; + int iRet = 0; + int iResoLen = 0; + + if(NULL == ptPtr) + { + RPT(RPT_ERR, "NULL pointer"); + iRet = -1; + goto exit; + } + + if(iN > MAX_LEN) + { + iN = MAX_LEN; + } + + iResoLen = getBitsLeft(ptPtr); + if(iResoLen < iN) + { + iRet = -1; + goto exit; + } + + + if((ptPtr->iBitPos + iN) > ptPtr->iTotalBit) + { + iN = ptPtr->iTotalBit- ptPtr->iBitPos; + } + + pu8CurChar = ptPtr->pu8Buf+ (ptPtr->iBitPos>>3); + u8Nbyte = (ptPtr->iCurBitPos + iN + 7) >> 3; + u8Shift = (8 - (ptPtr->iCurBitPos + iN))& 0x07; + + if(iN == MAX_LEN) + { + RPT(RPT_DBG, "12(ptPtr->iBitPos(:%d) + iN(:%d)) > ptPtr->iTotalBit(:%d)!!! ",\ + ptPtr->iBitPos, iN, ptPtr->iTotalBit); + RPT(RPT_DBG, "0x%x 0x%x 0x%x 0x%x", (*pu8CurChar), *(pu8CurChar+1),*(pu8CurChar+2),*(pu8CurChar+3)); + } + + memcpy(&au8Temp[5-u8Nbyte], pu8CurChar, u8Nbyte); + iRet = (uint32_t)au8Temp[0] << 24; + iRet = iRet << 8; + iRet = ((uint32_t)au8Temp[1]<<24)|((uint32_t)au8Temp[2] << 16)\ + |((uint32_t)au8Temp[3] << 8)|au8Temp[4]; + + iRet = (iRet >> u8Shift) & (((uint64_t)1<iBitPos += iN; +// ptPtr->iCurBitPos = ptPtr->iBitPos & 0x7; + +exit: + return u32Result; +} + + + +/** + * Show 0-32 bits. + */ +static inline unsigned int showBitsLong(void *pvHandle, int iN) +{ + T_GetBitContext *ptPtr = (T_GetBitContext *)pvHandle; + + if (iN <= 32) { + return showBits(ptPtr, iN); + } +} + + /** * @brief Function parseCodenum() Ö¸Êý¸çÂײ¼±àÂë½âÎö£¬²Î¿¼h264±ê×¼µÚ9½Ú @@ -938,6 +1128,967 @@ exit: return iRet; } + +static int decodeProfileTierLevel(T_GetBitContext *pvBuf, T_PTLCommon *ptl) +{ + int i; + + if (getBitsLeft(pvBuf) < 2+1+5 + 32 + 4 + 16 + 16 + 12) + return -1; + + ptl->profile_space = getBits(pvBuf, 2); + ptl->tier_flag = getOneBit(pvBuf); + ptl->profile_idc = getBits(pvBuf, 5); + if (ptl->profile_idc == T_PROFILE_HEVC_MAIN) + RPT(RPT_DBG, "Main profile bitstream\n"); + else if (ptl->profile_idc == T_PROFILE_HEVC_MAIN_10) + RPT(RPT_DBG, "Main 10 profile bitstream\n"); + else if (ptl->profile_idc == T_PROFILE_HEVC_MAIN_STILL_PICTURE) + RPT(RPT_DBG, "Main Still Picture profile bitstream\n"); + else if (ptl->profile_idc == T_PROFILE_HEVC_REXT) + RPT(RPT_DBG, "Range Extension profile bitstream\n"); + else + RPT(RPT_WRN, "Unknown HEVC profile: %d\n", ptl->profile_idc); + + for (i = 0; i < 32; i++) { + ptl->profile_compatibility_flag[i] = getOneBit(pvBuf); + + if (ptl->profile_idc == 0 && i > 0 && ptl->profile_compatibility_flag[i]) + ptl->profile_idc = i; + } + ptl->progressive_source_flag = getOneBit(pvBuf); + ptl->interlaced_source_flag = getOneBit(pvBuf); + ptl->non_packed_constraint_flag = getOneBit(pvBuf); + ptl->frame_only_constraint_flag = getOneBit(pvBuf); + + getBits(pvBuf, 16); // XXX_reserved_zero_44bits[0..15] + getBits(pvBuf, 16); // XXX_reserved_zero_44bits[16..31] + getBits(pvBuf, 12); // XXX_reserved_zero_44bits[32..43] + + return 0; +} + + +static int parsePtl(T_GetBitContext *pvBuf, T_PTL *ptl, int max_num_sub_layers) +{ + int i; + if (decodeProfileTierLevel(pvBuf, &ptl->general_ptl) < 0 || + getBitsLeft(pvBuf) < 8 + (8*2 * (max_num_sub_layers - 1 > 0))) { + RPT(RPT_ERR, "PTL information too short\n"); + return -1; + } + + ptl->general_ptl.level_idc = getBits(pvBuf, 8); + + for (i = 0; i < max_num_sub_layers - 1; i++) { + ptl->sub_layer_profile_present_flag[i] = getOneBit(pvBuf); + ptl->sub_layer_level_present_flag[i] = getOneBit(pvBuf); + } + + if (max_num_sub_layers - 1> 0) + for (i = max_num_sub_layers - 1; i < 8; i++) + getBits(pvBuf, 2); // reserved_zero_2bits[i] + for (i = 0; i < max_num_sub_layers - 1; i++) { + if (ptl->sub_layer_profile_present_flag[i] && + decodeProfileTierLevel(pvBuf, &ptl->sub_layer_ptl[i]) < 0) { + RPT(RPT_ERR, + "PTL information for sublayer %i too short\n", i); + return -1; + } + if (ptl->sub_layer_level_present_flag[i]) { + if (getBitsLeft(pvBuf) < 8) { + RPT(RPT_ERR, + "Not enough data for sublayer %i level_idc\n", i); + return -1; + } else + ptl->sub_layer_ptl[i].level_idc = getBits(pvBuf, 8); + } + } + + return 0; +} + + +static void setDefaultScalingListData(T_ScalingList *sl) +{ + int matrixId; + + for (matrixId = 0; matrixId < 6; matrixId++) { + // 4x4 default is 16 + memset(sl->sl[0][matrixId], 16, 16); + sl->sl_dc[0][matrixId] = 16; // default for 16x16 + sl->sl_dc[1][matrixId] = 16; // default for 32x32 + } + memcpy(sl->sl[1][0], default_scaling_list_intra, 64); + memcpy(sl->sl[1][1], default_scaling_list_intra, 64); + memcpy(sl->sl[1][2], default_scaling_list_intra, 64); + memcpy(sl->sl[1][3], default_scaling_list_inter, 64); + memcpy(sl->sl[1][4], default_scaling_list_inter, 64); + memcpy(sl->sl[1][5], default_scaling_list_inter, 64); + memcpy(sl->sl[2][0], default_scaling_list_intra, 64); + memcpy(sl->sl[2][1], default_scaling_list_intra, 64); + memcpy(sl->sl[2][2], default_scaling_list_intra, 64); + memcpy(sl->sl[2][3], default_scaling_list_inter, 64); + memcpy(sl->sl[2][4], default_scaling_list_inter, 64); + memcpy(sl->sl[2][5], default_scaling_list_inter, 64); + memcpy(sl->sl[3][0], default_scaling_list_intra, 64); + memcpy(sl->sl[3][1], default_scaling_list_intra, 64); + memcpy(sl->sl[3][2], default_scaling_list_intra, 64); + memcpy(sl->sl[3][3], default_scaling_list_inter, 64); + memcpy(sl->sl[3][4], default_scaling_list_inter, 64); + memcpy(sl->sl[3][5], default_scaling_list_inter, 64); +} + +static int scalingListData(T_GetBitContext *pvBuf, T_ScalingList *sl, T_HEVCSPS *sps) +{ + uint8_t scaling_list_pred_mode_flag; + int32_t scaling_list_dc_coef[2][6]; + int size_id, matrix_id, pos; + int i; + + for (size_id = 0; size_id < 4; size_id++) + for (matrix_id = 0; matrix_id < 6; matrix_id += ((size_id == 3) ? 3 : 1)) { + scaling_list_pred_mode_flag = getOneBit(pvBuf); + if (!scaling_list_pred_mode_flag) { + unsigned int delta = parseUe(pvBuf); + /* Only need to handle non-zero delta. Zero means default, + * which should already be in the arrays. */ + if (delta) { + // Copy from previous array. + delta *= (size_id == 3) ? 3 : 1; + if (matrix_id < delta) { + RPT(RPT_ERR, + "Invalid delta in scaling list data: %d.\n", delta); + return -1; + } + + memcpy(sl->sl[size_id][matrix_id], + sl->sl[size_id][matrix_id - delta], + size_id > 0 ? 64 : 16); + if (size_id > 1) + sl->sl_dc[size_id - 2][matrix_id] = sl->sl_dc[size_id - 2][matrix_id - delta]; + } + } else { + int next_coef, coef_num; + int32_t scaling_list_delta_coef; + + next_coef = 8; + coef_num = FFMIN(64, 1 << (4 + (size_id << 1))); + if (size_id > 1) { + scaling_list_dc_coef[size_id - 2][matrix_id] = parseSe(pvBuf) + 8; + next_coef = scaling_list_dc_coef[size_id - 2][matrix_id]; + sl->sl_dc[size_id - 2][matrix_id] = next_coef; + } + for (i = 0; i < coef_num; i++) { + if (size_id == 0) + pos = 4 * ff_hevc_diag_scan4x4_y[i] + + ff_hevc_diag_scan4x4_x[i]; + else + pos = 8 * ff_hevc_diag_scan8x8_y[i] + + ff_hevc_diag_scan8x8_x[i]; + + scaling_list_delta_coef = parseSe(pvBuf); + next_coef = (next_coef + 256U + scaling_list_delta_coef) % 256; + sl->sl[size_id][matrix_id][pos] = next_coef; + } + } + } + + if (sps->chroma_format_idc == 3) { + for (i = 0; i < 64; i++) { + sl->sl[3][1][i] = sl->sl[2][1][i]; + sl->sl[3][2][i] = sl->sl[2][2][i]; + sl->sl[3][4][i] = sl->sl[2][4][i]; + sl->sl[3][5][i] = sl->sl[2][5][i]; + } + sl->sl_dc[1][1] = sl->sl_dc[0][1]; + sl->sl_dc[1][2] = sl->sl_dc[0][2]; + sl->sl_dc[1][4] = sl->sl_dc[0][4]; + sl->sl_dc[1][5] = sl->sl_dc[0][5]; + } + + + return 0; +} + +int hevcDecodeShortTermRps(T_GetBitContext *pvBuf, + T_ShortTermRPS *rps, const T_HEVCSPS *sps, int is_slice_header) +{ + uint8_t rps_predict = 0; + int delta_poc; + int k0 = 0; + int k1 = 0; + int k = 0; + int i; + + if (rps != sps->st_rps && sps->nb_st_rps) + rps_predict = getOneBit(pvBuf); + + if (rps_predict) { + const T_ShortTermRPS *rps_ridx; + int delta_rps; + unsigned abs_delta_rps; + uint8_t use_delta_flag = 0; + uint8_t delta_rps_sign; + + if (is_slice_header) { + unsigned int delta_idx = parseUe(pvBuf) + 1; + if (delta_idx > sps->nb_st_rps) { + RPT(RPT_ERR, + "Invalid value of delta_idx in slice header RPS: %d > %d.\n", + delta_idx, sps->nb_st_rps); + return -1; + } + rps_ridx = &sps->st_rps[sps->nb_st_rps - delta_idx]; + rps->rps_idx_num_delta_pocs = rps_ridx->num_delta_pocs; + } else + rps_ridx = &sps->st_rps[rps - sps->st_rps - 1]; + + delta_rps_sign = getOneBit(pvBuf); + abs_delta_rps = parseUe(pvBuf) + 1; + if (abs_delta_rps < 1 || abs_delta_rps > 32768) { + RPT(RPT_ERR, + "Invalid value of abs_delta_rps: %d\n", + abs_delta_rps); + return -1; + } + delta_rps = (1 - (delta_rps_sign << 1)) * abs_delta_rps; + for (i = 0; i <= rps_ridx->num_delta_pocs; i++) { + int used = rps->used[k] = getOneBit(pvBuf); + + if (!used) + use_delta_flag = getOneBit(pvBuf); + + if (used || use_delta_flag) { + if (i < rps_ridx->num_delta_pocs) + delta_poc = delta_rps + rps_ridx->delta_poc[i]; + else + delta_poc = delta_rps; + rps->delta_poc[k] = delta_poc; + if (delta_poc < 0) + k0++; + else + k1++; + k++; + } + } + + if (k >= FF_ARRAY_ELEMS(rps->used)) { + RPT(RPT_ERR, + "Invalid num_delta_pocs: %d\n", k); + return -1; + } + + rps->num_delta_pocs = k; + rps->num_negative_pics = k0; + // sort in increasing order (smallest first) + if (rps->num_delta_pocs != 0) { + int used, tmp; + for (i = 1; i < rps->num_delta_pocs; i++) { + delta_poc = rps->delta_poc[i]; + used = rps->used[i]; + for (k = i - 1; k >= 0; k--) { + tmp = rps->delta_poc[k]; + if (delta_poc < tmp) { + rps->delta_poc[k + 1] = tmp; + rps->used[k + 1] = rps->used[k]; + rps->delta_poc[k] = delta_poc; + rps->used[k] = used; + } + } + } + } + if ((rps->num_negative_pics >> 1) != 0) { + int used; + k = rps->num_negative_pics - 1; + // flip the negative values to largest first + for (i = 0; i < rps->num_negative_pics >> 1; i++) { + delta_poc = rps->delta_poc[i]; + used = rps->used[i]; + rps->delta_poc[i] = rps->delta_poc[k]; + rps->used[i] = rps->used[k]; + rps->delta_poc[k] = delta_poc; + rps->used[k] = used; + k--; + } + } + } else { + unsigned int prev, nb_positive_pics; + rps->num_negative_pics = parseUe(pvBuf); + nb_positive_pics = parseUe(pvBuf); + + if (rps->num_negative_pics >= HEVC_MAX_REFS || + nb_positive_pics >= HEVC_MAX_REFS) { + RPT(RPT_ERR, "Too many refs in a short term RPS.\n"); + return -1; + } + + rps->num_delta_pocs = rps->num_negative_pics + nb_positive_pics; + if (rps->num_delta_pocs) { + prev = 0; + for (i = 0; i < rps->num_negative_pics; i++) { + delta_poc = parseUe(pvBuf) + 1; + if (delta_poc < 1 || delta_poc > 32768) { + RPT(RPT_ERR, + "Invalid value of delta_poc: %d\n", + delta_poc); + return -1; + } + prev -= delta_poc; + rps->delta_poc[i] = prev; + rps->used[i] = getOneBit(pvBuf); + } + prev = 0; + for (i = 0; i < nb_positive_pics; i++) { + delta_poc = parseUe(pvBuf) + 1; + if (delta_poc < 1 || delta_poc > 32768) { + RPT(RPT_ERR, + "Invalid value of delta_poc: %d\n", + delta_poc); + return -1; + } + prev += delta_poc; + rps->delta_poc[rps->num_negative_pics + i] = prev; + rps->used[rps->num_negative_pics + i] = getOneBit(pvBuf); + } + } + } + return 0; +} + +static void decodeSublayerHrd(T_GetBitContext *pvBuf, unsigned int nb_cpb, + int subpic_params_present) +{ + int i; + + for (i = 0; i < nb_cpb; i++) { + parseUe(pvBuf); // bit_rate_value_minus1 + parseUe(pvBuf); // cpb_size_value_minus1 + + if (subpic_params_present) { + parseUe(pvBuf); // cpb_size_du_value_minus1 + parseUe(pvBuf); // bit_rate_du_value_minus1 + } + getOneBit(pvBuf); // cbr_flag + } +} + +static int decodeHrd(T_GetBitContext *pvBuf, int common_inf_present, + int max_sublayers) +{ + int nal_params_present = 0, vcl_params_present = 0; + int subpic_params_present = 0; + int i; + + if (common_inf_present) { + nal_params_present = getOneBit(pvBuf); + vcl_params_present = getOneBit(pvBuf); + + if (nal_params_present || vcl_params_present) { + subpic_params_present = getOneBit(pvBuf); + + if (subpic_params_present) { + getBits(pvBuf, 8); // tick_divisor_minus2 + getBits(pvBuf, 5); // du_cpb_removal_delay_increment_length_minus1 + getBits(pvBuf, 1); // sub_pic_cpb_params_in_pic_timing_sei_flag + getBits(pvBuf, 5); // dpb_output_delay_du_length_minus1 + } + + getBits(pvBuf, 4); // bit_rate_scale + getBits(pvBuf, 4); // cpb_size_scale + + if (subpic_params_present) + getBits(pvBuf, 4); // cpb_size_du_scale + + getBits(pvBuf, 5); // initial_cpb_removal_delay_length_minus1 + getBits(pvBuf, 5); // au_cpb_removal_delay_length_minus1 + getBits(pvBuf, 5); // dpb_output_delay_length_minus1 + } + } + + for (i = 0; i < max_sublayers; i++) { + int low_delay = 0; + unsigned int nb_cpb = 1; + int fixed_rate = getOneBit(pvBuf); + + if (!fixed_rate) + fixed_rate = getOneBit(pvBuf); + + if (fixed_rate) + parseUe(pvBuf); // elemental_duration_in_tc_minus1 + else + low_delay = getOneBit(pvBuf); + + if (!low_delay) { + nb_cpb = parseUe(pvBuf) + 1; + if (nb_cpb < 1 || nb_cpb > 32) { + RPT(RPT_ERR, "nb_cpb %d invalid\n", nb_cpb); + return -1; + } + } + + if (nal_params_present) + decodeSublayerHrd(pvBuf, nb_cpb, subpic_params_present); + if (vcl_params_present) + decodeSublayerHrd(pvBuf, nb_cpb, subpic_params_present); + } + return 0; +} + + + +static void decodeVui(T_GetBitContext *pvBuf, T_HEVCSPS *sps) +{ + T_VUI backup_vui, *vui = &sps->vui; + T_GetBitContext backup; + int sar_present, alt = 0; + + RPT(RPT_DBG, "Decoding VUI\n"); + + sar_present = getOneBit(pvBuf); + if (sar_present) { + uint8_t sar_idx = getBits(pvBuf, 8); + if (sar_idx < FF_ARRAY_ELEMS(vui_sar)) + vui->sar = vui_sar[sar_idx]; + else if (sar_idx == 255) { + vui->sar.num = getBits(pvBuf, 16); + vui->sar.den = getBits(pvBuf, 16); + } else + RPT(RPT_WRN, + "Unknown SAR index: %u.\n", sar_idx); + } + + vui->overscan_info_present_flag = getOneBit(pvBuf); + if (vui->overscan_info_present_flag) + vui->overscan_appropriate_flag = getOneBit(pvBuf); + + vui->video_signal_type_present_flag = getOneBit(pvBuf); + if (vui->video_signal_type_present_flag) { + vui->video_format = getBits(pvBuf, 3); + vui->video_full_range_flag = getOneBit(pvBuf); + vui->colour_description_present_flag = getOneBit(pvBuf); +// if (vui->video_full_range_flag && sps->pix_fmt == AV_PIX_FMT_YUV420P) +// sps->pix_fmt = AV_PIX_FMT_YUVJ420P; + if (vui->colour_description_present_flag) { + vui->colour_primaries = getBits(pvBuf, 8); + vui->transfer_characteristic = getBits(pvBuf, 8); + vui->matrix_coeffs = getBits(pvBuf, 8); + +#if 0 + // Set invalid values to "unspecified" + if (!av_color_primaries_name(vui->colour_primaries)) + vui->colour_primaries = AVCOL_PRI_UNSPECIFIED; + if (!av_color_transfer_name(vui->transfer_characteristic)) + vui->transfer_characteristic = AVCOL_TRC_UNSPECIFIED; + if (!av_color_space_name(vui->matrix_coeffs)) + vui->matrix_coeffs = AVCOL_SPC_UNSPECIFIED; + if (vui->matrix_coeffs == AVCOL_SPC_RGB) { + switch (sps->pix_fmt) { + case AV_PIX_FMT_YUV444P: + sps->pix_fmt = AV_PIX_FMT_GBRP; + break; + case AV_PIX_FMT_YUV444P10: + sps->pix_fmt = AV_PIX_FMT_GBRP10; + break; + case AV_PIX_FMT_YUV444P12: + sps->pix_fmt = AV_PIX_FMT_GBRP12; + break; + } + } +#endif + } + } + + vui->chroma_loc_info_present_flag = getOneBit(pvBuf); + if (vui->chroma_loc_info_present_flag) { + vui->chroma_sample_loc_type_top_field = parseUe(pvBuf); + vui->chroma_sample_loc_type_bottom_field = parseUe(pvBuf); + } + + vui->neutra_chroma_indication_flag = getOneBit(pvBuf); + vui->field_seq_flag = getOneBit(pvBuf); + vui->frame_field_info_present_flag = getOneBit(pvBuf); + + // Backup context in case an alternate header is detected + memcpy(&backup, pvBuf, sizeof(backup)); + memcpy(&backup_vui, vui, sizeof(backup_vui)); + if (getBitsLeft(pvBuf) >= 68 && showBitsLong(pvBuf, 21) == 0x100000) { + vui->default_display_window_flag = 0; + RPT(RPT_WRN, "Invalid default display window\n"); + } else + vui->default_display_window_flag = getOneBit(pvBuf); + + if (vui->default_display_window_flag) { + int vert_mult = hevc_sub_height_c[sps->chroma_format_idc]; + int horiz_mult = hevc_sub_width_c[sps->chroma_format_idc]; + vui->def_disp_win.left_offset = parseUe(pvBuf) * horiz_mult; + vui->def_disp_win.right_offset = parseUe(pvBuf) * horiz_mult; + vui->def_disp_win.top_offset = parseUe(pvBuf) * vert_mult; + vui->def_disp_win.bottom_offset = parseUe(pvBuf) * vert_mult; + } + +timing_info: + vui->vui_timing_info_present_flag = getOneBit(pvBuf); + + if (vui->vui_timing_info_present_flag) { + if( getBitsLeft(pvBuf) < 66 && !alt) { + // The alternate syntax seem to have timing info located + // at where def_disp_win is normally located + RPT(RPT_WRN, + "Strange VUI timing information, retrying...\n"); + memcpy(vui, &backup_vui, sizeof(backup_vui)); + memcpy(pvBuf, &backup, sizeof(backup)); + alt = 1; + goto timing_info; + } + vui->vui_num_units_in_tick = getBits(pvBuf, 32); + vui->vui_time_scale = getBits(pvBuf, 32); + if (alt) { + RPT(RPT_INF, "Retry got %u/%u fps\n", + vui->vui_time_scale, vui->vui_num_units_in_tick); + } + vui->vui_poc_proportional_to_timing_flag = getOneBit(pvBuf); + if (vui->vui_poc_proportional_to_timing_flag) + vui->vui_num_ticks_poc_diff_one_minus1 = parseUe(pvBuf); + vui->vui_hrd_parameters_present_flag = getOneBit(pvBuf); + if (vui->vui_hrd_parameters_present_flag) + decodeHrd(pvBuf, 1, sps->max_sub_layers); + } + + vui->bitstream_restriction_flag = getOneBit(pvBuf); + if (vui->bitstream_restriction_flag) { + if (getBitsLeft(pvBuf) < 8 && !alt) { + RPT(RPT_WRN, + "Strange VUI bitstream restriction information, retrying" + " from timing information...\n"); + memcpy(vui, &backup_vui, sizeof(backup_vui)); + memcpy(pvBuf, &backup, sizeof(backup)); + alt = 1; + goto timing_info; + } + vui->tiles_fixed_structure_flag = getOneBit(pvBuf); + vui->motion_vectors_over_pic_boundaries_flag = getOneBit(pvBuf); + vui->restricted_ref_pic_lists_flag = getOneBit(pvBuf); + vui->min_spatial_segmentation_idc = parseUe(pvBuf); + vui->max_bytes_per_pic_denom = parseUe(pvBuf); + vui->max_bits_per_min_cu_denom = parseUe(pvBuf); + vui->log2_max_mv_length_horizontal = parseUe(pvBuf); + vui->log2_max_mv_length_vertical = parseUe(pvBuf); + } + + if (getBitsLeft(pvBuf) < 1 && !alt) { + // XXX: Alternate syntax when sps_range_extension_flag != 0? + RPT(RPT_WRN, + "Overread in VUI, retrying from timing information...\n"); + memcpy(vui, &backup_vui, sizeof(backup_vui)); + memcpy(pvBuf, &backup, sizeof(backup)); + alt = 1; + goto timing_info; + } +} + + + +int h265DecSeqParameterSet( void *pvBufSrc, T_HEVCSPS *sps ) +{ + T_HEVCWindow *ow; +// int ret = 0; + int log2_diff_max_min_transform_block_size; + int bit_depth_chroma, start, vui_present, sublayer_ordering_info; + int i; + int iRet = 0; + + + void *pvBuf = NULL; + if(NULL == pvBufSrc || NULL == sps) + { + RPT(RPT_ERR,"ERR null pointer\n"); + iRet = -1; + goto exit; + } + + memset((void *)sps, 0, sizeof(T_HEVCSPS)); + + pvBuf = deEmulationPrevention(pvBufSrc); + if(NULL == pvBuf) + { + RPT(RPT_ERR,"ERR null pointer\n"); + iRet = -1; + goto exit; + } + + + // Coded parameters + + sps->vps_id = getBits(pvBuf, 4); + if (sps->vps_id >= HEVC_MAX_VPS_COUNT) { + RPT(RPT_ERR, "VPS id out of range: %d\n", sps->vps_id); + iRet = -1; + goto exit; + } + +#if 0 + if (vps_list && !vps_list[sps->vps_id]) { + RPT(RPT_ERR, "VPS %d does not exist\n", + sps->vps_id); + return AVERROR_INVALIDDATA; + } +#endif + + sps->max_sub_layers = getBits(pvBuf, 3) + 1; + if (sps->max_sub_layers > HEVC_MAX_SUB_LAYERS) { + RPT(RPT_ERR, "sps_max_sub_layers out of range: %d\n", + sps->max_sub_layers); + iRet = -1; + goto exit; + } + + sps->temporal_id_nesting_flag = getBits(pvBuf, 1); + if ((iRet = parsePtl(pvBuf, &sps->ptl, sps->max_sub_layers)) < 0) + goto exit; + + int sps_id = parseUe(pvBuf); + if (sps_id >= HEVC_MAX_SPS_COUNT) { + RPT(RPT_ERR, "SPS id out of range: %d\n", sps_id); + iRet = -1; + goto exit; + } + + sps->chroma_format_idc = parseUe(pvBuf); + if (sps->chroma_format_idc > 3U) { + RPT(RPT_ERR, "chroma_format_idc %d is invalid\n", sps->chroma_format_idc); + iRet = -1; + goto exit; + } + + if (sps->chroma_format_idc == 3) + sps->separate_colour_plane_flag = getOneBit(pvBuf); + + if (sps->separate_colour_plane_flag) + sps->chroma_format_idc = 0; + + sps->width = parseUe(pvBuf); + sps->height = parseUe(pvBuf); + +// if ((iRet = av_image_check_size(sps->width, +// sps->height, 0, avctx)) < 0) +// goto exit; + + if (getOneBit(pvBuf)) { // pic_conformance_flag + int vert_mult = hevc_sub_height_c[sps->chroma_format_idc]; + int horiz_mult = hevc_sub_width_c[sps->chroma_format_idc]; + sps->pic_conf_win.left_offset = parseUe(pvBuf) * horiz_mult; + sps->pic_conf_win.right_offset = parseUe(pvBuf) * horiz_mult; + sps->pic_conf_win.top_offset = parseUe(pvBuf) * vert_mult; + sps->pic_conf_win.bottom_offset = parseUe(pvBuf) * vert_mult; + + sps->output_window = sps->pic_conf_win; + } + + sps->bit_depth = parseUe(pvBuf) + 8; + bit_depth_chroma = parseUe(pvBuf) + 8; + + if (sps->chroma_format_idc && bit_depth_chroma != sps->bit_depth) { + RPT(RPT_ERR, + "Luma bit depth (%d) is different from chroma bit depth (%d), " + "this is unsupported.\n", + sps->bit_depth, bit_depth_chroma); + iRet = -1; + goto exit; + } + sps->bit_depth_chroma = bit_depth_chroma; + +#if 0 + iRet = map_pixel_format(avctx, sps); + if (iRet < 0) + goto exit; +#endif + +#if 0 + + sps->log2_max_poc_lsb = parseUe(pvBuf) + 4; + if (sps->log2_max_poc_lsb > 16) { + RPT(RPT_ERR, "log2_max_pic_order_cnt_lsb_minus4 out range: %d\n", + sps->log2_max_poc_lsb - 4); + iRet = -1; + goto exit; + } + + sublayer_ordering_info = getOneBit(pvBuf); + start = sublayer_ordering_info ? 0 : sps->max_sub_layers - 1; + for (i = start; i < sps->max_sub_layers; i++) { + sps->temporal_layer[i].max_dec_pic_buffering = parseUe(pvBuf) + 1; + sps->temporal_layer[i].num_reorder_pics = parseUe(pvBuf); + sps->temporal_layer[i].max_latency_increase = parseUe(pvBuf) - 1; + if (sps->temporal_layer[i].max_dec_pic_buffering > (unsigned)HEVC_MAX_DPB_SIZE) { + RPT(RPT_ERR, "sps_max_dec_pic_buffering_minus1 out of range: %d\n", + sps->temporal_layer[i].max_dec_pic_buffering - 1U); + iRet = -1; + goto exit; + } + if (sps->temporal_layer[i].num_reorder_pics > sps->temporal_layer[i].max_dec_pic_buffering - 1) { + RPT(RPT_WRN, "sps_max_num_reorder_pics out of range: %d\n", + sps->temporal_layer[i].num_reorder_pics); + if (sps->temporal_layer[i].num_reorder_pics > HEVC_MAX_DPB_SIZE - 1) { + iRet = -1; + goto exit; + } + sps->temporal_layer[i].max_dec_pic_buffering = sps->temporal_layer[i].num_reorder_pics + 1; + } + } + + if (!sublayer_ordering_info) { + for (i = 0; i < start; i++) { + sps->temporal_layer[i].max_dec_pic_buffering = sps->temporal_layer[start].max_dec_pic_buffering; + sps->temporal_layer[i].num_reorder_pics = sps->temporal_layer[start].num_reorder_pics; + sps->temporal_layer[i].max_latency_increase = sps->temporal_layer[start].max_latency_increase; + } + } + + sps->log2_min_cb_size = parseUe(pvBuf) + 3; + sps->log2_diff_max_min_coding_block_size = parseUe(pvBuf); + sps->log2_min_tb_size = parseUe(pvBuf) + 2; + log2_diff_max_min_transform_block_size = parseUe(pvBuf); + sps->log2_max_trafo_size = log2_diff_max_min_transform_block_size + + sps->log2_min_tb_size; + + if (sps->log2_min_cb_size < 3 || sps->log2_min_cb_size > 30) { + RPT(RPT_ERR, "Invalid value %d for log2_min_cb_size", sps->log2_min_cb_size); + iRet = -1; + goto exit; + } + + if (sps->log2_diff_max_min_coding_block_size > 30) { + RPT(RPT_ERR, "Invalid value %d for log2_diff_max_min_coding_block_size", sps->log2_diff_max_min_coding_block_size); + iRet = -1; + goto exit; + } + + if (sps->log2_min_tb_size >= sps->log2_min_cb_size || sps->log2_min_tb_size < 2) { + RPT(RPT_ERR, "Invalid value for log2_min_tb_size"); + iRet = -1; + goto exit; + } + + if (log2_diff_max_min_transform_block_size < 0 || log2_diff_max_min_transform_block_size > 30) { + RPT(RPT_ERR, "Invalid value %d for log2_diff_max_min_transform_block_size", log2_diff_max_min_transform_block_size); + iRet = -1; + goto exit; + } + + sps->max_transform_hierarchy_depth_inter = parseUe(pvBuf); + sps->max_transform_hierarchy_depth_intra = parseUe(pvBuf); + + sps->scaling_list_enable_flag = getOneBit(pvBuf); + + printf("sps->scaling_list_enable_flag: %d\n",sps->scaling_list_enable_flag); + + if (sps->scaling_list_enable_flag) { + setDefaultScalingListData(&sps->scaling_list); + + if (getOneBit(pvBuf)) { + iRet = scalingListData(pvBuf, &sps->scaling_list, sps); + if (iRet < 0) + goto exit; + } + } + + sps->amp_enabled_flag = getOneBit(pvBuf); + sps->sao_enabled = getOneBit(pvBuf); + + sps->pcm_enabled_flag = getOneBit(pvBuf); + + printf("sps->pcm_enabled_flag: %d\n",sps->pcm_enabled_flag); + if (sps->pcm_enabled_flag) { + sps->pcm.bit_depth = getBits(pvBuf, 4) + 1; + sps->pcm.bit_depth_chroma = getBits(pvBuf, 4) + 1; + sps->pcm.log2_min_pcm_cb_size = parseUe(pvBuf) + 3; + sps->pcm.log2_max_pcm_cb_size = sps->pcm.log2_min_pcm_cb_size + + parseUe(pvBuf); + if (FFMAX(sps->pcm.bit_depth, sps->pcm.bit_depth_chroma) > sps->bit_depth) { + RPT(RPT_ERR, + "PCM bit depth (%d, %d) is greater than normal bit depth (%d)\n", + sps->pcm.bit_depth, sps->pcm.bit_depth_chroma, sps->bit_depth); + iRet = -1; + goto exit; + } + + sps->pcm.loop_filter_disable_flag = getOneBit(pvBuf); + } + + sps->nb_st_rps = parseUe(pvBuf); + if (sps->nb_st_rps > HEVC_MAX_SHORT_TERM_REF_PIC_SETS) { + RPT(RPT_ERR, "Too many short term RPS: %d.\n", + sps->nb_st_rps); + iRet = -1; + goto exit; + } + printf("sps->nb_st_rps: %d\n",sps->nb_st_rps); + for (i = 0; i < sps->nb_st_rps; i++) { + if ((iRet = hevcDecodeShortTermRps(pvBuf, &sps->st_rps[i], + sps, 0)) < 0) + goto exit; + } + + sps->long_term_ref_pics_present_flag = getOneBit(pvBuf); + if (sps->long_term_ref_pics_present_flag) { + sps->num_long_term_ref_pics_sps = parseUe(pvBuf); + if (sps->num_long_term_ref_pics_sps > HEVC_MAX_LONG_TERM_REF_PICS) { + RPT(RPT_ERR, "Too many long term ref pics: %d.\n", + sps->num_long_term_ref_pics_sps); + iRet = -1; + goto exit; + } + for (i = 0; i < sps->num_long_term_ref_pics_sps; i++) { + sps->lt_ref_pic_poc_lsb_sps[i] = getBits(pvBuf, sps->log2_max_poc_lsb); + sps->used_by_curr_pic_lt_sps_flag[i] = getOneBit(pvBuf); + } + } + + sps->sps_temporal_mvp_enabled_flag = getOneBit(pvBuf); + sps->sps_strong_intra_smoothing_enable_flag = getOneBit(pvBuf); + sps->vui.sar = (T_AVRational){0, 1}; + vui_present = getOneBit(pvBuf); + if (vui_present==1) + decodeVui(pvBuf, sps); + +#endif +#if 0 + + if (getOneBit(pvBuf)) { // sps_extension_flag + int sps_range_extension_flag = getOneBit(pvBuf); + getBits(pvBuf, 7); //sps_extension_7bits = getBits(pvBuf, 7); + if (sps_range_extension_flag) { + int extended_precision_processing_flag; + int cabac_bypass_alignment_enabled_flag; + + sps->transform_skip_rotation_enabled_flag = getOneBit(pvBuf); + sps->transform_skip_context_enabled_flag = getOneBit(pvBuf); + sps->implicit_rdpcm_enabled_flag = getOneBit(pvBuf); + + sps->explicit_rdpcm_enabled_flag = getOneBit(pvBuf); + + extended_precision_processing_flag = getOneBit(pvBuf); + if (extended_precision_processing_flag) + RPT(RPT_WRN, + "extended_precision_processing_flag not yet implemented\n"); + + sps->intra_smoothing_disabled_flag = getOneBit(pvBuf); + sps->high_precision_offsets_enabled_flag = getOneBit(pvBuf); + if (sps->high_precision_offsets_enabled_flag) + RPT(RPT_WRN, + "high_precision_offsets_enabled_flag not yet implemented\n"); + + sps->persistent_rice_adaptation_enabled_flag = getOneBit(pvBuf); + + cabac_bypass_alignment_enabled_flag = getOneBit(pvBuf); + if (cabac_bypass_alignment_enabled_flag) + RPT(RPT_WRN, + "cabac_bypass_alignment_enabled_flag not yet implemented\n"); + } + } + if (apply_defdispwin) { + sps->output_window.left_offset += sps->vui.def_disp_win.left_offset; + sps->output_window.right_offset += sps->vui.def_disp_win.right_offset; + sps->output_window.top_offset += sps->vui.def_disp_win.top_offset; + sps->output_window.bottom_offset += sps->vui.def_disp_win.bottom_offset; + } + + ow = &sps->output_window; + if (ow->left_offset >= INT_MAX - ow->right_offset || + ow->top_offset >= INT_MAX - ow->bottom_offset || + ow->left_offset + ow->right_offset >= sps->width || + ow->top_offset + ow->bottom_offset >= sps->height) { + RPT(RPT_WRN, "Invalid cropping offsets: %u/%u/%u/%u\n", + ow->left_offset, ow->right_offset, ow->top_offset, ow->bottom_offset); + if (avctx->err_recognition & AV_EF_EXPLODE) { + return AVERROR_INVALIDDATA; + } + RPT(RPT_WRN, + "Displaying the whole video surface.\n"); + memset(ow, 0, sizeof(*ow)); + memset(&sps->pic_conf_win, 0, sizeof(sps->pic_conf_win)); + } + + // Inferred parameters + sps->log2_ctb_size = sps->log2_min_cb_size + + sps->log2_diff_max_min_coding_block_size; + sps->log2_min_pu_size = sps->log2_min_cb_size - 1; + + if (sps->log2_ctb_size > HEVC_MAX_LOG2_CTB_SIZE) { + RPT(RPT_ERR, "CTB size out of range: 2^%d\n", sps->log2_ctb_size); + iRet = -1; + iRet = -1; + goto exit; + } + if (sps->log2_ctb_size < 4) { + RPT(RPT_ERR, + "log2_ctb_size %d differs from the bounds of any known profile\n", + sps->log2_ctb_size); + avpriv_request_sample(avctx, "log2_ctb_size %d", sps->log2_ctb_size); + iRet = -1; + iRet = -1; + goto exit; + } + + sps->ctb_width = (sps->width + (1 << sps->log2_ctb_size) - 1) >> sps->log2_ctb_size; + sps->ctb_height = (sps->height + (1 << sps->log2_ctb_size) - 1) >> sps->log2_ctb_size; + sps->ctb_size = sps->ctb_width * sps->ctb_height; + + sps->min_cb_width = sps->width >> sps->log2_min_cb_size; + sps->min_cb_height = sps->height >> sps->log2_min_cb_size; + sps->min_tb_width = sps->width >> sps->log2_min_tb_size; + sps->min_tb_height = sps->height >> sps->log2_min_tb_size; + sps->min_pu_width = sps->width >> sps->log2_min_pu_size; + sps->min_pu_height = sps->height >> sps->log2_min_pu_size; + sps->tb_mask = (1 << (sps->log2_ctb_size - sps->log2_min_tb_size)) - 1; + + sps->qp_bd_offset = 6 * (sps->bit_depth - 8); + + if (av_mod_uintp2(sps->width, sps->log2_min_cb_size) || + av_mod_uintp2(sps->height, sps->log2_min_cb_size)) { + RPT(RPT_ERR, "Invalid coded frame dimensions.\n"); + iRet = -1; + goto exit; + } + + if (sps->max_transform_hierarchy_depth_inter > sps->log2_ctb_size - sps->log2_min_tb_size) { + RPT(RPT_ERR, "max_transform_hierarchy_depth_inter out of range: %d\n", + sps->max_transform_hierarchy_depth_inter); + iRet = -1; + goto exit; + } + if (sps->max_transform_hierarchy_depth_intra > sps->log2_ctb_size - sps->log2_min_tb_size) { + RPT(RPT_ERR, "max_transform_hierarchy_depth_intra out of range: %d\n", + sps->max_transform_hierarchy_depth_intra); + iRet = -1; + goto exit; + } + if (sps->log2_max_trafo_size > FFMIN(sps->log2_ctb_size, 5)) { + RPT(RPT_ERR, + "max transform block size out of range: %d\n", + sps->log2_max_trafo_size); + iRet = -1; + goto exit; + } + + if (getBitsLeft(pvBuf) < 0) { + RPT(RPT_ERR, + "Overread SPS by %d bits\n", -getBitsLeft(pvBuf)); + iRet = -1; + goto exit; + } +#endif + + +exit: + + getBitContextFree(pvBuf); + return iRet; + +} + + void h264GetWidthHeight(T_SPS *ptSps, int *piWidth, int *piHeight) { // ¿í¸ß¼ÆË㹫ʽ @@ -1036,3 +2187,32 @@ void h264GeFramerate(T_SPS *ptSps, float *pfFramerate) + +void h265GetWidthHeight(T_HEVCSPS *ptSps, int *piWidth, int *piHeight) +{ +#if 1 + // ¿í¸ß¼ÆË㹫ʽ + int iCodeWidth = 0; + int iCodedHeight = 0; + iCodeWidth = ptSps->width; + iCodedHeight = ptSps->height; + *piWidth = ptSps->width - ptSps->pic_conf_win.left_offset - ptSps->pic_conf_win.right_offset; + *piHeight = ptSps->height - ptSps->pic_conf_win.top_offset - ptSps->pic_conf_win.bottom_offset; + + RPT(RPT_DBG, "iCodeWidth:%d, iCodedHeight:%d\n", iCodeWidth, iCodedHeight); + + RPT(RPT_DBG, "*piWidth:%d, *piHeight:%d\n", *piWidth, *piHeight); + +// RPT(RPT_DBG, "ptSps->uiCropRight:%d, ptSps->uiCropLeft:%d\n", ptSps->uiCropRight, ptSps->uiCropLeft); + +// RPT(RPT_DBG, "ptSps->uiCropTop:%d, ptSps->uiCropBottom:%d\n", ptSps->uiCropTop, ptSps->uiCropBottom); +#endif + +} + + + +void h265GeFramerate(T_HEVCSPS *ptSps, float *pfFramerate) +{ +} + diff --git a/src/Extension/SPSParser.h b/src/Extension/SPSParser.h index e25501ac..63f8d5f6 100644 --- a/src/Extension/SPSParser.h +++ b/src/Extension/SPSParser.h @@ -7,6 +7,15 @@ #define QP_MAX_NUM (51 + 6*6) // The maximum supported qp +#define HEVC_MAX_SHORT_TERM_RPS_COUNT 64 + +#define T_PROFILE_HEVC_MAIN 1 +#define T_PROFILE_HEVC_MAIN_10 2 +#define T_PROFILE_HEVC_MAIN_STILL_PICTURE 3 +#define T_PROFILE_HEVC_REXT 4 + + + /** * Chromaticity coordinates of the source primaries. */ @@ -67,6 +76,62 @@ enum T_AVColorSpace { }; +enum { + // 7.4.3.1: vps_max_layers_minus1 is in [0, 62]. + HEVC_MAX_LAYERS = 63, + // 7.4.3.1: vps_max_sub_layers_minus1 is in [0, 6]. + HEVC_MAX_SUB_LAYERS = 7, + // 7.4.3.1: vps_num_layer_sets_minus1 is in [0, 1023]. + HEVC_MAX_LAYER_SETS = 1024, + + // 7.4.2.1: vps_video_parameter_set_id is u(4). + HEVC_MAX_VPS_COUNT = 16, + // 7.4.3.2.1: sps_seq_parameter_set_id is in [0, 15]. + HEVC_MAX_SPS_COUNT = 16, + // 7.4.3.3.1: pps_pic_parameter_set_id is in [0, 63]. + HEVC_MAX_PPS_COUNT = 64, + + // A.4.2: MaxDpbSize is bounded above by 16. + HEVC_MAX_DPB_SIZE = 16, + // 7.4.3.1: vps_max_dec_pic_buffering_minus1[i] is in [0, MaxDpbSize - 1]. + HEVC_MAX_REFS = HEVC_MAX_DPB_SIZE, + + // 7.4.3.2.1: num_short_term_ref_pic_sets is in [0, 64]. + HEVC_MAX_SHORT_TERM_REF_PIC_SETS = 64, + // 7.4.3.2.1: num_long_term_ref_pics_sps is in [0, 32]. + HEVC_MAX_LONG_TERM_REF_PICS = 32, + + // A.3: all profiles require that CtbLog2SizeY is in [4, 6]. + HEVC_MIN_LOG2_CTB_SIZE = 4, + HEVC_MAX_LOG2_CTB_SIZE = 6, + + // E.3.2: cpb_cnt_minus1[i] is in [0, 31]. + HEVC_MAX_CPB_CNT = 32, + + // A.4.1: in table A.6 the highest level allows a MaxLumaPs of 35 651 584. + HEVC_MAX_LUMA_PS = 35651584, + // A.4.1: pic_width_in_luma_samples and pic_height_in_luma_samples are + // constrained to be not greater than sqrt(MaxLumaPs * 8). Hence height/ + // width are bounded above by sqrt(8 * 35651584) = 16888.2 samples. + HEVC_MAX_WIDTH = 16888, + HEVC_MAX_HEIGHT = 16888, + + // A.4.1: table A.6 allows at most 22 tile rows for any level. + HEVC_MAX_TILE_ROWS = 22, + // A.4.1: table A.6 allows at most 20 tile columns for any level. + HEVC_MAX_TILE_COLUMNS = 20, + + // 7.4.7.1: in the worst case (tiles_enabled_flag and + // entropy_coding_sync_enabled_flag are both set), entry points can be + // placed at the beginning of every Ctb row in every tile, giving an + // upper bound of (num_tile_columns_minus1 + 1) * PicHeightInCtbsY - 1. + // Only a stream with very high resolution and perverse parameters could + // get near that, though, so set a lower limit here with the maximum + // possible value for 4K video (at most 135 16x16 Ctb rows). + HEVC_MAX_ENTRY_POINT_OFFSETS = HEVC_MAX_TILE_COLUMNS * 135, +}; + + /** * rational number numerator/denominator */ @@ -170,6 +235,189 @@ typedef struct T_PPS { int iChromaQpDiff; } T_PPS; + +typedef struct T_HEVCWindow { + unsigned int left_offset; + unsigned int right_offset; + unsigned int top_offset; + unsigned int bottom_offset; +} T_HEVCWindow; + + +typedef struct T_VUI { + T_AVRational sar; + + int overscan_info_present_flag; + int overscan_appropriate_flag; + + int video_signal_type_present_flag; + int video_format; + int video_full_range_flag; + int colour_description_present_flag; + uint8_t colour_primaries; + uint8_t transfer_characteristic; + uint8_t matrix_coeffs; + + int chroma_loc_info_present_flag; + int chroma_sample_loc_type_top_field; + int chroma_sample_loc_type_bottom_field; + int neutra_chroma_indication_flag; + + int field_seq_flag; + int frame_field_info_present_flag; + + int default_display_window_flag; + T_HEVCWindow def_disp_win; + + int vui_timing_info_present_flag; + uint32_t vui_num_units_in_tick; + uint32_t vui_time_scale; + int vui_poc_proportional_to_timing_flag; + int vui_num_ticks_poc_diff_one_minus1; + int vui_hrd_parameters_present_flag; + + int bitstream_restriction_flag; + int tiles_fixed_structure_flag; + int motion_vectors_over_pic_boundaries_flag; + int restricted_ref_pic_lists_flag; + int min_spatial_segmentation_idc; + int max_bytes_per_pic_denom; + int max_bits_per_min_cu_denom; + int log2_max_mv_length_horizontal; + int log2_max_mv_length_vertical; +} T_VUI; + +typedef struct T_PTLCommon { + uint8_t profile_space; + uint8_t tier_flag; + uint8_t profile_idc; + uint8_t profile_compatibility_flag[32]; + uint8_t level_idc; + uint8_t progressive_source_flag; + uint8_t interlaced_source_flag; + uint8_t non_packed_constraint_flag; + uint8_t frame_only_constraint_flag; +} T_PTLCommon; + +typedef struct T_PTL { + T_PTLCommon general_ptl; + T_PTLCommon sub_layer_ptl[HEVC_MAX_SUB_LAYERS]; + + uint8_t sub_layer_profile_present_flag[HEVC_MAX_SUB_LAYERS]; + uint8_t sub_layer_level_present_flag[HEVC_MAX_SUB_LAYERS]; +} T_PTL; + +typedef struct T_ScalingList { + /* This is a little wasteful, since sizeID 0 only needs 8 coeffs, + * and size ID 3 only has 2 arrays, not 6. */ + uint8_t sl[4][6][64]; + uint8_t sl_dc[2][6]; +} T_ScalingList; + +typedef struct T_ShortTermRPS { + unsigned int num_negative_pics; + int num_delta_pocs; + int rps_idx_num_delta_pocs; + int32_t delta_poc[32]; + uint8_t used[32]; +} T_ShortTermRPS; + + +typedef struct T_HEVCSPS { + unsigned vps_id; + int chroma_format_idc; + uint8_t separate_colour_plane_flag; + + ///< output (i.e. cropped) values + int output_width, output_height; + T_HEVCWindow output_window; + + T_HEVCWindow pic_conf_win; + + int bit_depth; + int bit_depth_chroma; + int pixel_shift; +// enum AVPixelFormat pix_fmt; + + unsigned int log2_max_poc_lsb; + int pcm_enabled_flag; + + int max_sub_layers; + struct { + int max_dec_pic_buffering; + int num_reorder_pics; + int max_latency_increase; + } temporal_layer[HEVC_MAX_SUB_LAYERS]; + uint8_t temporal_id_nesting_flag; + + T_VUI vui; + T_PTL ptl; + + uint8_t scaling_list_enable_flag; + T_ScalingList scaling_list; + + unsigned int nb_st_rps; + T_ShortTermRPS st_rps[HEVC_MAX_SHORT_TERM_RPS_COUNT]; + + uint8_t amp_enabled_flag; + uint8_t sao_enabled; + + uint8_t long_term_ref_pics_present_flag; + uint16_t lt_ref_pic_poc_lsb_sps[32]; + uint8_t used_by_curr_pic_lt_sps_flag[32]; + uint8_t num_long_term_ref_pics_sps; + + struct { + uint8_t bit_depth; + uint8_t bit_depth_chroma; + unsigned int log2_min_pcm_cb_size; + unsigned int log2_max_pcm_cb_size; + uint8_t loop_filter_disable_flag; + } pcm; + uint8_t sps_temporal_mvp_enabled_flag; + uint8_t sps_strong_intra_smoothing_enable_flag; + + unsigned int log2_min_cb_size; + unsigned int log2_diff_max_min_coding_block_size; + unsigned int log2_min_tb_size; + unsigned int log2_max_trafo_size; + unsigned int log2_ctb_size; + unsigned int log2_min_pu_size; + + int max_transform_hierarchy_depth_inter; + int max_transform_hierarchy_depth_intra; + + int transform_skip_rotation_enabled_flag; + int transform_skip_context_enabled_flag; + int implicit_rdpcm_enabled_flag; + int explicit_rdpcm_enabled_flag; + int intra_smoothing_disabled_flag; + int persistent_rice_adaptation_enabled_flag; + + ///< coded frame dimension in various units + int width; + int height; + int ctb_width; + int ctb_height; + int ctb_size; + int min_cb_width; + int min_cb_height; + int min_tb_width; + int min_tb_height; + int min_pu_width; + int min_pu_height; + int tb_mask; + + int hshift[3]; + int vshift[3]; + + int qp_bd_offset; + + uint8_t data[4096]; + int data_size; +}T_HEVCSPS; + + typedef struct T_GetBitContext{ uint8_t *pu8Buf; /*Ö¸ÏòSPS start*/ int iBufSize; /*SPS ³¤¶È*/ @@ -180,8 +428,13 @@ typedef struct T_GetBitContext{ int h264DecSeqParameterSet(void *pvBuf, T_SPS *ptSps); +int h265DecSeqParameterSet( void *pvBufSrc, T_HEVCSPS *p_sps ); + void h264GetWidthHeight(T_SPS *ptSps, int *piWidth, int *piHeight); +void h265GetWidthHeight(T_HEVCSPS *ptSps, int *piWidth, int *piHeight); + void h264GeFramerate(T_SPS *ptSps, float *pfFramerate); +void h265GeFramerate(T_HEVCSPS *ptSps, float *pfFramerate); #if defined (__cplusplus) } diff --git a/src/MediaFile/Mp4Maker.cpp b/src/MediaFile/Mp4Maker.cpp index 4afa2912..1c9bd37f 100644 --- a/src/MediaFile/Mp4Maker.cpp +++ b/src/MediaFile/Mp4Maker.cpp @@ -35,9 +35,57 @@ #include "Util/util.h" #include "Util/NoticeCenter.h" #include "Extension/H264.h" +#include "Extension/H265.h" #include "Extension/AAC.h" #include "Thread/WorkThreadPool.h" + +#ifdef MP4_H265RECORD +#include "mov-buffer.h" +#include "mov-format.h" + +#if defined(_WIN32) || defined(_WIN64) +#define fseek64 _fseeki64 +#define ftell64 _ftelli64 +#else +#define fseek64 fseek +#define ftell64 ftell +#endif + +static int mov_file_read(void* fp, void* data, uint64_t bytes) +{ + if (bytes == fread(data, 1, bytes, (FILE*)fp)) + return 0; + return 0 != ferror((FILE*)fp) ? ferror((FILE*)fp) : -1 /*EOF*/; +} + +static int mov_file_write(void* fp, const void* data, uint64_t bytes) +{ + return bytes == fwrite(data, 1, bytes, (FILE*)fp) ? 0 : ferror((FILE*)fp); +} + +static int mov_file_seek(void* fp, uint64_t offset) +{ + return fseek64((FILE*)fp, offset, SEEK_SET); +} + +static uint64_t mov_file_tell(void* fp) +{ + return ftell64((FILE*)fp); +} + +const struct mov_buffer_t* mov_file_buffer(void) +{ + static struct mov_buffer_t s_io = { + mov_file_read, + mov_file_write, + mov_file_seek, + mov_file_tell, + }; + return &s_io; +} +#endif + using namespace toolkit; namespace mediakit { @@ -101,17 +149,46 @@ void Mp4Maker::inputH264(void *pData, uint32_t ui32Length, uint32_t ui32TimeStam break; } } -void Mp4Maker::inputAAC(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp){ - if (_strLastAudio.size()) { - int64_t iTimeInc = (int64_t)ui32TimeStamp - (int64_t)_ui32LastAudioTime; - iTimeInc = MAX(0,MIN(iTimeInc,500)); - if(iTimeInc == 0 || iTimeInc == 500){ - WarnL << "abnormal time stamp increment:" << ui32TimeStamp << " " << _ui32LastAudioTime; - } - inputAAC_l((char *) _strLastAudio.data(), _strLastAudio.size(), iTimeInc); + +void Mp4Maker::inputH265(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp){ +#ifdef MP4_H265RECORD + auto iType = H265_TYPE(((uint8_t*)pData)[4]); + if (iType <= 19 ){ + if (_strLastVideo.size() && iType == 19){ + _strLastVideo.append((char *)pData,ui32Length); + inputH265_l((char *) _strLastVideo.data(), _strLastVideo.size(), ui32TimeStamp); + _strLastVideo = ""; + _ui32LastVideoTime = ui32TimeStamp; + }else + inputH265_l((char *) pData, ui32Length, ui32TimeStamp); + }else{ + _strLastVideo.append((char *)pData,ui32Length); + _ui32LastVideoTime = ui32TimeStamp; } - _strLastAudio.assign((char *)pData, ui32Length); - _ui32LastAudioTime = ui32TimeStamp; +#endif +} + +void Mp4Maker::inputAAC(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp){ +#ifdef MP4_H265RECORD + if (_h265Record){ + inputAAC_l((char *) pData, ui32Length, ui32TimeStamp); + }else +#endif + { + if (_strLastAudio.size()) { + int64_t iTimeInc = (int64_t)ui32TimeStamp - (int64_t)_ui32LastAudioTime; + iTimeInc = MAX(0,MIN(iTimeInc,500)); + if(iTimeInc == 0 || iTimeInc == 500){ + WarnL << "abnormal time stamp increment:" << ui32TimeStamp << " " << _ui32LastAudioTime; + } + inputAAC_l((char *) _strLastAudio.data(), _strLastAudio.size(), iTimeInc); + } + _strLastAudio.assign((char *)pData, ui32Length); + _ui32LastAudioTime = ui32TimeStamp; + } + + + } void Mp4Maker::inputH264_l(void *pData, uint32_t ui32Length, uint32_t ui32Duration) { @@ -127,17 +204,79 @@ void Mp4Maker::inputH264_l(void *pData, uint32_t ui32Length, uint32_t ui32Durati } } -void Mp4Maker::inputAAC_l(void *pData, uint32_t ui32Length, uint32_t ui32Duration) { +void Mp4Maker::inputH265_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp) { GET_CONFIG(uint32_t,recordSec,Record::kFileSecond); - - if (!_haveVideo && (_hMp4 == MP4_INVALID_FILE_HANDLE || _ticker.elapsedTime() > recordSec * 1000)) { + +#ifdef MP4_H265RECORD + int32_t compositionTime; + auto iType = H265_TYPE(((uint8_t*)pData)[4]); + if( iType >= H265Frame::NAL_IDR_W_RADL && (_movH265info.pMov == NULL || _ticker.elapsedTime() > recordSec * 1000)){ //在I帧率处新建MP4文件 //如果文件未创建或者文件超过10分钟则创建新文件 + _h265Record = 1; createFile(); } - if (_hAudio != MP4_INVALID_TRACK_ID) { - auto duration = ui32Duration * _audioSampleRate /1000.0; - MP4WriteSample(_hMp4, _hAudio, (uint8_t*)pData, ui32Length,duration,0,false); + + char *pNualData = (char *)pData; + if (/*iType <= 31 && */_movH265info.pMov!=NULL){ + int vcl; + //media-server新版的api使用h265_annexbtomp4 + //int n = h265_annexbtomp4(&_movH265info.hevc, pData, ui32Length, _sBbuffer, sizeof(_sBbuffer), &vcl); + int n = hevc_annexbtomp4(&_movH265info.hevc, pData, ui32Length, _sBbuffer, sizeof(_sBbuffer)); + if (_movH265info.videoTrack < 0){ + if (_movH265info.hevc.numOfArrays < 1){ + return; // waiting for vps/sps/pps + } + + uint8_t sExtraData[64 * 1024]; + int extraDataSize = mpeg4_hevc_decoder_configuration_record_save(&_movH265info.hevc, sExtraData, sizeof(sExtraData)); + if (extraDataSize <= 0){ + // invalid HVCC + return; + } + + // TODO: waiting for key frame ??? + _movH265info.videoTrack = mov_writer_add_video(_movH265info.pMov, MOV_OBJECT_HEVC, _movH265info.width, _movH265info.height, sExtraData, extraDataSize); + if (_movH265info.videoTrack < 0) + return; + } + mov_writer_write(_movH265info.pMov, + _movH265info.videoTrack, + _sBbuffer, + n, + ui32TimeStamp, + ui32TimeStamp, + (iType >= 16 && iType <= 23) ? MOV_AV_FLAG_KEYFREAME : 0 ); +// mov_writer_write(_movH265info.pMov, _movH265info.videoTrack, _sBbuffer, n, ui32TimeStamp, ui32TimeStamp, 1 == vcl ? MOV_AV_FLAG_KEYFREAME : 0); + } +#endif + +} + +void Mp4Maker::inputAAC_l(void *pData, uint32_t ui32Length, uint32_t ui32Duration) { + GET_CONFIG(uint32_t,recordSec,Record::kFileSecond); +#ifdef MP4_H265RECORD + if ( _h265Record ) + { + if (!_haveVideo && (_movH265info.pMov == NULL || _ticker.elapsedTime() > recordSec * 1000)) { + createFile(); + } + + if (-1 != _movH265info.audioTrack && _movH265info.pMov != NULL){ + mov_writer_write(_movH265info.pMov, _movH265info.audioTrack, (uint8_t*)pData, ui32Length, ui32Duration, ui32Duration, 0); + } + }else +#endif + { + if (!_haveVideo && (_hMp4 == MP4_INVALID_FILE_HANDLE || _ticker.elapsedTime() > recordSec * 1000)) { + //在I帧率处新建MP4文件 + //如果文件未创建或者文件超过10分钟则创建新文件 + createFile(); + } + if (_hAudio != MP4_INVALID_TRACK_ID) { + auto duration = ui32Duration * _audioSampleRate /1000.0; + MP4WriteSample(_hMp4, _hAudio, (uint8_t*)pData, ui32Length,duration,0,false); + } } } @@ -169,60 +308,120 @@ void Mp4Maker::createFile() { #else File::createfile_path(strFileTmp.data(), 0); #endif - _hMp4 = MP4Create(strFileTmp.data()); - if (_hMp4 == MP4_INVALID_FILE_HANDLE) { - WarnL << "创建MP4文件失败:" << strFileTmp; - return; + +#ifdef MP4_H265RECORD + if ( _h265Record ){ + memset(&_movH265info, 0, sizeof(_movH265info)); + _movH265info.videoTrack = -1; + _movH265info.audioTrack = -1; + _movH265info.width = 0; + _movH265info.height = 0; + _movH265info.ptr = NULL; + _movH265info.pFile = fopen(strFileTmp.data(), "wb+"); + _movH265info.pMov = mov_writer_create(mov_file_buffer(), _movH265info.pFile, 0/*MOV_FLAG_FASTSTART*/); + }else +#endif + { + _hMp4 = MP4Create(strFileTmp.data(),MP4_CREATE_64BIT_DATA); + if (_hMp4 == MP4_INVALID_FILE_HANDLE) { + WarnL << "创建MP4文件失败:" << strFileTmp; + return; + } } + //MP4SetTimeScale(_hMp4, 90000); _strFileTmp = strFileTmp; _strFile = strFile; _ticker.resetTime(); - auto videoTrack = dynamic_pointer_cast(getTrack(TrackVideo)); - if(videoTrack){ - auto &sps = videoTrack->getSps(); - auto &pps = videoTrack->getPps(); - _hVideo = MP4AddH264VideoTrack(_hMp4, - 90000, - MP4_INVALID_DURATION, - videoTrack->getVideoWidth(), - videoTrack->getVideoHeight(), - sps[1], - sps[2], - sps[3], - 3); - if(_hVideo != MP4_INVALID_TRACK_ID){ - MP4AddH264SequenceParameterSet(_hMp4, _hVideo, (uint8_t *)sps.data(), sps.size()); - MP4AddH264PictureParameterSet(_hMp4, _hVideo, (uint8_t *)pps.data(), pps.size()); - }else{ - WarnL << "添加视频通道失败:" << strFileTmp; + if ( _h265Record ){ + auto videoTrack = dynamic_pointer_cast(getTrack(TrackVideo)); +#ifdef MP4_H265RECORD + if(videoTrack){ + _movH265info.width = videoTrack->getVideoWidth(); + _movH265info.height = videoTrack->getVideoHeight(); } +#endif + + }else { + auto videoTrack = dynamic_pointer_cast(getTrack(TrackVideo)); + if(videoTrack){ + auto &sps = videoTrack->getSps(); + auto &pps = videoTrack->getPps(); + + + _hVideo = MP4AddH264VideoTrack(_hMp4, + 90000, + MP4_INVALID_DURATION, + videoTrack->getVideoWidth(), + videoTrack->getVideoHeight(), + sps[1], + sps[2], + sps[3], + 3); + if(_hVideo != MP4_INVALID_TRACK_ID){ + MP4AddH264SequenceParameterSet(_hMp4, _hVideo, (uint8_t *)sps.data(), sps.size()); + MP4AddH264PictureParameterSet(_hMp4, _hVideo, (uint8_t *)pps.data(), pps.size()); + }else{ + WarnL << "添加视频通道失败:" << strFileTmp; + } + } + } auto audioTrack = dynamic_pointer_cast(getTrack(TrackAudio)); if(audioTrack){ _audioSampleRate = audioTrack->getAudioSampleRate(); - _hAudio = MP4AddAudioTrack(_hMp4, _audioSampleRate, MP4_INVALID_DURATION, MP4_MPEG4_AUDIO_TYPE); - if (_hAudio != MP4_INVALID_TRACK_ID) { - auto &cfg = audioTrack->getAacCfg(); - MP4SetTrackESConfiguration(_hMp4, _hAudio,(uint8_t *)cfg.data(), cfg.size()); - }else{ - WarnL << "添加音频通道失败:" << strFileTmp; + _audioChannel = audioTrack->getAudioChannel(); +#ifdef MP4_H265RECORD + uint8_t extra_data[64 * 1024]; + if ( _h265Record ){ + _movH265info.audioTrack = mov_writer_add_audio(_movH265info.pMov, MOV_OBJECT_AAC, _audioChannel, 16, _audioSampleRate, audioTrack->getAacCfg().data(), 2); + if (-1 == _movH265info.audioTrack) + WarnL << "添加音频通道失败:" << strFileTmp; + }else +#endif + { + _hAudio = MP4AddAudioTrack(_hMp4, _audioSampleRate, MP4_INVALID_DURATION, MP4_MPEG4_AUDIO_TYPE); + if (_hAudio != MP4_INVALID_TRACK_ID) { + auto &cfg = audioTrack->getAacCfg(); + MP4SetTrackESConfiguration(_hMp4, _hAudio,(uint8_t *)cfg.data(), cfg.size()); + }else{ + WarnL << "添加音频通道失败:" << strFileTmp; + } } } } void Mp4Maker::asyncClose() { - auto hMp4 = _hMp4; + +// auto hMp4 = (_h265Record==0)?_hMp4:_movH265info.pMov; auto strFileTmp = _strFileTmp; auto strFile = _strFile; auto info = _info; - WorkThreadPool::Instance().getExecutor()->async([hMp4,strFileTmp,strFile,info]() { + + int h265Record = _h265Record; +#ifdef MP4_H265RECORD + FILE *pFile = (_h265Record)?_movH265info.pFile:NULL; + void * hMp4 = (_h265Record)?(void*)_movH265info.pMov:(void*)_hMp4; +#else + auto hMp4 = _hMp4; + FILE *pFile = NULL; +#endif + WorkThreadPool::Instance().getExecutor()->async([hMp4,strFileTmp,strFile,info,pFile,h265Record]() { //获取文件录制时间,放在MP4Close之前是为了忽略MP4Close执行时间 const_cast(info).ui64TimeLen = ::time(NULL) - info.ui64StartedTime; //MP4Close非常耗时,所以要放在后台线程执行 - MP4Close(hMp4,MP4_CLOSE_DO_NOT_COMPUTE_BITRATE); + +#ifdef MP4_H265RECORD + if (h265Record){ + mov_writer_destroy((mov_writer_t*)hMp4); + fclose(pFile); + }else +#endif + { + MP4Close(hMp4,MP4_CLOSE_DO_NOT_COMPUTE_BITRATE); + } //临时文件名改成正式文件名,防止mp4未完成时被访问 rename(strFileTmp.data(),strFile.data()); //获取文件大小 @@ -235,11 +434,20 @@ void Mp4Maker::asyncClose() { } void Mp4Maker::closeFile() { - if (_hMp4 != MP4_INVALID_FILE_HANDLE) { - asyncClose(); - _hMp4 = MP4_INVALID_FILE_HANDLE; - _hVideo = MP4_INVALID_TRACK_ID; - _hAudio = MP4_INVALID_TRACK_ID; +#ifdef MP4_H265RECORD + if (_h265Record){ + if (_movH265info.pMov != NULL) { + asyncClose(); + } + }else +#endif + { + if (_hMp4 != MP4_INVALID_FILE_HANDLE) { + asyncClose(); + _hMp4 = MP4_INVALID_FILE_HANDLE; + _hVideo = MP4_INVALID_TRACK_ID; + _hAudio = MP4_INVALID_TRACK_ID; + } } } @@ -253,7 +461,10 @@ void Mp4Maker::onTrackFrame(const Frame::Ptr &frame) { inputAAC(frame->data() + frame->prefixSize(), frame->size() - frame->prefixSize(),frame->stamp()); } break; - + case CodecH265:{ + inputH265(frame->data() , frame->size(),frame->stamp()); + } + break; default: break; } diff --git a/src/MediaFile/Mp4Maker.h b/src/MediaFile/Mp4Maker.h index f6e41149..447dd636 100644 --- a/src/MediaFile/Mp4Maker.h +++ b/src/MediaFile/Mp4Maker.h @@ -40,6 +40,12 @@ #include "Common/MediaSink.h" #include "Extension/Track.h" + +#ifdef MP4_H265RECORD +#include "mov-writer.h" +#include "mpeg4-hevc.h" +#endif + using namespace toolkit; namespace mediakit { @@ -57,6 +63,22 @@ public: string strStreamId;//流ID string strVhost;//vhost }; + +class MovH265Info { +public: + +#ifdef MP4_H265RECORD + mov_writer_t* pMov; + struct mpeg4_hevc_t hevc; + int videoTrack; + int audioTrack; + int width; + int height; + const uint8_t* ptr; + FILE * pFile; +#endif +}; + class Mp4Maker : public MediaSink{ public: typedef std::shared_ptr Ptr; @@ -82,14 +104,22 @@ private: void asyncClose(); //时间戳:参考频率1000 - void inputH264(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); + void inputH264(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); + void inputH265(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); //时间戳:参考频率1000 void inputAAC(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); - void inputH264_l(void *pData, uint32_t ui32Length, uint32_t ui64Duration); + void inputH264_l(void *pData, uint32_t ui32Length, uint32_t ui64Duration); + void inputH265_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); void inputAAC_l(void *pData, uint32_t ui32Length, uint32_t ui64Duration); private: + + MovH265Info _movH265info; + int _h265Record = 0; + + uint8_t _sBbuffer[2 * 1024 * 1024]; MP4FileHandle _hMp4 = MP4_INVALID_FILE_HANDLE; + MP4TrackId _hVideo = MP4_INVALID_TRACK_ID; MP4TrackId _hAudio = MP4_INVALID_TRACK_ID; string _strPath; @@ -106,6 +136,7 @@ private: bool _haveVideo = false; int _audioSampleRate; + int _audioChannel; }; } /* namespace mediakit */ diff --git a/tests/test_server.cpp b/tests/test_server.cpp index df30a0c8..85fa58a4 100644 --- a/tests/test_server.cpp +++ b/tests/test_server.cpp @@ -180,7 +180,7 @@ void initEventListener() { NoticeCenter::Instance().addListener(nullptr, Broadcast::kBroadcastMediaChanged, [](BroadcastMediaChangedArgs) { if (schema == RTMP_SCHEMA && app == "live") { lock_guard lck(s_mtxFlvRecorder); - if (bRegist) { + if (/*bRegist*/0) { DebugL << "开始录制RTMP:" << schema << " " << vhost << " " << app << " " << stream; GET_CONFIG(string, http_root, Http::kRootPath); auto path = @@ -239,8 +239,9 @@ int main(int argc,char *argv[]) { //这里是拉流地址,支持rtmp/rtsp协议,负载必须是H264+AAC //如果是其他不识别的音视频将会被忽略(譬如说h264+adpcm转发后会去除音频) - auto urlList = {"rtmp://live.hkstv.hk.lxdns.com/live/hks1", - "rtmp://live.hkstv.hk.lxdns.com/live/hks2" + auto urlList = { +// "rtsp://admin:admin123@192.168.5.82/", + "rtsp://192.168.5.24/live/chn0", //rtsp链接支持输入用户名密码 /*"rtsp://admin:jzan123456@192.168.0.122/"*/}; map proxyMap; @@ -259,7 +260,7 @@ int main(int argc,char *argv[]) { //rtsp://127.0.0.1/record/live/0/2017-04-11/11-09-38.mp4 //rtmp://127.0.0.1/record/live/0/2017-04-11/11-09-38.mp4 - PlayerProxy::Ptr player(new PlayerProxy(DEFAULT_VHOST, "live", to_string(i).data())); + PlayerProxy::Ptr player(new PlayerProxy(DEFAULT_VHOST, "live", to_string(i).data(),true,true,true,true)); //指定RTP over TCP(播放rtsp时有效) (*player)[kRtpType] = Rtsp::RTP_TCP; //开始播放,如果播放失败或者播放中止,将会自动重试若干次,重试次数在配置文件中配置,默认一直重试 @@ -276,7 +277,7 @@ int main(int argc,char *argv[]) { " http-flv地址 : http://127.0.0.1/live/0.flv\n" " rtsp地址 : rtsp://127.0.0.1/live/0\n" " rtmp地址 : rtmp://127.0.0.1/live/0"; - +#if 1 //加载证书,证书包含公钥和私钥 SSL_Initor::Instance().loadCertificate((exeDir() + "ssl.p12").data()); //信任某个自签名证书 @@ -293,12 +294,12 @@ int main(int argc,char *argv[]) { //简单的telnet服务器,可用于服务器调试,但是不能使用23端口,否则telnet上了莫名其妙的现象 //测试方法:telnet 127.0.0.1 9000 - TcpServer::Ptr shellSrv(new TcpServer()); +// TcpServer::Ptr shellSrv(new TcpServer()); TcpServer::Ptr rtspSrv(new TcpServer()); TcpServer::Ptr rtmpSrv(new TcpServer()); TcpServer::Ptr httpSrv(new TcpServer()); - shellSrv->start(shellPort); +// shellSrv->start(shellPort); rtspSrv->start(rtspPort);//默认554 rtmpSrv->start(rtmpPort);//默认1935 //http服务器,支持websocket @@ -312,15 +313,17 @@ int main(int argc,char *argv[]) { //支持ssl加密的rtsp服务器,可用于诸如亚马逊echo show这样的设备访问 TcpServer::Ptr rtspSSLSrv(new TcpServer()); rtspSSLSrv->start(rtspsPort);//默认322 - + //服务器支持动态切换端口(不影响现有连接) NoticeCenter::Instance().addListener(ReloadConfigTag,Broadcast::kBroadcastReloadConfig,[&](BroadcastReloadConfigArgs){ //重新创建服务器 +#if 0 if(shellPort != mINI::Instance()[Shell::kPort].as()){ shellPort = mINI::Instance()[Shell::kPort]; shellSrv->start(shellPort); InfoL << "重启shell服务器:" << shellPort; } +#endif if(rtspPort != mINI::Instance()[Rtsp::kPort].as()){ rtspPort = mINI::Instance()[Rtsp::kPort]; rtspSrv->start(rtspPort); @@ -331,6 +334,7 @@ int main(int argc,char *argv[]) { rtmpSrv->start(rtmpPort); InfoL << "重启rtmp服务器" << rtmpPort; } +#if 1 if(httpPort != mINI::Instance()[Http::kPort].as()){ httpPort = mINI::Instance()[Http::kPort]; httpSrv->start(httpPort); @@ -341,6 +345,7 @@ int main(int argc,char *argv[]) { httpsSrv->start(httpsPort); InfoL << "重启https服务器" << httpsPort; } +#endif if(rtspsPort != mINI::Instance()[Rtsp::kSSLPort].as()){ rtspsPort = mINI::Instance()[Rtsp::kSSLPort]; @@ -348,7 +353,7 @@ int main(int argc,char *argv[]) { InfoL << "重启rtsps服务器" << rtspsPort; } }); - +#endif //设置退出信号处理函数 static semaphore sem; signal(SIGINT, [](int) { sem.post(); });// 设置退出信号 From 7e92a0b73855787189619e561411092722d78ba0 Mon Sep 17 00:00:00 2001 From: zqsong Date: Tue, 30 Jul 2019 21:29:31 +0800 Subject: [PATCH 02/30] =?UTF-8?q?MP4=E5=BD=95=E5=88=B6=E6=B7=BB=E5=8A=A0H2?= =?UTF-8?q?65=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Extension/H265.cpp | 27 +++++++++++++++++++++++++++ src/Extension/H265.h | 37 +++++++++++++++++++++++++++++++++++++ tests/test_server.cpp | 23 +++++++++-------------- 3 files changed, 73 insertions(+), 14 deletions(-) diff --git a/src/Extension/H265.cpp b/src/Extension/H265.cpp index 6894264c..5c4aa916 100644 --- a/src/Extension/H265.cpp +++ b/src/Extension/H265.cpp @@ -25,9 +25,36 @@ */ #include "H265.h" +#include "SPSParser.h" +#include "Util/logger.h" namespace mediakit{ + + +bool getAVCH265Info(const string& strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps) { + return getAVC265Info(strSps.data(),strSps.size(),iVideoWidth,iVideoHeight,iVideoFps); + +} + +bool getAVC265Info(const char * sps,int sps_len,int &iVideoWidth, int &iVideoHeight, float &iVideoFps){ + T_GetBitContext tGetBitBuf; + T_HEVCSPS tH265SpsInfo; + memset(&tGetBitBuf,0,sizeof(tGetBitBuf)); + memset(&tH265SpsInfo,0,sizeof(tH265SpsInfo)); + tGetBitBuf.pu8Buf = (uint8_t*)sps ; + tGetBitBuf.iBufSize = sps_len ; + if(0 != h265DecSeqParameterSet((void *) &tGetBitBuf, &tH265SpsInfo)){ + return false; + } + h265GetWidthHeight(&tH265SpsInfo, &iVideoWidth, &iVideoHeight); + h265GeFramerate(&tH265SpsInfo, &iVideoFps); + //ErrorL << iVideoWidth << " " << iVideoHeight << " " << iVideoFps; + return true; +} + + + Sdp::Ptr H265Track::getSdp() { if(!ready()){ WarnL << "H265 Track未准备好"; diff --git a/src/Extension/H265.h b/src/Extension/H265.h index cd367b66..7063d470 100644 --- a/src/Extension/H265.h +++ b/src/Extension/H265.h @@ -36,6 +36,9 @@ using namespace toolkit; namespace mediakit { +bool getAVCH265Info(const string& strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps); +bool getAVC265Info(const char * sps,int sps_len,int &iVideoWidth, int &iVideoHeight, float &iVideoFps); + /** * 265帧类 */ @@ -176,6 +179,7 @@ public: _vps = vps.substr(vps_prefix_len); _sps = sps.substr(sps_prefix_len); _pps = pps.substr(pps_prefix_len); + onReady(); } /** @@ -206,6 +210,30 @@ public: return CodecH265; } + /** + * 返回视频高度 + * @return + */ + int getVideoHeight() const override{ + return _height ; + } + + /** + * 返回视频宽度 + * @return + */ + int getVideoWidth() const override{ + return _width; + } + + /** + * 返回视频fps + * @return + */ + float getVideoFps() const override{ + return _fps; + } + bool ready() override { return !_vps.empty() && !_sps.empty() && !_pps.empty(); } @@ -280,6 +308,12 @@ private: } } + /** + * 解析sps获取宽高fps + */ + void onReady(){ + getAVCH265Info(_sps,_width,_height,_fps); + } Track::Ptr clone() override { return std::make_shared::type>(*this); } @@ -325,6 +359,9 @@ private: string _vps; string _sps; string _pps; + int _width = 0; + int _height = 0; + float _fps = 0; bool _last_frame_is_idr = false; }; diff --git a/tests/test_server.cpp b/tests/test_server.cpp index 85fa58a4..df30a0c8 100644 --- a/tests/test_server.cpp +++ b/tests/test_server.cpp @@ -180,7 +180,7 @@ void initEventListener() { NoticeCenter::Instance().addListener(nullptr, Broadcast::kBroadcastMediaChanged, [](BroadcastMediaChangedArgs) { if (schema == RTMP_SCHEMA && app == "live") { lock_guard lck(s_mtxFlvRecorder); - if (/*bRegist*/0) { + if (bRegist) { DebugL << "开始录制RTMP:" << schema << " " << vhost << " " << app << " " << stream; GET_CONFIG(string, http_root, Http::kRootPath); auto path = @@ -239,9 +239,8 @@ int main(int argc,char *argv[]) { //这里是拉流地址,支持rtmp/rtsp协议,负载必须是H264+AAC //如果是其他不识别的音视频将会被忽略(譬如说h264+adpcm转发后会去除音频) - auto urlList = { -// "rtsp://admin:admin123@192.168.5.82/", - "rtsp://192.168.5.24/live/chn0", + auto urlList = {"rtmp://live.hkstv.hk.lxdns.com/live/hks1", + "rtmp://live.hkstv.hk.lxdns.com/live/hks2" //rtsp链接支持输入用户名密码 /*"rtsp://admin:jzan123456@192.168.0.122/"*/}; map proxyMap; @@ -260,7 +259,7 @@ int main(int argc,char *argv[]) { //rtsp://127.0.0.1/record/live/0/2017-04-11/11-09-38.mp4 //rtmp://127.0.0.1/record/live/0/2017-04-11/11-09-38.mp4 - PlayerProxy::Ptr player(new PlayerProxy(DEFAULT_VHOST, "live", to_string(i).data(),true,true,true,true)); + PlayerProxy::Ptr player(new PlayerProxy(DEFAULT_VHOST, "live", to_string(i).data())); //指定RTP over TCP(播放rtsp时有效) (*player)[kRtpType] = Rtsp::RTP_TCP; //开始播放,如果播放失败或者播放中止,将会自动重试若干次,重试次数在配置文件中配置,默认一直重试 @@ -277,7 +276,7 @@ int main(int argc,char *argv[]) { " http-flv地址 : http://127.0.0.1/live/0.flv\n" " rtsp地址 : rtsp://127.0.0.1/live/0\n" " rtmp地址 : rtmp://127.0.0.1/live/0"; -#if 1 + //加载证书,证书包含公钥和私钥 SSL_Initor::Instance().loadCertificate((exeDir() + "ssl.p12").data()); //信任某个自签名证书 @@ -294,12 +293,12 @@ int main(int argc,char *argv[]) { //简单的telnet服务器,可用于服务器调试,但是不能使用23端口,否则telnet上了莫名其妙的现象 //测试方法:telnet 127.0.0.1 9000 -// TcpServer::Ptr shellSrv(new TcpServer()); + TcpServer::Ptr shellSrv(new TcpServer()); TcpServer::Ptr rtspSrv(new TcpServer()); TcpServer::Ptr rtmpSrv(new TcpServer()); TcpServer::Ptr httpSrv(new TcpServer()); -// shellSrv->start(shellPort); + shellSrv->start(shellPort); rtspSrv->start(rtspPort);//默认554 rtmpSrv->start(rtmpPort);//默认1935 //http服务器,支持websocket @@ -313,17 +312,15 @@ int main(int argc,char *argv[]) { //支持ssl加密的rtsp服务器,可用于诸如亚马逊echo show这样的设备访问 TcpServer::Ptr rtspSSLSrv(new TcpServer()); rtspSSLSrv->start(rtspsPort);//默认322 - + //服务器支持动态切换端口(不影响现有连接) NoticeCenter::Instance().addListener(ReloadConfigTag,Broadcast::kBroadcastReloadConfig,[&](BroadcastReloadConfigArgs){ //重新创建服务器 -#if 0 if(shellPort != mINI::Instance()[Shell::kPort].as()){ shellPort = mINI::Instance()[Shell::kPort]; shellSrv->start(shellPort); InfoL << "重启shell服务器:" << shellPort; } -#endif if(rtspPort != mINI::Instance()[Rtsp::kPort].as()){ rtspPort = mINI::Instance()[Rtsp::kPort]; rtspSrv->start(rtspPort); @@ -334,7 +331,6 @@ int main(int argc,char *argv[]) { rtmpSrv->start(rtmpPort); InfoL << "重启rtmp服务器" << rtmpPort; } -#if 1 if(httpPort != mINI::Instance()[Http::kPort].as()){ httpPort = mINI::Instance()[Http::kPort]; httpSrv->start(httpPort); @@ -345,7 +341,6 @@ int main(int argc,char *argv[]) { httpsSrv->start(httpsPort); InfoL << "重启https服务器" << httpsPort; } -#endif if(rtspsPort != mINI::Instance()[Rtsp::kSSLPort].as()){ rtspsPort = mINI::Instance()[Rtsp::kSSLPort]; @@ -353,7 +348,7 @@ int main(int argc,char *argv[]) { InfoL << "重启rtsps服务器" << rtspsPort; } }); -#endif + //设置退出信号处理函数 static semaphore sem; signal(SIGINT, [](int) { sem.post(); });// 设置退出信号 From 124cce34b63f62f649982e9ed4c934fd2d80ca06 Mon Sep 17 00:00:00 2001 From: zqsong Date: Thu, 1 Aug 2019 11:44:16 +0800 Subject: [PATCH 03/30] =?UTF-8?q?mp4=E5=BD=95=E5=88=B6=E5=85=A8=E9=83=A8?= =?UTF-8?q?=E6=9B=BF=E6=8D=A2mp4v2=E4=B8=BAmedia-server?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 3rdpart/media-server | 2 +- CMakeLists.txt | 45 +++-- src/MediaFile/Mp4Maker.cpp | 402 +++++++++++++++++-------------------- src/MediaFile/Mp4Maker.h | 24 +-- 4 files changed, 232 insertions(+), 241 deletions(-) diff --git a/3rdpart/media-server b/3rdpart/media-server index e399b938..a32fe104 160000 --- a/3rdpart/media-server +++ b/3rdpart/media-server @@ -1 +1 @@ -Subproject commit e399b93802610dcf574ff64bcb7677572cd028c1 +Subproject commit a32fe104c0290bc01a7ee73d50b568e8d9ded931 diff --git a/CMakeLists.txt b/CMakeLists.txt index 84e7383a..35f7c194 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,6 +2,14 @@ cmake_minimum_required(VERSION 3.1.3) #使能c++11 set(CMAKE_CXX_STANDARD 11) +SET(CMAKE_C_COMPILER aarch64-himix100-linux-gcc) +SET(CMAKE_CXX_COMPILER aarch64-himix100-linux-g++) +#SET(CMAKE_LINKER aarch64-himix100-linux-ld) +SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) + + #加载自定义模块 set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${PROJECT_SOURCE_DIR}/cmake") @@ -14,6 +22,7 @@ set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin) set(ToolKit_Root ${CMAKE_SOURCE_DIR}/3rdpart/ZLToolKit/src) set(MediaKit_Root ${CMAKE_SOURCE_DIR}/src) + #设置头文件目录 INCLUDE_DIRECTORIES(${ToolKit_Root}) INCLUDE_DIRECTORIES(${MediaKit_Root}) @@ -32,11 +41,14 @@ endif () set(ENABLE_HLS true) set(ENABLE_OPENSSL true) -set(ENABLE_MYSQL true) +set(ENABLE_MYSQL false) set(ENABLE_MP4V2 true) -set(ENABLE_FAAC true) -set(ENABLE_X264 true) -set(MP4_H265RECORD true) +set(ENABLE_FAAC false) +set(ENABLE_X264 false) +set(ENABLE_MP4RECORD true) + + + #添加两个静态库 if(ENABLE_HLS) @@ -48,19 +60,28 @@ else() set(LINK_LIB_LIST zlmediakit zltoolkit) endif() -if(MP4_H265RECORD) - message(STATUS "MP4_H265RECORD defined") - add_definitions(-DMP4_H265RECORD) +if(ENABLE_MP4RECORD) + message(STATUS "ENABLE_MP4RECORD defined") + add_definitions(-DENABLE_MP4RECORD) set(MediaServer_Root ${CMAKE_SOURCE_DIR}/3rdpart/media-server) list(APPEND LINK_LIB_LIST mov flv) endif() + +set(OPENSSL_INCLUDE_DIR /nand/hi3559/openssl/include/) +set(OPENSSL_LIBRARIES /nand/hi3559/openssl/lib/) +#set(OPENSSL_CRYPTO_LIBRARIES /nand/hi3559/openssl/lib/libcrypto.so) + +set(MP4V2_INCLUDE_DIR /nand/hi3559/mp4v2/include/) +#set(MP4V2_LIBRARY /nand/hi3559/mp4v2/lib/libmp4v2.a) +set(MP4V2_LIBRARY /nand/hi3559/mp4v2/lib/libmp4v2.so) + #查找openssl是否安装 find_package(OpenSSL QUIET) -if (OPENSSL_FOUND AND ENABLE_OPENSSL) +if (1) message(STATUS "found library:${OPENSSL_LIBRARIES},ENABLE_OPENSSL defined") - include_directories(${OPENSSL_INCLUDE_DIR}) + include_directories(/nand/hi3559/openssl/include/) add_definitions(-DENABLE_OPENSSL) - list(APPEND LINK_LIB_LIST ${OPENSSL_LIBRARIES}) + list(APPEND LINK_LIB_LIST /nand/hi3559/openssl/lib/libssl.so /nand/hi3559/openssl/lib/libcrypto.so) endif () #查找mysql是否安装 @@ -111,14 +132,14 @@ set(VS_FALGS "/wd4819 /wd4996 /wd4018 /wd4267 /wd4244 /wd4101 /wd4828 /wd4309 /w if(ENABLE_HLS) aux_source_directory(${MediaServer_Root}/libmpeg/include src_mpeg) aux_source_directory(${MediaServer_Root}/libmpeg/source src_mpeg) - include_directories(${MediaServer_Root}/libmpeg/include) + include_directories(${MediaServer_Root}/libmpeg/include) add_library(mpeg STATIC ${src_mpeg}) if(WIN32) set_target_properties(mpeg PROPERTIES COMPILE_FLAGS ${VS_FALGS} ) endif(WIN32) endif() -if(MP4_H265RECORD) +if(ENABLE_MP4RECORD) aux_source_directory(${MediaServer_Root}/libmov/include src_mov) aux_source_directory(${MediaServer_Root}/libmov/source src_mov) include_directories(${MediaServer_Root}/libmov/include) diff --git a/src/MediaFile/Mp4Maker.cpp b/src/MediaFile/Mp4Maker.cpp index 1c9bd37f..96d6af99 100644 --- a/src/MediaFile/Mp4Maker.cpp +++ b/src/MediaFile/Mp4Maker.cpp @@ -24,7 +24,7 @@ * SOFTWARE. */ -#ifdef ENABLE_MP4V2 +#ifdef ENABLE_MP4RECORD #include #include #include "Common/config.h" @@ -40,10 +40,15 @@ #include "Thread/WorkThreadPool.h" -#ifdef MP4_H265RECORD #include "mov-buffer.h" #include "mov-format.h" + + +using namespace toolkit; + +namespace mediakit { + #if defined(_WIN32) || defined(_WIN64) #define fseek64 _fseeki64 #define ftell64 _ftelli64 @@ -52,43 +57,39 @@ #define ftell64 ftell #endif -static int mov_file_read(void* fp, void* data, uint64_t bytes) +static int movfileRead(void* fp, void* data, uint64_t bytes) { if (bytes == fread(data, 1, bytes, (FILE*)fp)) return 0; return 0 != ferror((FILE*)fp) ? ferror((FILE*)fp) : -1 /*EOF*/; } -static int mov_file_write(void* fp, const void* data, uint64_t bytes) +static int movfileWrite(void* fp, const void* data, uint64_t bytes) { return bytes == fwrite(data, 1, bytes, (FILE*)fp) ? 0 : ferror((FILE*)fp); } -static int mov_file_seek(void* fp, uint64_t offset) +static int movfileSeek(void* fp, uint64_t offset) { return fseek64((FILE*)fp, offset, SEEK_SET); } -static uint64_t mov_file_tell(void* fp) +static uint64_t movfileTell(void* fp) { return ftell64((FILE*)fp); } -const struct mov_buffer_t* mov_file_buffer(void) +const struct mov_buffer_t* movfileBuffer(void) { static struct mov_buffer_t s_io = { - mov_file_read, - mov_file_write, - mov_file_seek, - mov_file_tell, + movfileRead, + movfileWrite, + movfileSeek, + movfileTell, }; return &s_io; } -#endif -using namespace toolkit; - -namespace mediakit { string timeStr(const char *fmt) { std::tm tm_snapshot; @@ -118,6 +119,11 @@ Mp4Maker::Mp4Maker(const string& strPath, _info.strStreamId = strStreamId; _info.strVhost = strVhost; _info.strFolder = strPath; + + memset(&_movH265info, 0, sizeof(_movH265info)); + _movH265info.videoTrack = -1; + _movH265info.audioTrack = -1; + //----record 业务逻辑----// } Mp4Maker::~Mp4Maker() { @@ -125,105 +131,140 @@ Mp4Maker::~Mp4Maker() { } void Mp4Maker::inputH264(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp){ - auto iType = H264_TYPE(((uint8_t*)pData)[0]); - switch (iType) { - case H264Frame::NAL_B_P: //P - case H264Frame::NAL_IDR: { //IDR - if (_strLastVideo.size()) { - int64_t iTimeInc = (int64_t)ui32TimeStamp - (int64_t)_ui32LastVideoTime; - iTimeInc = MAX(0,MIN(iTimeInc,500)); - if(iTimeInc == 0 || iTimeInc == 500){ - WarnL << "abnormal time stamp increment:" << ui32TimeStamp << " " << _ui32LastVideoTime; - } - inputH264_l((char *) _strLastVideo.data(), _strLastVideo.size(), iTimeInc); - } - - uint32_t prefixe = htonl(ui32Length); - _strLastVideo.assign((char *) &prefixe, 4); - _strLastVideo.append((char *)pData,ui32Length); + auto iType = H264_TYPE(((uint8_t*)pData)[4]); + + if (H264Frame::NAL_B_P <= iType && iType <= H264Frame::NAL_IDR){ + int64_t iTimeInc = (int64_t)ui32TimeStamp - (int64_t)_ui32LastVideoTime; + iTimeInc = MAX(0,MIN(iTimeInc,500)); + if( (iTimeInc == 0 || iTimeInc == 500) && H264Frame::NAL_IDR != iType){ + WarnL << "abnormal time stamp increment:" << ui32TimeStamp << " " << _ui32LastVideoTime; + } + + if ( _strLastVideo.size() ){ + //如果出现SPS PPS黏连的帧,那么在这里先处理 + inputH264_l((char *) _strLastVideo.data(), _strLastVideo.size(), _ui32LastVideoTime); + _strLastVideo = ""; + } + inputH264_l((char *) pData, ui32Length, ui32TimeStamp); + _ui32LastVideoTime = ui32TimeStamp; + }else{ + //SPS PPS 进入等待组合为一帧 + _strLastVideo.append((char *)pData,ui32Length); _ui32LastVideoTime = ui32TimeStamp; - } - break; - default: - break; } } void Mp4Maker::inputH265(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp){ -#ifdef MP4_H265RECORD + auto iType = H265_TYPE(((uint8_t*)pData)[4]); - if (iType <= 19 ){ - if (_strLastVideo.size() && iType == 19){ - _strLastVideo.append((char *)pData,ui32Length); - inputH265_l((char *) _strLastVideo.data(), _strLastVideo.size(), ui32TimeStamp); + if (iType <= H265Frame::NAL_IDR_W_RADL ){ + + int64_t iTimeInc = (int64_t)ui32TimeStamp - (int64_t)_ui32LastVideoTime; + iTimeInc = MAX(0,MIN(iTimeInc,500)); + if((iTimeInc == 0 || iTimeInc == 500) && H265Frame::NAL_IDR_W_RADL != iType){ + WarnL << "abnormal time stamp increment:" << ui32TimeStamp << " " << _ui32LastVideoTime; + } + + if ( _strLastVideo.size() ){ + //如果出现SPS PPS VPS黏连的帧,那么在这里先处理 + inputH265_l((char *) _strLastVideo.data(), _strLastVideo.size(), _ui32LastVideoTime); _strLastVideo = ""; - _ui32LastVideoTime = ui32TimeStamp; - }else - inputH265_l((char *) pData, ui32Length, ui32TimeStamp); + } + inputH265_l((char *) pData, ui32Length, ui32TimeStamp); + _ui32LastVideoTime = ui32TimeStamp; }else{ _strLastVideo.append((char *)pData,ui32Length); _ui32LastVideoTime = ui32TimeStamp; } -#endif } -void Mp4Maker::inputAAC(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp){ -#ifdef MP4_H265RECORD - if (_h265Record){ - inputAAC_l((char *) pData, ui32Length, ui32TimeStamp); - }else -#endif - { - if (_strLastAudio.size()) { - int64_t iTimeInc = (int64_t)ui32TimeStamp - (int64_t)_ui32LastAudioTime; - iTimeInc = MAX(0,MIN(iTimeInc,500)); - if(iTimeInc == 0 || iTimeInc == 500){ - WarnL << "abnormal time stamp increment:" << ui32TimeStamp << " " << _ui32LastAudioTime; - } - inputAAC_l((char *) _strLastAudio.data(), _strLastAudio.size(), iTimeInc); - } - _strLastAudio.assign((char *)pData, ui32Length); - _ui32LastAudioTime = ui32TimeStamp; - } - - - +void Mp4Maker::inputAAC(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp){ + int64_t iTimeInc = (int64_t)ui32TimeStamp - (int64_t)_ui32LastAudioTime; + iTimeInc = MAX(0,MIN(iTimeInc,500)); + if(iTimeInc == 0 || iTimeInc == 500){ + WarnL << "abnormal time stamp increment:" << ui32TimeStamp << " " << _ui32LastAudioTime; + } + inputAAC_l((char *) pData, ui32Length, ui32TimeStamp); + _ui32LastAudioTime = ui32TimeStamp; } -void Mp4Maker::inputH264_l(void *pData, uint32_t ui32Length, uint32_t ui32Duration) { +void Mp4Maker::inputH264_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp) { GET_CONFIG(uint32_t,recordSec,Record::kFileSecond); auto iType = H264_TYPE(((uint8_t*)pData)[4]); - if(iType == H264Frame::NAL_IDR && (_hMp4 == MP4_INVALID_FILE_HANDLE || _ticker.elapsedTime() > recordSec * 1000)){ + int32_t compositionTime; + if( iType >= H264Frame::NAL_IDR && (_movH265info.pMov == NULL || _ticker.elapsedTime() > recordSec * 1000)){ //在I帧率处新建MP4文件 //如果文件未创建或者文件超过10分钟则创建新文件 - createFile(); + //每一个录制的MP4文件时间戳都要从0开始 + _startPts = ui32TimeStamp; + createFile(); } - if (_hVideo != MP4_INVALID_TRACK_ID) { - MP4WriteSample(_hMp4, _hVideo, (uint8_t *) pData, ui32Length,ui32Duration * 90,0,iType == 5); + + char *pNualData = (char *)pData; + if (_movH265info.pMov!=NULL){ + int vcl; + if (_movH265info.videoTrack < 0){ + //解析解析SPS PPS,未添加track的时候执行 + int n = h264_annexbtomp4(&_movH265info.avc, pData, ui32Length, _sBbuffer, sizeof(_sBbuffer), &vcl); + if (_movH265info.avc.nb_sps < 1 || _movH265info.avc.nb_pps < 1){ + return; // waiting for sps/pps + } + + uint8_t sExtraData[64 * 1024]; + int extraDataSize = mpeg4_avc_decoder_configuration_record_save(&_movH265info.avc, sExtraData, sizeof(sExtraData)); + if (extraDataSize <= 0){ + // invalid HVCC + return; + } + + // TODO: waiting for key frame ??? + _movH265info.videoTrack = mov_writer_add_video(_movH265info.pMov, + MOV_OBJECT_H264, + _movH265info.width, + _movH265info.height, + sExtraData, + extraDataSize); + return; + } + if ( iType <= H264Frame::NAL_IDR ){ + uint8_t *ptr = (uint8_t*)pData; + ptr[0] = (uint8_t)((ui32Length-4 >> 24) & 0xFF); + ptr[1] = (uint8_t)((ui32Length-4 >> 16) & 0xFF); + ptr[2] = (uint8_t)((ui32Length-4 >> 8) & 0xFF); + ptr[3] = (uint8_t)((ui32Length-4 >> 0) & 0xFF); + uint32_t ui32Pts = ui32TimeStamp < _movH265info.startPts ? 0 : ui32TimeStamp-_movH265info.startPts; + mov_writer_write(_movH265info.pMov, + _movH265info.videoTrack, pData, ui32Length, + ui32Pts, + ui32Pts, + iType == H264Frame::NAL_IDR ? MOV_AV_FLAG_KEYFREAME : 0); + } } + } void Mp4Maker::inputH265_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp) { GET_CONFIG(uint32_t,recordSec,Record::kFileSecond); -#ifdef MP4_H265RECORD int32_t compositionTime; auto iType = H265_TYPE(((uint8_t*)pData)[4]); if( iType >= H265Frame::NAL_IDR_W_RADL && (_movH265info.pMov == NULL || _ticker.elapsedTime() > recordSec * 1000)){ - //在I帧率处新建MP4文件 - //如果文件未创建或者文件超过10分钟则创建新文件 _h265Record = 1; + //每一个录制的MP4文件时间戳都要从0开始 + _startPts = ui32TimeStamp; + + //在I帧率处新建MP4文件 + //如果文件未创建或者文件超过最长时间则创建新文件 createFile(); } char *pNualData = (char *)pData; - if (/*iType <= 31 && */_movH265info.pMov!=NULL){ + if (_movH265info.pMov!=NULL){ int vcl; - //media-server新版的api使用h265_annexbtomp4 - //int n = h265_annexbtomp4(&_movH265info.hevc, pData, ui32Length, _sBbuffer, sizeof(_sBbuffer), &vcl); - int n = hevc_annexbtomp4(&_movH265info.hevc, pData, ui32Length, _sBbuffer, sizeof(_sBbuffer)); if (_movH265info.videoTrack < 0){ + //解析解析VPS SPS PPS,未添加track的时候执行 + int n = h265_annexbtomp4(&_movH265info.hevc, pData, ui32Length, _sBbuffer, sizeof(_sBbuffer), &vcl); if (_movH265info.hevc.numOfArrays < 1){ return; // waiting for vps/sps/pps } @@ -234,55 +275,49 @@ void Mp4Maker::inputH265_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeSt // invalid HVCC return; } - // TODO: waiting for key frame ??? _movH265info.videoTrack = mov_writer_add_video(_movH265info.pMov, MOV_OBJECT_HEVC, _movH265info.width, _movH265info.height, sExtraData, extraDataSize); - if (_movH265info.videoTrack < 0) - return; + + return; + } + if ( iType <= H265Frame::NAL_IDR_W_RADL ) + { + uint8_t *ptr = (uint8_t*)pData; + ptr[0] = (uint8_t)((ui32Length-4 >> 24) & 0xFF); + ptr[1] = (uint8_t)((ui32Length-4 >> 16) & 0xFF); + ptr[2] = (uint8_t)((ui32Length-4 >> 8) & 0xFF); + ptr[3] = (uint8_t)((ui32Length-4 >> 0) & 0xFF); + + uint32_t ui32Pts = ui32TimeStamp < _movH265info.startPts ? 0 : ui32TimeStamp-_movH265info.startPts; + mov_writer_write(_movH265info.pMov, + _movH265info.videoTrack, + pData, + ui32Length, + ui32Pts, + ui32Pts, + iType == H265Frame::NAL_IDR_W_RADL ? MOV_AV_FLAG_KEYFREAME : 0); } - mov_writer_write(_movH265info.pMov, - _movH265info.videoTrack, - _sBbuffer, - n, - ui32TimeStamp, - ui32TimeStamp, - (iType >= 16 && iType <= 23) ? MOV_AV_FLAG_KEYFREAME : 0 ); -// mov_writer_write(_movH265info.pMov, _movH265info.videoTrack, _sBbuffer, n, ui32TimeStamp, ui32TimeStamp, 1 == vcl ? MOV_AV_FLAG_KEYFREAME : 0); } -#endif } -void Mp4Maker::inputAAC_l(void *pData, uint32_t ui32Length, uint32_t ui32Duration) { +void Mp4Maker::inputAAC_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp) { GET_CONFIG(uint32_t,recordSec,Record::kFileSecond); -#ifdef MP4_H265RECORD - if ( _h265Record ) - { - if (!_haveVideo && (_movH265info.pMov == NULL || _ticker.elapsedTime() > recordSec * 1000)) { - createFile(); - } - - if (-1 != _movH265info.audioTrack && _movH265info.pMov != NULL){ - mov_writer_write(_movH265info.pMov, _movH265info.audioTrack, (uint8_t*)pData, ui32Length, ui32Duration, ui32Duration, 0); - } - }else -#endif - { - if (!_haveVideo && (_hMp4 == MP4_INVALID_FILE_HANDLE || _ticker.elapsedTime() > recordSec * 1000)) { - //在I帧率处新建MP4文件 - //如果文件未创建或者文件超过10分钟则创建新文件 - createFile(); - } - if (_hAudio != MP4_INVALID_TRACK_ID) { - auto duration = ui32Duration * _audioSampleRate /1000.0; - MP4WriteSample(_hMp4, _hAudio, (uint8_t*)pData, ui32Length,duration,0,false); - } + if (!_haveVideo && (_movH265info.pMov == NULL || _ticker.elapsedTime() > recordSec * 1000)) { + _startPts = ui32TimeStamp; + createFile(); } + + if (-1 != _movH265info.audioTrack && _movH265info.pMov != NULL){ + + uint32_t ui32Pts = ui32TimeStamp < _movH265info.startPts ? 0 : ui32TimeStamp-_movH265info.startPts; + mov_writer_write(_movH265info.pMov, _movH265info.audioTrack, (uint8_t*)pData, ui32Length, ui32Pts, ui32Pts, 0); + } + } void Mp4Maker::createFile() { closeFile(); - auto strDate = timeStr("%Y-%m-%d"); auto strTime = timeStr("%H-%M-%S"); auto strFileTmp = _strPath + strDate + "/." + strTime + ".mp4"; @@ -309,119 +344,65 @@ void Mp4Maker::createFile() { File::createfile_path(strFileTmp.data(), 0); #endif -#ifdef MP4_H265RECORD - if ( _h265Record ){ - memset(&_movH265info, 0, sizeof(_movH265info)); - _movH265info.videoTrack = -1; - _movH265info.audioTrack = -1; - _movH265info.width = 0; - _movH265info.height = 0; - _movH265info.ptr = NULL; - _movH265info.pFile = fopen(strFileTmp.data(), "wb+"); - _movH265info.pMov = mov_writer_create(mov_file_buffer(), _movH265info.pFile, 0/*MOV_FLAG_FASTSTART*/); - }else -#endif - { - _hMp4 = MP4Create(strFileTmp.data(),MP4_CREATE_64BIT_DATA); - if (_hMp4 == MP4_INVALID_FILE_HANDLE) { - WarnL << "创建MP4文件失败:" << strFileTmp; - return; - } - } + memset(&_movH265info, 0, sizeof(_movH265info)); + _movH265info.videoTrack = -1; + _movH265info.audioTrack = -1; + _movH265info.width = 0; + _movH265info.height = 0; + _movH265info.pFile = fopen(strFileTmp.data(), "wb+"); + _movH265info.startPts = _startPts; + _movH265info.pMov = mov_writer_create(movfileBuffer(), _movH265info.pFile, 0/*MOV_FLAG_FASTSTART*/); - //MP4SetTimeScale(_hMp4, 90000); _strFileTmp = strFileTmp; _strFile = strFile; _ticker.resetTime(); if ( _h265Record ){ auto videoTrack = dynamic_pointer_cast(getTrack(TrackVideo)); -#ifdef MP4_H265RECORD if(videoTrack){ _movH265info.width = videoTrack->getVideoWidth(); _movH265info.height = videoTrack->getVideoHeight(); } -#endif - - }else { + }else{ auto videoTrack = dynamic_pointer_cast(getTrack(TrackVideo)); if(videoTrack){ - auto &sps = videoTrack->getSps(); - auto &pps = videoTrack->getPps(); - - - _hVideo = MP4AddH264VideoTrack(_hMp4, - 90000, - MP4_INVALID_DURATION, - videoTrack->getVideoWidth(), - videoTrack->getVideoHeight(), - sps[1], - sps[2], - sps[3], - 3); - if(_hVideo != MP4_INVALID_TRACK_ID){ - MP4AddH264SequenceParameterSet(_hMp4, _hVideo, (uint8_t *)sps.data(), sps.size()); - MP4AddH264PictureParameterSet(_hMp4, _hVideo, (uint8_t *)pps.data(), pps.size()); - }else{ - WarnL << "添加视频通道失败:" << strFileTmp; - } - } - +// auto &sps = videoTrack->getSps(); +// auto &pps = videoTrack->getPps(); + _movH265info.width = videoTrack->getVideoWidth(); + _movH265info.height = videoTrack->getVideoHeight(); + } } + if ( _movH265info.width <=0 || _movH265info.height <= 0 ) + WarnL << "分辨率获取失败,MP4录制异常"; auto audioTrack = dynamic_pointer_cast(getTrack(TrackAudio)); if(audioTrack){ _audioSampleRate = audioTrack->getAudioSampleRate(); _audioChannel = audioTrack->getAudioChannel(); -#ifdef MP4_H265RECORD - uint8_t extra_data[64 * 1024]; - if ( _h265Record ){ - _movH265info.audioTrack = mov_writer_add_audio(_movH265info.pMov, MOV_OBJECT_AAC, _audioChannel, 16, _audioSampleRate, audioTrack->getAacCfg().data(), 2); - if (-1 == _movH265info.audioTrack) - WarnL << "添加音频通道失败:" << strFileTmp; - }else -#endif - { - _hAudio = MP4AddAudioTrack(_hMp4, _audioSampleRate, MP4_INVALID_DURATION, MP4_MPEG4_AUDIO_TYPE); - if (_hAudio != MP4_INVALID_TRACK_ID) { - auto &cfg = audioTrack->getAacCfg(); - MP4SetTrackESConfiguration(_hMp4, _hAudio,(uint8_t *)cfg.data(), cfg.size()); - }else{ - WarnL << "添加音频通道失败:" << strFileTmp; - } - } + uint8_t extra_data[64 * 1024]; + _movH265info.audioTrack = mov_writer_add_audio(_movH265info.pMov, MOV_OBJECT_AAC, _audioChannel, 16, _audioSampleRate, audioTrack->getAacCfg().data(), 2); + if (-1 == _movH265info.audioTrack) + WarnL << "添加音频通道失败:" << strFileTmp; } } void Mp4Maker::asyncClose() { - -// auto hMp4 = (_h265Record==0)?_hMp4:_movH265info.pMov; auto strFileTmp = _strFileTmp; auto strFile = _strFile; auto info = _info; - int h265Record = _h265Record; -#ifdef MP4_H265RECORD - FILE *pFile = (_h265Record)?_movH265info.pFile:NULL; - void * hMp4 = (_h265Record)?(void*)_movH265info.pMov:(void*)_hMp4; -#else - auto hMp4 = _hMp4; - FILE *pFile = NULL; -#endif - WorkThreadPool::Instance().getExecutor()->async([hMp4,strFileTmp,strFile,info,pFile,h265Record]() { + FILE *pFile = _movH265info.pFile; + mov_writer_t* hMp4 = _movH265info.pMov; + WorkThreadPool::Instance().getExecutor()->async([hMp4,strFileTmp,strFile,info,pFile]() { //获取文件录制时间,放在MP4Close之前是为了忽略MP4Close执行时间 const_cast(info).ui64TimeLen = ::time(NULL) - info.ui64StartedTime; //MP4Close非常耗时,所以要放在后台线程执行 - -#ifdef MP4_H265RECORD - if (h265Record){ - mov_writer_destroy((mov_writer_t*)hMp4); + if (hMp4 != NULL ){ + mov_writer_destroy(hMp4); fclose(pFile); - }else -#endif - { - MP4Close(hMp4,MP4_CLOSE_DO_NOT_COMPUTE_BITRATE); + DebugL << "fclose end"; } + //临时文件名改成正式文件名,防止mp4未完成时被访问 rename(strFileTmp.data(),strFile.data()); //获取文件大小 @@ -434,35 +415,30 @@ void Mp4Maker::asyncClose() { } void Mp4Maker::closeFile() { -#ifdef MP4_H265RECORD - if (_h265Record){ - if (_movH265info.pMov != NULL) { - asyncClose(); - } - }else -#endif - { - if (_hMp4 != MP4_INVALID_FILE_HANDLE) { - asyncClose(); - _hMp4 = MP4_INVALID_FILE_HANDLE; - _hVideo = MP4_INVALID_TRACK_ID; - _hAudio = MP4_INVALID_TRACK_ID; - } - } + if (_movH265info.pMov != NULL) { + asyncClose(); + memset(&_movH265info, 0, sizeof(_movH265info)); + _movH265info.pMov = NULL; + _movH265info.videoTrack = -1; + _movH265info.audioTrack = -1; + } } void Mp4Maker::onTrackFrame(const Frame::Ptr &frame) { switch (frame->getCodecId()){ case CodecH264:{ - inputH264(frame->data() + frame->prefixSize(), frame->size() - frame->prefixSize(),frame->stamp()); + //需要带00 00 00 01,方便在mov_writer_write的时候字节修改这4Byte为长度信息 + inputH264(frame->data() , frame->size(),frame->pts()); } break; case CodecAAC:{ - inputAAC(frame->data() + frame->prefixSize(), frame->size() - frame->prefixSize(),frame->stamp()); + //不需要ADTS头 + inputAAC(frame->data() + frame->prefixSize(), frame->size() - frame->prefixSize(),frame->pts()); } break; case CodecH265:{ - inputH265(frame->data() , frame->size(),frame->stamp()); + //需要带00 00 00 01,方便在mov_writer_write的时候字节修改这4Byte为长度信息 + inputH265(frame->data() , frame->size(),frame->pts()); } break; default: @@ -477,4 +453,4 @@ void Mp4Maker::onAllTrackReady() { } /* namespace mediakit */ -#endif //ENABLE_MP4V2 +#endif //ENABLE_MP4RECORD \ No newline at end of file diff --git a/src/MediaFile/Mp4Maker.h b/src/MediaFile/Mp4Maker.h index 447dd636..4967690d 100644 --- a/src/MediaFile/Mp4Maker.h +++ b/src/MediaFile/Mp4Maker.h @@ -27,11 +27,10 @@ #ifndef MP4MAKER_H_ #define MP4MAKER_H_ -#ifdef ENABLE_MP4V2 +#ifdef ENABLE_MP4RECORD #include #include -#include #include "Player/PlayerBase.h" #include "Util/util.h" #include "Util/logger.h" @@ -41,10 +40,10 @@ #include "Extension/Track.h" -#ifdef MP4_H265RECORD #include "mov-writer.h" #include "mpeg4-hevc.h" -#endif +#include "mpeg4-avc.h" + using namespace toolkit; @@ -66,17 +65,15 @@ public: class MovH265Info { public: - -#ifdef MP4_H265RECORD mov_writer_t* pMov; struct mpeg4_hevc_t hevc; + struct mpeg4_avc_t avc; int videoTrack; int audioTrack; int width; int height; - const uint8_t* ptr; + uint32_t startPts; FILE * pFile; -#endif }; class Mp4Maker : public MediaSink{ @@ -109,19 +106,16 @@ private: //时间戳:参考频率1000 void inputAAC(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); - void inputH264_l(void *pData, uint32_t ui32Length, uint32_t ui64Duration); + void inputH264_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); void inputH265_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); - void inputAAC_l(void *pData, uint32_t ui32Length, uint32_t ui64Duration); + void inputAAC_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); private: MovH265Info _movH265info; int _h265Record = 0; + uint32_t _startPts; uint8_t _sBbuffer[2 * 1024 * 1024]; - MP4FileHandle _hMp4 = MP4_INVALID_FILE_HANDLE; - - MP4TrackId _hVideo = MP4_INVALID_TRACK_ID; - MP4TrackId _hAudio = MP4_INVALID_TRACK_ID; string _strPath; string _strFile; string _strFileTmp; @@ -141,6 +135,6 @@ private: } /* namespace mediakit */ -#endif ///ENABLE_MP4V2 +#endif ///ENABLE_MP4RECORD #endif /* MP4MAKER_H_ */ From 776dd4c085e243128ec72a23372bf19e3555884e Mon Sep 17 00:00:00 2001 From: zqsong Date: Thu, 1 Aug 2019 11:47:30 +0800 Subject: [PATCH 04/30] =?UTF-8?q?=E6=81=A2=E5=A4=8DCMakeLists.txt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CMakeLists.txt | 35 +++++++---------------------------- 1 file changed, 7 insertions(+), 28 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 35f7c194..4c2861c0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,14 +2,6 @@ cmake_minimum_required(VERSION 3.1.3) #使能c++11 set(CMAKE_CXX_STANDARD 11) -SET(CMAKE_C_COMPILER aarch64-himix100-linux-gcc) -SET(CMAKE_CXX_COMPILER aarch64-himix100-linux-g++) -#SET(CMAKE_LINKER aarch64-himix100-linux-ld) -SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) - - #加载自定义模块 set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${PROJECT_SOURCE_DIR}/cmake") @@ -22,7 +14,6 @@ set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin) set(ToolKit_Root ${CMAKE_SOURCE_DIR}/3rdpart/ZLToolKit/src) set(MediaKit_Root ${CMAKE_SOURCE_DIR}/src) - #设置头文件目录 INCLUDE_DIRECTORIES(${ToolKit_Root}) INCLUDE_DIRECTORIES(${MediaKit_Root}) @@ -41,15 +32,12 @@ endif () set(ENABLE_HLS true) set(ENABLE_OPENSSL true) -set(ENABLE_MYSQL false) +set(ENABLE_MYSQL true) set(ENABLE_MP4V2 true) -set(ENABLE_FAAC false) -set(ENABLE_X264 false) +set(ENABLE_FAAC true) +set(ENABLE_X264 true) set(ENABLE_MP4RECORD true) - - - #添加两个静态库 if(ENABLE_HLS) message(STATUS "ENABLE_HLS defined") @@ -66,22 +54,13 @@ if(ENABLE_MP4RECORD) set(MediaServer_Root ${CMAKE_SOURCE_DIR}/3rdpart/media-server) list(APPEND LINK_LIB_LIST mov flv) endif() - -set(OPENSSL_INCLUDE_DIR /nand/hi3559/openssl/include/) -set(OPENSSL_LIBRARIES /nand/hi3559/openssl/lib/) -#set(OPENSSL_CRYPTO_LIBRARIES /nand/hi3559/openssl/lib/libcrypto.so) - -set(MP4V2_INCLUDE_DIR /nand/hi3559/mp4v2/include/) -#set(MP4V2_LIBRARY /nand/hi3559/mp4v2/lib/libmp4v2.a) -set(MP4V2_LIBRARY /nand/hi3559/mp4v2/lib/libmp4v2.so) - #查找openssl是否安装 find_package(OpenSSL QUIET) -if (1) +if (OPENSSL_FOUND AND ENABLE_OPENSSL) message(STATUS "found library:${OPENSSL_LIBRARIES},ENABLE_OPENSSL defined") - include_directories(/nand/hi3559/openssl/include/) + include_directories(${OPENSSL_INCLUDE_DIR}) add_definitions(-DENABLE_OPENSSL) - list(APPEND LINK_LIB_LIST /nand/hi3559/openssl/lib/libssl.so /nand/hi3559/openssl/lib/libcrypto.so) + list(APPEND LINK_LIB_LIST ${OPENSSL_LIBRARIES}) endif () #查找mysql是否安装 @@ -132,7 +111,7 @@ set(VS_FALGS "/wd4819 /wd4996 /wd4018 /wd4267 /wd4244 /wd4101 /wd4828 /wd4309 /w if(ENABLE_HLS) aux_source_directory(${MediaServer_Root}/libmpeg/include src_mpeg) aux_source_directory(${MediaServer_Root}/libmpeg/source src_mpeg) - include_directories(${MediaServer_Root}/libmpeg/include) + include_directories(${MediaServer_Root}/libmpeg/include) add_library(mpeg STATIC ${src_mpeg}) if(WIN32) set_target_properties(mpeg PROPERTIES COMPILE_FLAGS ${VS_FALGS} ) From e13ae419ae5ed5957169a8ce9ea5e8f88419efa8 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Thu, 1 Aug 2019 14:39:09 +0800 Subject: [PATCH 05/30] =?UTF-8?q?=E7=B2=BE=E7=AE=80H264Frame=E5=AF=B9?= =?UTF-8?q?=E8=B1=A1=EF=BC=8C=E5=88=A0=E9=99=A4=E5=A4=9A=E4=BD=99=E5=AD=97?= =?UTF-8?q?=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 3rdpart/media-server | 2 +- src/Extension/H264.h | 6 +---- src/Extension/H264Rtmp.cpp | 1 - src/Extension/H264Rtp.cpp | 46 ++++++++++++++++++-------------------- src/Extension/H264Rtp.h | 1 + 5 files changed, 25 insertions(+), 31 deletions(-) diff --git a/3rdpart/media-server b/3rdpart/media-server index e399b938..a32fe104 160000 --- a/3rdpart/media-server +++ b/3rdpart/media-server @@ -1 +1 @@ -Subproject commit e399b93802610dcf574ff64bcb7677572cd028c1 +Subproject commit a32fe104c0290bc01a7ee73d50b568e8d9ded931 diff --git a/src/Extension/H264.h b/src/Extension/H264.h index 400f5474..54e28e07 100644 --- a/src/Extension/H264.h +++ b/src/Extension/H264.h @@ -80,13 +80,11 @@ public: } bool keyFrame() const override { - return type == NAL_IDR; + return H264_TYPE(buffer[iPrefixSize]) == H264Frame::NAL_IDR; } public: - uint16_t sequence; uint32_t timeStamp; uint32_t ptsStamp = 0; - unsigned char type; string buffer; uint32_t iPrefixSize = 4; }; @@ -326,7 +324,6 @@ private: if(!_sps.empty()){ auto spsFrame = std::make_shared(); - spsFrame->type = H264Frame::NAL_SPS; spsFrame->iPrefixSize = 4; spsFrame->buffer.assign("\x0\x0\x0\x1",4); spsFrame->buffer.append(_sps); @@ -336,7 +333,6 @@ private: if(!_pps.empty()){ auto ppsFrame = std::make_shared(); - ppsFrame->type = H264Frame::NAL_PPS; ppsFrame->iPrefixSize = 4; ppsFrame->buffer.assign("\x0\x0\x0\x1",4); ppsFrame->buffer.append(_pps); diff --git a/src/Extension/H264Rtmp.cpp b/src/Extension/H264Rtmp.cpp index 9ff10e27..2f56b9e6 100644 --- a/src/Extension/H264Rtmp.cpp +++ b/src/Extension/H264Rtmp.cpp @@ -80,7 +80,6 @@ bool H264RtmpDecoder::decodeRtmp(const RtmpPacket::Ptr &pkt) { inline void H264RtmpDecoder::onGetH264(const char* pcData, int iLen, uint32_t dts,uint32_t pts) { #if 1 - _h264frame->type = H264_TYPE(pcData[0]); _h264frame->timeStamp = dts; _h264frame->ptsStamp = pts; _h264frame->buffer.assign("\x0\x0\x0\x1", 4); //添加264头 diff --git a/src/Extension/H264Rtp.cpp b/src/Extension/H264Rtp.cpp index 7dd58c47..51581c6c 100644 --- a/src/Extension/H264Rtp.cpp +++ b/src/Extension/H264Rtp.cpp @@ -100,12 +100,10 @@ bool H264RtpDecoder::decodeRtp(const RtpPacket::Ptr &rtppack) { //a full frame _h264frame->buffer.assign("\x0\x0\x0\x1", 4); _h264frame->buffer.append((char *)frame, length); - _h264frame->type = nal.type; _h264frame->timeStamp = rtppack->timeStamp; - _h264frame->sequence = rtppack->sequence; - auto isIDR = _h264frame->type == H264Frame::NAL_IDR; + auto key = _h264frame->keyFrame(); onGetH264(_h264frame); - return (isIDR); //i frame + return (key); //i frame } switch (nal.type){ @@ -131,9 +129,7 @@ bool H264RtpDecoder::decodeRtp(const RtpPacket::Ptr &rtppack) { MakeNalu(ptr[0], nal); _h264frame->buffer.assign("\x0\x0\x0\x1", 4); _h264frame->buffer.append((char *)ptr, len); - _h264frame->type = nal.type; _h264frame->timeStamp = rtppack->timeStamp; - _h264frame->sequence = rtppack->sequence; if(nal.type == H264Frame::NAL_IDR){ haveIDR = true; } @@ -148,35 +144,39 @@ bool H264RtpDecoder::decodeRtp(const RtpPacket::Ptr &rtppack) { //FU-A FU fu; MakeFU(frame[1], fu); - if (fu.S == 1) { - //FU-A start + if (fu.S) { + //该帧的第一个rtp包 char tmp = (nal.forbidden_zero_bit << 7 | nal.nal_ref_idc << 5 | fu.type); _h264frame->buffer.assign("\x0\x0\x0\x1", 4); _h264frame->buffer.push_back(tmp); _h264frame->buffer.append((char *)frame + 2, length - 2); - _h264frame->type = fu.type; _h264frame->timeStamp = rtppack->timeStamp; - _h264frame->sequence = rtppack->sequence; - return (_h264frame->type == H264Frame::NAL_IDR); //i frame + //该函数return时,保存下当前sequence,以便下次对比seq是否连续 + _lastSeq = rtppack->sequence; + return _h264frame->keyFrame(); } - if (rtppack->sequence != (uint16_t)(_h264frame->sequence + 1)) { + if (rtppack->sequence != _lastSeq + 1 && rtppack->sequence != 0) { + //中间的或末尾的rtp包,其seq必须连续(如果回环了则判定为连续),否则说明rtp丢包,那么该帧不完整,必须得丢弃 _h264frame->buffer.clear(); - WarnL << "丢包,帧废弃:" << rtppack->sequence << "," << _h264frame->sequence; + WarnL << "rtp sequence不连续: " << rtppack->sequence << " != " << _lastSeq << " + 1,该帧被废弃"; return false; } - _h264frame->sequence = rtppack->sequence; - if (fu.E == 1) { - //FU-A end + + if (!fu.E) { + //该帧的中间rtp包 _h264frame->buffer.append((char *)frame + 2, length - 2); - _h264frame->timeStamp = rtppack->timeStamp; - auto isIDR = _h264frame->type == H264Frame::NAL_IDR; - onGetH264(_h264frame); - return isIDR; + //该函数return时,保存下当前sequence,以便下次对比seq是否连续 + _lastSeq = rtppack->sequence; + return false; } - //FU-A mid + + //该帧最后一个rtp包 _h264frame->buffer.append((char *)frame + 2, length - 2); - return false; + _h264frame->timeStamp = rtppack->timeStamp; + auto key = _h264frame->keyFrame(); + onGetH264(_h264frame); + return key; } default:{ @@ -195,10 +195,8 @@ bool H264RtpDecoder::decodeRtp(const RtpPacket::Ptr &rtppack) { void H264RtpDecoder::onGetH264(const H264Frame::Ptr &frame) { //写入环形缓存 - auto lastSeq = _h264frame->sequence; RtpCodec::inputFrame(frame); _h264frame = obtainFrame(); - _h264frame->sequence = lastSeq; } diff --git a/src/Extension/H264Rtp.h b/src/Extension/H264Rtp.h index 4719fe3a..09f2346d 100644 --- a/src/Extension/H264Rtp.h +++ b/src/Extension/H264Rtp.h @@ -64,6 +64,7 @@ private: H264Frame::Ptr obtainFrame(); private: H264Frame::Ptr _h264frame; + int _lastSeq = 0; }; /** From 383a14a76d01843496d33c92403ce759e89437d9 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Thu, 1 Aug 2019 18:49:04 +0800 Subject: [PATCH 06/30] =?UTF-8?q?=E9=87=8D=E6=96=B0mp4=E5=BD=95=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 3rdpart/media-server | 2 +- src/Extension/AAC.h | 8 + src/Extension/Frame.h | 12 ++ src/Extension/H264.h | 20 ++ src/Extension/H265.h | 37 +++- src/Extension/H265Rtp.cpp | 42 ++-- src/Extension/H265Rtp.h | 1 + src/MediaFile/MP4Muxer.cpp | 230 ++++++++++++++++++++ src/MediaFile/MP4Muxer.h | 98 +++++++++ src/MediaFile/MediaRecorder.cpp | 4 +- src/MediaFile/MediaRecorder.h | 4 +- src/MediaFile/Mp4Maker.cpp | 368 ++++---------------------------- src/MediaFile/Mp4Maker.h | 54 +---- src/MediaFile/TsMuxer.h | 7 +- 14 files changed, 470 insertions(+), 417 deletions(-) create mode 100644 src/MediaFile/MP4Muxer.cpp create mode 100644 src/MediaFile/MP4Muxer.h diff --git a/3rdpart/media-server b/3rdpart/media-server index a32fe104..6df71e01 160000 --- a/3rdpart/media-server +++ b/3rdpart/media-server @@ -1 +1 @@ -Subproject commit a32fe104c0290bc01a7ee73d50b568e8d9ded931 +Subproject commit 6df71e01c174cdfe69e597cc4acb766a20b28620 diff --git a/src/Extension/AAC.h b/src/Extension/AAC.h index e445b7fe..2af513f6 100644 --- a/src/Extension/AAC.h +++ b/src/Extension/AAC.h @@ -79,6 +79,10 @@ public: bool keyFrame() const override { return false; } + + bool configFrame() const override{ + return false; + } public: unsigned int syncword = 0; //12 bslbf 同步字The bit string ‘1111 1111 1111’,说明一个ADTS帧的开始 unsigned int id; //1 bslbf MPEG 标示符, 设置为1 @@ -127,6 +131,10 @@ public: bool keyFrame() const override { return false; } + + bool configFrame() const override{ + return false; + } } ; diff --git a/src/Extension/Frame.h b/src/Extension/Frame.h index 5d49753a..79b5d02a 100644 --- a/src/Extension/Frame.h +++ b/src/Extension/Frame.h @@ -117,6 +117,12 @@ public: */ virtual bool keyFrame() const = 0; + /** + * 是否为配置帧,譬如sps pps vps + * @return + */ + virtual bool configFrame() const = 0; + /** * 是否可以缓存 */ @@ -371,6 +377,7 @@ public: _trackType = frame->getTrackType(); _codec = frame->getCodecId(); _key = frame->keyFrame(); + _config = frame->configFrame(); } virtual ~FrameCacheAble() = default; @@ -394,12 +401,17 @@ public: bool keyFrame() const override{ return _key; } + + bool configFrame() const override{ + return _config; + } private: Frame::Ptr _frame; BufferRaw::Ptr _buffer; TrackType _trackType; CodecId _codec; bool _key; + bool _config; }; diff --git a/src/Extension/H264.h b/src/Extension/H264.h index 54e28e07..4cb91135 100644 --- a/src/Extension/H264.h +++ b/src/Extension/H264.h @@ -82,6 +82,16 @@ public: bool keyFrame() const override { return H264_TYPE(buffer[iPrefixSize]) == H264Frame::NAL_IDR; } + + bool configFrame() const override{ + switch(H264_TYPE(buffer[iPrefixSize]) ){ + case H264Frame::NAL_SPS: + case H264Frame::NAL_PPS: + return true; + default: + return false; + } + } public: uint32_t timeStamp; uint32_t ptsStamp = 0; @@ -118,6 +128,16 @@ public: bool keyFrame() const override { return H264_TYPE(_ptr[_prefixSize]) == H264Frame::NAL_IDR; } + + bool configFrame() const override{ + switch(H264_TYPE(_ptr[_prefixSize])){ + case H264Frame::NAL_SPS: + case H264Frame::NAL_PPS: + return true; + default: + return false; + } + } }; /** diff --git a/src/Extension/H265.h b/src/Extension/H265.h index 7063d470..7557b628 100644 --- a/src/Extension/H265.h +++ b/src/Extension/H265.h @@ -86,6 +86,10 @@ public: return timeStamp; } + uint32_t pts() const override { + return ptsStamp ? ptsStamp : timeStamp; + } + uint32_t prefixSize() const override { return iPrefixSize; } @@ -99,7 +103,18 @@ public: } bool keyFrame() const override { - return isKeyFrame(type); + return isKeyFrame(H265_TYPE(buffer[iPrefixSize])); + } + + bool configFrame() const override{ + switch(H265_TYPE(buffer[iPrefixSize])){ + case H265Frame::NAL_VPS: + case H265Frame::NAL_SPS: + case H265Frame::NAL_PPS: + return true; + default: + return false; + } } static bool isKeyFrame(int type) { @@ -117,9 +132,8 @@ public: } public: - uint16_t sequence; uint32_t timeStamp; - unsigned char type; + uint32_t ptsStamp = 0; string buffer; uint32_t iPrefixSize = 4; }; @@ -146,8 +160,18 @@ public: } bool keyFrame() const override { - int type = H265_TYPE(((uint8_t *) _ptr)[_prefixSize]); - return H265Frame::isKeyFrame(type); + return H265Frame::isKeyFrame(H265_TYPE(((uint8_t *) _ptr)[_prefixSize])); + } + + bool configFrame() const override{ + switch(H265_TYPE(((uint8_t *) _ptr)[_prefixSize])){ + case H265Frame::NAL_VPS: + case H265Frame::NAL_SPS: + case H265Frame::NAL_PPS: + return true; + default: + return false; + } } }; @@ -328,7 +352,6 @@ private: } if(!_vps.empty()){ auto vpsFrame = std::make_shared(); - vpsFrame->type = H265Frame::NAL_VPS; vpsFrame->iPrefixSize = 4; vpsFrame->buffer.assign("\x0\x0\x0\x1", 4); vpsFrame->buffer.append(_vps); @@ -337,7 +360,6 @@ private: } if (!_sps.empty()) { auto spsFrame = std::make_shared(); - spsFrame->type = H265Frame::NAL_SPS; spsFrame->iPrefixSize = 4; spsFrame->buffer.assign("\x0\x0\x0\x1", 4); spsFrame->buffer.append(_sps); @@ -347,7 +369,6 @@ private: if (!_pps.empty()) { auto ppsFrame = std::make_shared(); - ppsFrame->type = H265Frame::NAL_PPS; ppsFrame->iPrefixSize = 4; ppsFrame->buffer.assign("\x0\x0\x0\x1", 4); ppsFrame->buffer.append(_pps); diff --git a/src/Extension/H265Rtp.cpp b/src/Extension/H265Rtp.cpp index 9d34d925..4fc00042 100644 --- a/src/Extension/H265Rtp.cpp +++ b/src/Extension/H265Rtp.cpp @@ -99,56 +99,56 @@ bool H265RtpDecoder::decodeRtp(const RtpPacket::Ptr &rtppack) { // fragmentation unit (FU) FU fu; MakeFU(frame[2], fu); - if (fu.S == 1) { - //FU-A start + if (fu.S) { + //该帧的第一个rtp包 _h265frame->buffer.assign("\x0\x0\x0\x1", 4); _h265frame->buffer.push_back(fu.type << 1); _h265frame->buffer.push_back(0x01); _h265frame->buffer.append((char *) frame + 3, length - 3); - _h265frame->type = fu.type; _h265frame->timeStamp = rtppack->timeStamp; - _h265frame->sequence = rtppack->sequence; + //该函数return时,保存下当前sequence,以便下次对比seq是否连续 + _lastSeq = rtppack->sequence; return (_h265frame->keyFrame()); //i frame } - if (rtppack->sequence != (uint16_t) (_h265frame->sequence + 1)) { + if (rtppack->sequence != _lastSeq + 1 && rtppack->sequence != 0) { + //中间的或末尾的rtp包,其seq必须连续(如果回环了则判定为连续),否则说明rtp丢包,那么该帧不完整,必须得丢弃 _h265frame->buffer.clear(); - WarnL << "丢包,帧废弃:" << rtppack->sequence << "," << _h265frame->sequence; + WarnL << "rtp sequence不连续: " << rtppack->sequence << " != " << _lastSeq << " + 1,该帧被废弃"; return false; } - _h265frame->sequence = rtppack->sequence; - if (fu.E == 1) { - //FU-A end + + if (!fu.E) { + //该帧的中间rtp包 _h265frame->buffer.append((char *) frame + 3, length - 3); - _h265frame->timeStamp = rtppack->timeStamp; - auto isIDR = _h265frame->keyFrame(); - onGetH265(_h265frame); - return isIDR; + //该函数return时,保存下当前sequence,以便下次对比seq是否连续 + _lastSeq = rtppack->sequence; + return false; } - //FU-A mid + + //该帧最后一个rtp包 _h265frame->buffer.append((char *) frame + 3, length - 3); - return false; + _h265frame->timeStamp = rtppack->timeStamp; + auto key = _h265frame->keyFrame(); + onGetH265(_h265frame); + return key; } default: // 4.4.1. Single NAL Unit Packets (p24) //a full frame _h265frame->buffer.assign("\x0\x0\x0\x1", 4); _h265frame->buffer.append((char *)frame, length); - _h265frame->type = nal; _h265frame->timeStamp = rtppack->timeStamp; - _h265frame->sequence = rtppack->sequence; - auto isIDR = _h265frame->keyFrame(); + auto key = _h265frame->keyFrame(); onGetH265(_h265frame); - return (isIDR); //i frame + return key; } } void H265RtpDecoder::onGetH265(const H265Frame::Ptr &frame) { //写入环形缓存 - auto lastSeq = _h265frame->sequence; RtpCodec::inputFrame(frame); _h265frame = obtainFrame(); - _h265frame->sequence = lastSeq; } diff --git a/src/Extension/H265Rtp.h b/src/Extension/H265Rtp.h index 9c42937b..f243baf2 100644 --- a/src/Extension/H265Rtp.h +++ b/src/Extension/H265Rtp.h @@ -65,6 +65,7 @@ private: H265Frame::Ptr obtainFrame(); private: H265Frame::Ptr _h265frame; + int _lastSeq = 0; }; /** diff --git a/src/MediaFile/MP4Muxer.cpp b/src/MediaFile/MP4Muxer.cpp new file mode 100644 index 00000000..f9f736df --- /dev/null +++ b/src/MediaFile/MP4Muxer.cpp @@ -0,0 +1,230 @@ +/* + * MIT License + * + * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> + * + * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifdef ENABLE_MP4RECORD + +#include "MP4Muxer.h" +#include "Util/File.h" + +namespace mediakit{ + +#if defined(_WIN32) || defined(_WIN64) +#define fseek64 _fseeki64 +#define ftell64 _ftelli64 +#else +#define fseek64 fseek +#define ftell64 ftell +#endif + +MP4MuxerBase::MP4MuxerBase(int flags) { + static struct mov_buffer_t s_io = { + [](void* ctx, void* data, uint64_t bytes) { + MP4MuxerBase *thiz = (MP4MuxerBase *)ctx; + return thiz->onRead(data,bytes); + }, + [](void* ctx, const void* data, uint64_t bytes){ + MP4MuxerBase *thiz = (MP4MuxerBase *)ctx; + return thiz->onWrite(data,bytes); + }, + [](void* ctx, uint64_t offset) { + MP4MuxerBase *thiz = (MP4MuxerBase *)ctx; + return thiz->onSeek(offset); + }, + [](void* ctx){ + MP4MuxerBase *thiz = (MP4MuxerBase *)ctx; + return thiz->onTell(); + } + }; + _mov_writter.reset(mov_writer_create(&s_io,this,flags),[](mov_writer_t *ptr){ + if(ptr){ + mov_writer_destroy(ptr); + } + }); +} + +/////////////////////////////////// + +MP4Muxer::MP4Muxer(int flags) : MP4MuxerBase(flags) { +} + + +void MP4Muxer::onTrackFrame(const Frame::Ptr &frame) { + if(frame->configFrame()){ + //忽略配置帧 + return; + } + auto it = _codec_to_trackid.find(frame->getCodecId()); + if(it == _codec_to_trackid.end()){ + return; + } + + mov_writer_write_l(_mov_writter.get(), + it->second, + frame->data() + frame->prefixSize(), + frame->size() - frame->prefixSize(), + frame->pts(), + frame->dts(), + frame->keyFrame() ? MOV_AV_FLAG_KEYFREAME : 0, + 0); +} + +void MP4Muxer::onTrackReady(const Track::Ptr &track) { + switch (track->getCodecId()) { + case CodecAAC: { + auto aac_track = dynamic_pointer_cast(track); + if (!aac_track) { + WarnL << "不是AAC Track"; + return; + } + auto track_id = mov_writer_add_audio(_mov_writter.get(), + MOV_OBJECT_AAC, + aac_track->getAudioChannel(), + aac_track->getAudioSampleBit(), + aac_track->getAudioSampleRate(), + aac_track->getAacCfg().data(), 2); + _codec_to_trackid[track->getCodecId()] = track_id; + } + break; + case CodecH264: { + auto h264_track = dynamic_pointer_cast(track); + if (!h264_track) { + WarnL << "不是H264 Track"; + return; + } + + struct mpeg4_avc_t avc; + string sps_pps = string("\x00\x00\x00\x01", 4) + h264_track->getSps() + + string("\x00\x00\x00\x01", 4) + h264_track->getPps(); + h264_annexbtomp4(&avc, sps_pps.data(), sps_pps.size(), NULL, 0, NULL); + + uint8_t extra_data[1024]; + int extra_data_size = mpeg4_avc_decoder_configuration_record_save(&avc, extra_data, sizeof(extra_data)); + if (extra_data_size == -1) { + WarnL << "生成H264 extra_data 失败"; + return; + } + + auto track_id = mov_writer_add_video(_mov_writter.get(), + MOV_OBJECT_H264, + h264_track->getVideoWidth(), + h264_track->getVideoHeight(), + extra_data, + extra_data_size); + _codec_to_trackid[track->getCodecId()] = track_id; + } + break; + case CodecH265: { + auto h265_track = dynamic_pointer_cast(track); + if (!h265_track) { + WarnL << "不是H265 Track"; + return; + } + + struct mpeg4_hevc_t hevc; + string vps_sps_pps = string("\x00\x00\x00\x01", 4) + h265_track->getVps() + + string("\x00\x00\x00\x01", 4) + h265_track->getSps() + + string("\x00\x00\x00\x01", 4) + h265_track->getPps(); + h265_annexbtomp4(&hevc, vps_sps_pps.data(), vps_sps_pps.size(), NULL, 0, NULL); + + uint8_t extra_data[1024]; + int extra_data_size = mpeg4_hevc_decoder_configuration_record_save(&hevc, extra_data, sizeof(extra_data)); + if (extra_data_size == -1) { + WarnL << "生成H265 extra_data 失败"; + return; + } + + auto track_id = mov_writer_add_video(_mov_writter.get(), + MOV_OBJECT_HEVC, + h265_track->getVideoWidth(), + h265_track->getVideoHeight(), + extra_data, + extra_data_size); + _codec_to_trackid[track->getCodecId()] = track_id; + } + break; + default: + WarnL << "MP4录制不支持该编码格式:" << track->getCodecId(); + break; + } +} + +#define FILE_BUF_SIZE (64 * 1024) + +MP4MuxerFile::MP4MuxerFile(const char *file) { + //创建文件 + auto fp = File::createfile_file(file,"wb"); + if(!fp){ + throw std::runtime_error(string("打开文件失败:") + file); + } + + //新建文件io缓存 + std::shared_ptr file_buf(new char[FILE_BUF_SIZE],[](char *ptr){ + if(ptr){ + delete [] ptr; + } + }); + + if(file_buf){ + //设置文件io缓存 + setvbuf(fp, file_buf.get(), _IOFBF, FILE_BUF_SIZE); + } + + //创建智能指针 + _file.reset(fp,[file_buf](FILE *fp) { + fclose(fp); + }); +} + + +int MP4MuxerFile::onRead(void *data, uint64_t bytes) { + return fread(data, 1, bytes, _file.get()); +} + +int MP4MuxerFile::onWrite(const void *data, uint64_t bytes) { + return fwrite(data, 1, bytes, _file.get()); +} + + +#if defined(_WIN32) || defined(_WIN64) + #define fseek64 _fseeki64 + #define ftell64 _ftelli64 +#else + #define fseek64 fseek + #define ftell64 ftell +#endif + +int MP4MuxerFile::onSeek(uint64_t offset) { + return fseek64(_file.get(), offset, SEEK_SET); +} + +uint64_t MP4MuxerFile::onTell() { + return ftell64(_file.get()); +} + + +}//namespace mediakit + +#endif//#ifdef ENABLE_MP4RECORD diff --git a/src/MediaFile/MP4Muxer.h b/src/MediaFile/MP4Muxer.h new file mode 100644 index 00000000..80d82a54 --- /dev/null +++ b/src/MediaFile/MP4Muxer.h @@ -0,0 +1,98 @@ +/* + * MIT License + * + * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> + * + * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef ZLMEDIAKIT_MP4MUXER_H +#define ZLMEDIAKIT_MP4MUXER_H + +#ifdef ENABLE_MP4RECORD + +#include "Common/MediaSink.h" +#include "mov-writer.h" +#include "mpeg4-hevc.h" +#include "mpeg4-avc.h" +#include "mpeg4-aac.h" +#include "mov-buffer.h" +#include "mov-format.h" +#include "Extension/AAC.h" +#include "Extension/H264.h" +#include "Extension/H265.h" + +namespace mediakit{ + +class MP4MuxerBase{ +public: + MP4MuxerBase(int flags = MOV_FLAG_FASTSTART); + virtual ~MP4MuxerBase() = default; +protected: + virtual int onRead(void* data, uint64_t bytes) = 0; + virtual int onWrite(const void* data, uint64_t bytes) = 0; + virtual int onSeek( uint64_t offset) = 0; + virtual uint64_t onTell() = 0; +protected: + std::shared_ptr _mov_writter; +}; + +class MP4Muxer : public MediaSink , public MP4MuxerBase{ +public: + MP4Muxer(int flags = MOV_FLAG_FASTSTART) ; + ~MP4Muxer() override = default; +protected: + /** + * 某track已经准备好,其ready()状态返回true, + * 此时代表可以获取其例如sps pps等相关信息了 + * @param track + */ + void onTrackReady(const Track::Ptr & track) override; + + /** + * 某Track输出frame,在onAllTrackReady触发后才会调用此方法 + * @param frame + */ + void onTrackFrame(const Frame::Ptr &frame) override; +private: + map _codec_to_trackid; +}; + + +class MP4MuxerFile : public MP4Muxer { +public: + typedef std::shared_ptr Ptr; + MP4MuxerFile(const char *file); + ~MP4MuxerFile() = default; +protected: + int onRead(void* data, uint64_t bytes) override; + int onWrite(const void* data, uint64_t bytes) override; + int onSeek( uint64_t offset) override; + uint64_t onTell() override ; +private: + std::shared_ptr _file; +}; + +}//namespace mediakit + +#endif//#ifdef ENABLE_MP4RECORD + +#endif //ZLMEDIAKIT_MP4MUXER_H diff --git a/src/MediaFile/MediaRecorder.cpp b/src/MediaFile/MediaRecorder.cpp index be08867d..71eac5e4 100644 --- a/src/MediaFile/MediaRecorder.cpp +++ b/src/MediaFile/MediaRecorder.cpp @@ -106,11 +106,11 @@ void MediaRecorder::addTrack(const Track::Ptr &track) { } #endif //defined(ENABLE_HLS) -#if defined(ENABLE_MP4V2) +#if defined(ENABLE_MP4RECORD) if (_mp4Maker) { _mp4Maker->addTrack(track); } -#endif //defined(ENABLE_MP4V2) +#endif //defined(ENABLE_MP4RECORD) } } /* namespace mediakit */ diff --git a/src/MediaFile/MediaRecorder.h b/src/MediaFile/MediaRecorder.h index b1b72119..da06885e 100644 --- a/src/MediaFile/MediaRecorder.h +++ b/src/MediaFile/MediaRecorder.h @@ -64,9 +64,9 @@ private: std::shared_ptr _hlsMaker; #endif //defined(ENABLE_HLS) -#if defined(ENABLE_MP4V2) +#if defined(ENABLE_MP4RECORD) std::shared_ptr _mp4Maker; -#endif //defined(ENABLE_MP4V2) +#endif //defined(ENABLE_MP4RECORD) }; } /* namespace mediakit */ diff --git a/src/MediaFile/Mp4Maker.cpp b/src/MediaFile/Mp4Maker.cpp index 96d6af99..d4f814ee 100644 --- a/src/MediaFile/Mp4Maker.cpp +++ b/src/MediaFile/Mp4Maker.cpp @@ -29,68 +29,14 @@ #include #include "Common/config.h" #include "Mp4Maker.h" -#include "MediaRecorder.h" -#include "Util/File.h" -#include "Util/mini.h" #include "Util/util.h" #include "Util/NoticeCenter.h" -#include "Extension/H264.h" -#include "Extension/H265.h" -#include "Extension/AAC.h" #include "Thread/WorkThreadPool.h" - -#include "mov-buffer.h" -#include "mov-format.h" - - - using namespace toolkit; namespace mediakit { -#if defined(_WIN32) || defined(_WIN64) -#define fseek64 _fseeki64 -#define ftell64 _ftelli64 -#else -#define fseek64 fseek -#define ftell64 ftell -#endif - -static int movfileRead(void* fp, void* data, uint64_t bytes) -{ - if (bytes == fread(data, 1, bytes, (FILE*)fp)) - return 0; - return 0 != ferror((FILE*)fp) ? ferror((FILE*)fp) : -1 /*EOF*/; -} - -static int movfileWrite(void* fp, const void* data, uint64_t bytes) -{ - return bytes == fwrite(data, 1, bytes, (FILE*)fp) ? 0 : ferror((FILE*)fp); -} - -static int movfileSeek(void* fp, uint64_t offset) -{ - return fseek64((FILE*)fp, offset, SEEK_SET); -} - -static uint64_t movfileTell(void* fp) -{ - return ftell64((FILE*)fp); -} - -const struct mov_buffer_t* movfileBuffer(void) -{ - static struct mov_buffer_t s_io = { - movfileRead, - movfileWrite, - movfileSeek, - movfileTell, - }; - return &s_io; -} - - string timeStr(const char *fmt) { std::tm tm_snapshot; auto time = ::time(NULL); @@ -119,203 +65,11 @@ Mp4Maker::Mp4Maker(const string& strPath, _info.strStreamId = strStreamId; _info.strVhost = strVhost; _info.strFolder = strPath; - - memset(&_movH265info, 0, sizeof(_movH265info)); - _movH265info.videoTrack = -1; - _movH265info.audioTrack = -1; - - //----record 业务逻辑----// } Mp4Maker::~Mp4Maker() { closeFile(); } -void Mp4Maker::inputH264(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp){ - auto iType = H264_TYPE(((uint8_t*)pData)[4]); - - if (H264Frame::NAL_B_P <= iType && iType <= H264Frame::NAL_IDR){ - - int64_t iTimeInc = (int64_t)ui32TimeStamp - (int64_t)_ui32LastVideoTime; - iTimeInc = MAX(0,MIN(iTimeInc,500)); - if( (iTimeInc == 0 || iTimeInc == 500) && H264Frame::NAL_IDR != iType){ - WarnL << "abnormal time stamp increment:" << ui32TimeStamp << " " << _ui32LastVideoTime; - } - - if ( _strLastVideo.size() ){ - //如果出现SPS PPS黏连的帧,那么在这里先处理 - inputH264_l((char *) _strLastVideo.data(), _strLastVideo.size(), _ui32LastVideoTime); - _strLastVideo = ""; - } - inputH264_l((char *) pData, ui32Length, ui32TimeStamp); - _ui32LastVideoTime = ui32TimeStamp; - }else{ - //SPS PPS 进入等待组合为一帧 - _strLastVideo.append((char *)pData,ui32Length); - _ui32LastVideoTime = ui32TimeStamp; - } -} - -void Mp4Maker::inputH265(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp){ - - auto iType = H265_TYPE(((uint8_t*)pData)[4]); - if (iType <= H265Frame::NAL_IDR_W_RADL ){ - - int64_t iTimeInc = (int64_t)ui32TimeStamp - (int64_t)_ui32LastVideoTime; - iTimeInc = MAX(0,MIN(iTimeInc,500)); - if((iTimeInc == 0 || iTimeInc == 500) && H265Frame::NAL_IDR_W_RADL != iType){ - WarnL << "abnormal time stamp increment:" << ui32TimeStamp << " " << _ui32LastVideoTime; - } - - if ( _strLastVideo.size() ){ - //如果出现SPS PPS VPS黏连的帧,那么在这里先处理 - inputH265_l((char *) _strLastVideo.data(), _strLastVideo.size(), _ui32LastVideoTime); - _strLastVideo = ""; - } - inputH265_l((char *) pData, ui32Length, ui32TimeStamp); - _ui32LastVideoTime = ui32TimeStamp; - }else{ - _strLastVideo.append((char *)pData,ui32Length); - _ui32LastVideoTime = ui32TimeStamp; - } -} - -void Mp4Maker::inputAAC(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp){ - int64_t iTimeInc = (int64_t)ui32TimeStamp - (int64_t)_ui32LastAudioTime; - iTimeInc = MAX(0,MIN(iTimeInc,500)); - if(iTimeInc == 0 || iTimeInc == 500){ - WarnL << "abnormal time stamp increment:" << ui32TimeStamp << " " << _ui32LastAudioTime; - } - inputAAC_l((char *) pData, ui32Length, ui32TimeStamp); - _ui32LastAudioTime = ui32TimeStamp; -} - -void Mp4Maker::inputH264_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp) { - GET_CONFIG(uint32_t,recordSec,Record::kFileSecond); - auto iType = H264_TYPE(((uint8_t*)pData)[4]); - int32_t compositionTime; - if( iType >= H264Frame::NAL_IDR && (_movH265info.pMov == NULL || _ticker.elapsedTime() > recordSec * 1000)){ - //在I帧率处新建MP4文件 - //如果文件未创建或者文件超过10分钟则创建新文件 - //每一个录制的MP4文件时间戳都要从0开始 - _startPts = ui32TimeStamp; - createFile(); - } - - char *pNualData = (char *)pData; - if (_movH265info.pMov!=NULL){ - int vcl; - if (_movH265info.videoTrack < 0){ - //解析解析SPS PPS,未添加track的时候执行 - int n = h264_annexbtomp4(&_movH265info.avc, pData, ui32Length, _sBbuffer, sizeof(_sBbuffer), &vcl); - if (_movH265info.avc.nb_sps < 1 || _movH265info.avc.nb_pps < 1){ - return; // waiting for sps/pps - } - - uint8_t sExtraData[64 * 1024]; - int extraDataSize = mpeg4_avc_decoder_configuration_record_save(&_movH265info.avc, sExtraData, sizeof(sExtraData)); - if (extraDataSize <= 0){ - // invalid HVCC - return; - } - - // TODO: waiting for key frame ??? - _movH265info.videoTrack = mov_writer_add_video(_movH265info.pMov, - MOV_OBJECT_H264, - _movH265info.width, - _movH265info.height, - sExtraData, - extraDataSize); - return; - } - if ( iType <= H264Frame::NAL_IDR ){ - uint8_t *ptr = (uint8_t*)pData; - ptr[0] = (uint8_t)((ui32Length-4 >> 24) & 0xFF); - ptr[1] = (uint8_t)((ui32Length-4 >> 16) & 0xFF); - ptr[2] = (uint8_t)((ui32Length-4 >> 8) & 0xFF); - ptr[3] = (uint8_t)((ui32Length-4 >> 0) & 0xFF); - uint32_t ui32Pts = ui32TimeStamp < _movH265info.startPts ? 0 : ui32TimeStamp-_movH265info.startPts; - mov_writer_write(_movH265info.pMov, - _movH265info.videoTrack, pData, ui32Length, - ui32Pts, - ui32Pts, - iType == H264Frame::NAL_IDR ? MOV_AV_FLAG_KEYFREAME : 0); - } - } - -} - -void Mp4Maker::inputH265_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp) { - GET_CONFIG(uint32_t,recordSec,Record::kFileSecond); - - int32_t compositionTime; - auto iType = H265_TYPE(((uint8_t*)pData)[4]); - if( iType >= H265Frame::NAL_IDR_W_RADL && (_movH265info.pMov == NULL || _ticker.elapsedTime() > recordSec * 1000)){ - _h265Record = 1; - //每一个录制的MP4文件时间戳都要从0开始 - _startPts = ui32TimeStamp; - - //在I帧率处新建MP4文件 - //如果文件未创建或者文件超过最长时间则创建新文件 - createFile(); - } - - char *pNualData = (char *)pData; - if (_movH265info.pMov!=NULL){ - int vcl; - if (_movH265info.videoTrack < 0){ - //解析解析VPS SPS PPS,未添加track的时候执行 - int n = h265_annexbtomp4(&_movH265info.hevc, pData, ui32Length, _sBbuffer, sizeof(_sBbuffer), &vcl); - if (_movH265info.hevc.numOfArrays < 1){ - return; // waiting for vps/sps/pps - } - - uint8_t sExtraData[64 * 1024]; - int extraDataSize = mpeg4_hevc_decoder_configuration_record_save(&_movH265info.hevc, sExtraData, sizeof(sExtraData)); - if (extraDataSize <= 0){ - // invalid HVCC - return; - } - // TODO: waiting for key frame ??? - _movH265info.videoTrack = mov_writer_add_video(_movH265info.pMov, MOV_OBJECT_HEVC, _movH265info.width, _movH265info.height, sExtraData, extraDataSize); - - return; - } - if ( iType <= H265Frame::NAL_IDR_W_RADL ) - { - uint8_t *ptr = (uint8_t*)pData; - ptr[0] = (uint8_t)((ui32Length-4 >> 24) & 0xFF); - ptr[1] = (uint8_t)((ui32Length-4 >> 16) & 0xFF); - ptr[2] = (uint8_t)((ui32Length-4 >> 8) & 0xFF); - ptr[3] = (uint8_t)((ui32Length-4 >> 0) & 0xFF); - - uint32_t ui32Pts = ui32TimeStamp < _movH265info.startPts ? 0 : ui32TimeStamp-_movH265info.startPts; - mov_writer_write(_movH265info.pMov, - _movH265info.videoTrack, - pData, - ui32Length, - ui32Pts, - ui32Pts, - iType == H265Frame::NAL_IDR_W_RADL ? MOV_AV_FLAG_KEYFREAME : 0); - } - } - -} - -void Mp4Maker::inputAAC_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp) { - GET_CONFIG(uint32_t,recordSec,Record::kFileSecond); - if (!_haveVideo && (_movH265info.pMov == NULL || _ticker.elapsedTime() > recordSec * 1000)) { - _startPts = ui32TimeStamp; - createFile(); - } - - if (-1 != _movH265info.audioTrack && _movH265info.pMov != NULL){ - - uint32_t ui32Pts = ui32TimeStamp < _movH265info.startPts ? 0 : ui32TimeStamp-_movH265info.startPts; - mov_writer_write(_movH265info.pMov, _movH265info.audioTrack, (uint8_t*)pData, ui32Length, ui32Pts, ui32Pts, 0); - } - -} - void Mp4Maker::createFile() { closeFile(); auto strDate = timeStr("%Y-%m-%d"); @@ -327,82 +81,39 @@ void Mp4Maker::createFile() { _info.ui64StartedTime = ::time(NULL); _info.strFileName = strTime + ".mp4"; _info.strFilePath = strFile; - GET_CONFIG(string,appName,Record::kAppName); - _info.strUrl = appName + "/" + _info.strAppName + "/" + _info.strStreamId + "/" + strDate + "/" + strTime + ".mp4"; - //----record 业务逻辑----// - -#if !defined(_WIN32) - File::createfile_path(strFileTmp.data(), S_IRWXO | S_IRWXG | S_IRWXU); -#else - File::createfile_path(strFileTmp.data(), 0); -#endif - - memset(&_movH265info, 0, sizeof(_movH265info)); - _movH265info.videoTrack = -1; - _movH265info.audioTrack = -1; - _movH265info.width = 0; - _movH265info.height = 0; - _movH265info.pFile = fopen(strFileTmp.data(), "wb+"); - _movH265info.startPts = _startPts; - _movH265info.pMov = mov_writer_create(movfileBuffer(), _movH265info.pFile, 0/*MOV_FLAG_FASTSTART*/); - - _strFileTmp = strFileTmp; - _strFile = strFile; - _ticker.resetTime(); - - if ( _h265Record ){ - auto videoTrack = dynamic_pointer_cast(getTrack(TrackVideo)); - if(videoTrack){ - _movH265info.width = videoTrack->getVideoWidth(); - _movH265info.height = videoTrack->getVideoHeight(); + try { + _muxer = std::make_shared(strFileTmp.data()); + for(auto &track :_tracks){ + if(track){ + //添加track + _muxer->addTrack(track); + } } - }else{ - auto videoTrack = dynamic_pointer_cast(getTrack(TrackVideo)); - if(videoTrack){ -// auto &sps = videoTrack->getSps(); -// auto &pps = videoTrack->getPps(); - _movH265info.width = videoTrack->getVideoWidth(); - _movH265info.height = videoTrack->getVideoHeight(); - } - } - if ( _movH265info.width <=0 || _movH265info.height <= 0 ) - WarnL << "分辨率获取失败,MP4录制异常"; - - auto audioTrack = dynamic_pointer_cast(getTrack(TrackAudio)); - if(audioTrack){ - _audioSampleRate = audioTrack->getAudioSampleRate(); - _audioChannel = audioTrack->getAudioChannel(); - uint8_t extra_data[64 * 1024]; - _movH265info.audioTrack = mov_writer_add_audio(_movH265info.pMov, MOV_OBJECT_AAC, _audioChannel, 16, _audioSampleRate, audioTrack->getAacCfg().data(), 2); - if (-1 == _movH265info.audioTrack) - WarnL << "添加音频通道失败:" << strFileTmp; + _strFileTmp = strFileTmp; + _strFile = strFile; + _createFileTicker.resetTime(); + }catch(std::exception &ex) { + WarnL << ex.what(); } } void Mp4Maker::asyncClose() { + auto muxer = _muxer; auto strFileTmp = _strFileTmp; auto strFile = _strFile; auto info = _info; - - FILE *pFile = _movH265info.pFile; - mov_writer_t* hMp4 = _movH265info.pMov; - WorkThreadPool::Instance().getExecutor()->async([hMp4,strFileTmp,strFile,info,pFile]() { - //获取文件录制时间,放在MP4Close之前是为了忽略MP4Close执行时间 + WorkThreadPool::Instance().getExecutor()->async([muxer,strFileTmp,strFile,info]() { + //获取文件录制时间,放在关闭mp4之前是为了忽略关闭mp4执行时间 const_cast(info).ui64TimeLen = ::time(NULL) - info.ui64StartedTime; - //MP4Close非常耗时,所以要放在后台线程执行 - if (hMp4 != NULL ){ - mov_writer_destroy(hMp4); - fclose(pFile); - DebugL << "fclose end"; - } - + //关闭mp4非常耗时,所以要放在后台线程执行 + const_cast(muxer).reset(); //临时文件名改成正式文件名,防止mp4未完成时被访问 rename(strFileTmp.data(),strFile.data()); //获取文件大小 @@ -415,42 +126,37 @@ void Mp4Maker::asyncClose() { } void Mp4Maker::closeFile() { - if (_movH265info.pMov != NULL) { + if (_muxer) { asyncClose(); - memset(&_movH265info, 0, sizeof(_movH265info)); - _movH265info.pMov = NULL; - _movH265info.videoTrack = -1; - _movH265info.audioTrack = -1; - } + _muxer = nullptr; + } } void Mp4Maker::onTrackFrame(const Frame::Ptr &frame) { - switch (frame->getCodecId()){ - case CodecH264:{ - //需要带00 00 00 01,方便在mov_writer_write的时候字节修改这4Byte为长度信息 - inputH264(frame->data() , frame->size(),frame->pts()); - } - break; - case CodecAAC:{ - //不需要ADTS头 - inputAAC(frame->data() + frame->prefixSize(), frame->size() - frame->prefixSize(),frame->pts()); - } - break; - case CodecH265:{ - //需要带00 00 00 01,方便在mov_writer_write的时候字节修改这4Byte为长度信息 - inputH265(frame->data() , frame->size(),frame->pts()); - } - break; - default: - break; + GET_CONFIG(uint32_t,recordSec,Record::kFileSecond); + if(!_muxer || ((_createFileTicker.elapsedTime() > recordSec * 1000) && + (!_haveVideo || (_haveVideo && frame->keyFrame()))) ){ + //成立条件 + //1、_muxer为空 + //2、到了切片时间,并且只有音频 + //3、到了切片时间,有视频并且遇到视频的关键帧 + createFile(); + } + + if(_muxer){ + //生成mp4文件 + _muxer->inputFrame(frame); } } void Mp4Maker::onAllTrackReady() { + //保存所有的track,为创建MP4MuxerFile做准备 + _tracks.emplace_back(getTrack(TrackVideo)); + _tracks.emplace_back(getTrack(TrackAudio)); _haveVideo = getTrack(TrackVideo).operator bool(); } } /* namespace mediakit */ -#endif //ENABLE_MP4RECORD \ No newline at end of file +#endif //ENABLE_MP4RECORD diff --git a/src/MediaFile/Mp4Maker.h b/src/MediaFile/Mp4Maker.h index 4967690d..1d46a7fa 100644 --- a/src/MediaFile/Mp4Maker.h +++ b/src/MediaFile/Mp4Maker.h @@ -1,4 +1,4 @@ -/* + /* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> @@ -37,14 +37,7 @@ #include "Util/TimeTicker.h" #include "Util/TimeTicker.h" #include "Common/MediaSink.h" -#include "Extension/Track.h" - - -#include "mov-writer.h" -#include "mpeg4-hevc.h" -#include "mpeg4-avc.h" - - +#include "MP4Muxer.h" using namespace toolkit; namespace mediakit { @@ -62,20 +55,6 @@ public: string strStreamId;//流ID string strVhost;//vhost }; - -class MovH265Info { -public: - mov_writer_t* pMov; - struct mpeg4_hevc_t hevc; - struct mpeg4_avc_t avc; - int videoTrack; - int audioTrack; - int width; - int height; - uint32_t startPts; - FILE * pFile; -}; - class Mp4Maker : public MediaSink{ public: typedef std::shared_ptr Ptr; @@ -99,38 +78,15 @@ private: void createFile(); void closeFile(); void asyncClose(); - - //时间戳:参考频率1000 - void inputH264(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); - void inputH265(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); - //时间戳:参考频率1000 - void inputAAC(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); - - void inputH264_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); - void inputH265_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); - void inputAAC_l(void *pData, uint32_t ui32Length, uint32_t ui32TimeStamp); private: - - MovH265Info _movH265info; - int _h265Record = 0; - uint32_t _startPts; - - uint8_t _sBbuffer[2 * 1024 * 1024]; string _strPath; string _strFile; string _strFileTmp; - Ticker _ticker; - - string _strLastVideo; - string _strLastAudio; - - uint32_t _ui32LastVideoTime = 0; - uint32_t _ui32LastAudioTime = 0; + Ticker _createFileTicker; Mp4Info _info; - bool _haveVideo = false; - int _audioSampleRate; - int _audioChannel; + MP4MuxerFile::Ptr _muxer; + list _tracks; }; } /* namespace mediakit */ diff --git a/src/MediaFile/TsMuxer.h b/src/MediaFile/TsMuxer.h index 88dae724..8185307f 100644 --- a/src/MediaFile/TsMuxer.h +++ b/src/MediaFile/TsMuxer.h @@ -31,16 +31,17 @@ #include "Extension/Frame.h" #include "Extension/Track.h" #include "Util/File.h" +#include "Common/MediaSink.h" using namespace toolkit; namespace mediakit { -class TsMuxer { +class TsMuxer : public MediaSink{ public: TsMuxer(); virtual ~TsMuxer(); - void addTrack(const Track::Ptr &track); - void inputFrame(const Frame::Ptr &frame); + void addTrack(const Track::Ptr &track) override; + void inputFrame(const Frame::Ptr &frame) override ; protected: virtual void onTs(const void *packet, int bytes,uint32_t timestamp,int flags) = 0; void resetTracks(); From 6d8db7d232285922bd8cbb884e6e10329bdd1e93 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Thu, 1 Aug 2019 19:09:14 +0800 Subject: [PATCH 07/30] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dbug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/MediaFile/MP4Muxer.cpp | 19 +++++++++++-------- src/MediaFile/MP4Muxer.h | 7 ++++--- tests/test_server.cpp | 5 ++--- 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/src/MediaFile/MP4Muxer.cpp b/src/MediaFile/MP4Muxer.cpp index f9f736df..d9876507 100644 --- a/src/MediaFile/MP4Muxer.cpp +++ b/src/MediaFile/MP4Muxer.cpp @@ -39,7 +39,7 @@ namespace mediakit{ #define ftell64 ftell #endif -MP4MuxerBase::MP4MuxerBase(int flags) { +void MP4MuxerBase::init(int flags) { static struct mov_buffer_t s_io = { [](void* ctx, void* data, uint64_t bytes) { MP4MuxerBase *thiz = (MP4MuxerBase *)ctx; @@ -67,10 +67,6 @@ MP4MuxerBase::MP4MuxerBase(int flags) { /////////////////////////////////// -MP4Muxer::MP4Muxer(int flags) : MP4MuxerBase(flags) { -} - - void MP4Muxer::onTrackFrame(const Frame::Ptr &frame) { if(frame->configFrame()){ //忽略配置帧 @@ -196,15 +192,23 @@ MP4MuxerFile::MP4MuxerFile(const char *file) { _file.reset(fp,[file_buf](FILE *fp) { fclose(fp); }); + + init(MOV_FLAG_FASTSTART); } +MP4MuxerFile::~MP4MuxerFile() { + _mov_writter = nullptr; +} int MP4MuxerFile::onRead(void *data, uint64_t bytes) { - return fread(data, 1, bytes, _file.get()); + if (bytes == fread(data, 1, bytes, _file.get())){ + return 0; + } + return 0 != ferror(_file.get()) ? ferror(_file.get()) : -1 /*EOF*/; } int MP4MuxerFile::onWrite(const void *data, uint64_t bytes) { - return fwrite(data, 1, bytes, _file.get()); + return bytes == fwrite(data, 1, bytes, _file.get()) ? 0 : ferror(_file.get()); } @@ -224,7 +228,6 @@ uint64_t MP4MuxerFile::onTell() { return ftell64(_file.get()); } - }//namespace mediakit #endif//#ifdef ENABLE_MP4RECORD diff --git a/src/MediaFile/MP4Muxer.h b/src/MediaFile/MP4Muxer.h index 80d82a54..88f7a028 100644 --- a/src/MediaFile/MP4Muxer.h +++ b/src/MediaFile/MP4Muxer.h @@ -44,20 +44,21 @@ namespace mediakit{ class MP4MuxerBase{ public: - MP4MuxerBase(int flags = MOV_FLAG_FASTSTART); + MP4MuxerBase() = default; virtual ~MP4MuxerBase() = default; protected: virtual int onRead(void* data, uint64_t bytes) = 0; virtual int onWrite(const void* data, uint64_t bytes) = 0; virtual int onSeek( uint64_t offset) = 0; virtual uint64_t onTell() = 0; + void init(int flags); protected: std::shared_ptr _mov_writter; }; class MP4Muxer : public MediaSink , public MP4MuxerBase{ public: - MP4Muxer(int flags = MOV_FLAG_FASTSTART) ; + MP4Muxer() = default; ~MP4Muxer() override = default; protected: /** @@ -81,7 +82,7 @@ class MP4MuxerFile : public MP4Muxer { public: typedef std::shared_ptr Ptr; MP4MuxerFile(const char *file); - ~MP4MuxerFile() = default; + ~MP4MuxerFile(); protected: int onRead(void* data, uint64_t bytes) override; int onWrite(const void* data, uint64_t bytes) override; diff --git a/tests/test_server.cpp b/tests/test_server.cpp index df30a0c8..c34fd255 100644 --- a/tests/test_server.cpp +++ b/tests/test_server.cpp @@ -239,8 +239,7 @@ int main(int argc,char *argv[]) { //这里是拉流地址,支持rtmp/rtsp协议,负载必须是H264+AAC //如果是其他不识别的音视频将会被忽略(譬如说h264+adpcm转发后会去除音频) - auto urlList = {"rtmp://live.hkstv.hk.lxdns.com/live/hks1", - "rtmp://live.hkstv.hk.lxdns.com/live/hks2" + auto urlList = {"rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov" //rtsp链接支持输入用户名密码 /*"rtsp://admin:jzan123456@192.168.0.122/"*/}; map proxyMap; @@ -259,7 +258,7 @@ int main(int argc,char *argv[]) { //rtsp://127.0.0.1/record/live/0/2017-04-11/11-09-38.mp4 //rtmp://127.0.0.1/record/live/0/2017-04-11/11-09-38.mp4 - PlayerProxy::Ptr player(new PlayerProxy(DEFAULT_VHOST, "live", to_string(i).data())); + PlayerProxy::Ptr player(new PlayerProxy(DEFAULT_VHOST, "live", to_string(i).data(),false,false,false,true)); //指定RTP over TCP(播放rtsp时有效) (*player)[kRtpType] = Rtsp::RTP_TCP; //开始播放,如果播放失败或者播放中止,将会自动重试若干次,重试次数在配置文件中配置,默认一直重试 From 6c0d89f417e7bda720036986f880210940d7a608 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Thu, 1 Aug 2019 21:59:26 +0800 Subject: [PATCH 08/30] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=94=9F=E6=88=90mp4?= =?UTF-8?q?=E7=9B=B8=E5=85=B3bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/MediaFile/MP4Muxer.cpp | 70 +++++++++++++++++++++++++++++++------- src/MediaFile/MP4Muxer.h | 7 +++- src/MediaFile/Mp4Maker.cpp | 2 -- 3 files changed, 64 insertions(+), 15 deletions(-) diff --git a/src/MediaFile/MP4Muxer.cpp b/src/MediaFile/MP4Muxer.cpp index d9876507..eb5a9b56 100644 --- a/src/MediaFile/MP4Muxer.cpp +++ b/src/MediaFile/MP4Muxer.cpp @@ -74,17 +74,44 @@ void MP4Muxer::onTrackFrame(const Frame::Ptr &frame) { } auto it = _codec_to_trackid.find(frame->getCodecId()); if(it == _codec_to_trackid.end()){ + //该Track不存在或初始化失败 return; } + int with_nalu_size ; + switch (frame->getCodecId()){ + case CodecH264: + case CodecH265: + //我们输入264、265是没有头四个字节表明数据长度的 + with_nalu_size = 0; + break; + default: + //aac或其他类型frame不用添加4个nalu_size的字节 + with_nalu_size = 1; + break; + } + + //mp4文件时间戳需要从0开始 + auto &track_info = it->second; + if(!track_info.start_dts){ + track_info.start_dts = frame->dts(); + } + if(!track_info.start_pts){ + track_info.start_pts = frame->pts(); + } + + //相对时间戳 + int dts_inc = frame->dts() - track_info.start_dts; + int pts_inc = frame->pts() - track_info.start_pts; + mov_writer_write_l(_mov_writter.get(), - it->second, - frame->data() + frame->prefixSize(), - frame->size() - frame->prefixSize(), - frame->pts(), - frame->dts(), - frame->keyFrame() ? MOV_AV_FLAG_KEYFREAME : 0, - 0); + track_info.track_id, + frame->data() + frame->prefixSize(), + frame->size() - frame->prefixSize(), + pts_inc >= 0 ? pts_inc : 0, + dts_inc >= 0 ? dts_inc : 0, + frame->keyFrame() ? MOV_AV_FLAG_KEYFREAME : 0, + with_nalu_size); } void MP4Muxer::onTrackReady(const Track::Ptr &track) { @@ -98,10 +125,16 @@ void MP4Muxer::onTrackReady(const Track::Ptr &track) { auto track_id = mov_writer_add_audio(_mov_writter.get(), MOV_OBJECT_AAC, aac_track->getAudioChannel(), - aac_track->getAudioSampleBit(), + aac_track->getAudioSampleBit() * aac_track->getAudioChannel(), aac_track->getAudioSampleRate(), aac_track->getAacCfg().data(), 2); - _codec_to_trackid[track->getCodecId()] = track_id; + if(track_id < 0){ + WarnL << "添加AAC Track失败:" << track_id; + return; + } + track_info info; + info.track_id = track_id; + _codec_to_trackid[track->getCodecId()] = info; } break; case CodecH264: { @@ -129,7 +162,14 @@ void MP4Muxer::onTrackReady(const Track::Ptr &track) { h264_track->getVideoHeight(), extra_data, extra_data_size); - _codec_to_trackid[track->getCodecId()] = track_id; + + if(track_id < 0){ + WarnL << "添加H264 Track失败:" << track_id; + return; + } + track_info info; + info.track_id = track_id; + _codec_to_trackid[track->getCodecId()] = info; } break; case CodecH265: { @@ -158,7 +198,13 @@ void MP4Muxer::onTrackReady(const Track::Ptr &track) { h265_track->getVideoHeight(), extra_data, extra_data_size); - _codec_to_trackid[track->getCodecId()] = track_id; + if(track_id < 0){ + WarnL << "添加H265 Track失败:" << track_id; + return; + } + track_info info; + info.track_id = track_id; + _codec_to_trackid[track->getCodecId()] = info; } break; default: @@ -171,7 +217,7 @@ void MP4Muxer::onTrackReady(const Track::Ptr &track) { MP4MuxerFile::MP4MuxerFile(const char *file) { //创建文件 - auto fp = File::createfile_file(file,"wb"); + auto fp = File::createfile_file(file,"wb+"); if(!fp){ throw std::runtime_error(string("打开文件失败:") + file); } diff --git a/src/MediaFile/MP4Muxer.h b/src/MediaFile/MP4Muxer.h index 88f7a028..a458b4ca 100644 --- a/src/MediaFile/MP4Muxer.h +++ b/src/MediaFile/MP4Muxer.h @@ -74,7 +74,12 @@ protected: */ void onTrackFrame(const Frame::Ptr &frame) override; private: - map _codec_to_trackid; + struct track_info{ + int track_id = -1; + uint32_t start_dts = 0; + uint32_t start_pts = 0; + }; + map _codec_to_trackid; }; diff --git a/src/MediaFile/Mp4Maker.cpp b/src/MediaFile/Mp4Maker.cpp index d4f814ee..305b7ad5 100644 --- a/src/MediaFile/Mp4Maker.cpp +++ b/src/MediaFile/Mp4Maker.cpp @@ -57,9 +57,7 @@ Mp4Maker::Mp4Maker(const string& strPath, const string &strVhost, const string &strApp, const string &strStreamId) { - DebugL << strPath; _strPath = strPath; - /////record 业务逻辑////// _info.strAppName = strApp; _info.strStreamId = strStreamId; From 13a6d3ac16e6851fad78be93252834108b6469d2 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Thu, 1 Aug 2019 22:07:40 +0800 Subject: [PATCH 09/30] =?UTF-8?q?=E5=AE=8C=E5=96=84=E5=86=99mp4=E6=96=87?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/MediaFile/Mp4Maker.cpp | 9 +++++---- src/MediaFile/Mp4Maker.h | 10 ++++++---- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/MediaFile/Mp4Maker.cpp b/src/MediaFile/Mp4Maker.cpp index 305b7ad5..a4ec0d89 100644 --- a/src/MediaFile/Mp4Maker.cpp +++ b/src/MediaFile/Mp4Maker.cpp @@ -147,11 +147,12 @@ void Mp4Maker::onTrackFrame(const Frame::Ptr &frame) { } } -void Mp4Maker::onAllTrackReady() { +void Mp4Maker::onTrackReady(const Track::Ptr & track){ //保存所有的track,为创建MP4MuxerFile做准备 - _tracks.emplace_back(getTrack(TrackVideo)); - _tracks.emplace_back(getTrack(TrackAudio)); - _haveVideo = getTrack(TrackVideo).operator bool(); + _tracks.emplace_back(track); + if(track->getTrackType() == TrackVideo){ + _haveVideo = true; + } } } /* namespace mediakit */ diff --git a/src/MediaFile/Mp4Maker.h b/src/MediaFile/Mp4Maker.h index 1d46a7fa..cef69701 100644 --- a/src/MediaFile/Mp4Maker.h +++ b/src/MediaFile/Mp4Maker.h @@ -70,10 +70,12 @@ private: */ void onTrackFrame(const Frame::Ptr &frame) override ; - /** - * 所有Track准备好了 - */ - void onAllTrackReady() override; + /** + * 某track已经准备好,其ready()状态返回true, + * 此时代表可以获取其例如sps pps等相关信息了 + * @param track + */ + void onTrackReady(const Track::Ptr & track) override; private: void createFile(); void closeFile(); From 1f8901981861b210d611b2d55708cad736e8cd80 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Thu, 1 Aug 2019 22:13:26 +0800 Subject: [PATCH 10/30] =?UTF-8?q?=E5=86=99mp4=E6=96=87=E4=BB=B6=E7=BC=93?= =?UTF-8?q?=E5=AD=98=E5=8F=AF=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Common/config.cpp | 4 ++++ src/Common/config.h | 2 ++ src/MediaFile/MP4Muxer.cpp | 9 +++++---- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/Common/config.cpp b/src/Common/config.cpp index 42aedb2d..1b4bf795 100644 --- a/src/Common/config.cpp +++ b/src/Common/config.cpp @@ -260,11 +260,15 @@ const string kFileSecond = RECORD_FIELD"fileSecond"; #define RECORD_FILE_PATH HTTP_ROOT_PATH const string kFilePath = RECORD_FIELD"filePath"; +//mp4文件写缓存大小 +const string kFileBufSize = RECORD_FIELD"fileBufSize"; + onceToken token([](){ mINI::Instance()[kAppName] = RECORD_APP_NAME; mINI::Instance()[kSampleMS] = RECORD_SAMPLE_MS; mINI::Instance()[kFileSecond] = RECORD_FILE_SECOND; mINI::Instance()[kFilePath] = RECORD_FILE_PATH; + mINI::Instance()[kFileBufSize] = 64 * 1024; },nullptr); } //namespace Record diff --git a/src/Common/config.h b/src/Common/config.h index 8807d175..6817e02e 100644 --- a/src/Common/config.h +++ b/src/Common/config.h @@ -255,6 +255,8 @@ extern const string kSampleMS; extern const string kFileSecond; //录制文件路径 extern const string kFilePath; +//mp4文件写缓存大小 +extern const string kFileBufSize; } //namespace Record ////////////HLS相关配置/////////// diff --git a/src/MediaFile/MP4Muxer.cpp b/src/MediaFile/MP4Muxer.cpp index eb5a9b56..afa78762 100644 --- a/src/MediaFile/MP4Muxer.cpp +++ b/src/MediaFile/MP4Muxer.cpp @@ -28,6 +28,7 @@ #include "MP4Muxer.h" #include "Util/File.h" +#include "Common/config.h" namespace mediakit{ @@ -213,8 +214,6 @@ void MP4Muxer::onTrackReady(const Track::Ptr &track) { } } -#define FILE_BUF_SIZE (64 * 1024) - MP4MuxerFile::MP4MuxerFile(const char *file) { //创建文件 auto fp = File::createfile_file(file,"wb+"); @@ -222,8 +221,10 @@ MP4MuxerFile::MP4MuxerFile(const char *file) { throw std::runtime_error(string("打开文件失败:") + file); } + GET_CONFIG(uint32_t,mp4BufSize,Record::kFileBufSize); + //新建文件io缓存 - std::shared_ptr file_buf(new char[FILE_BUF_SIZE],[](char *ptr){ + std::shared_ptr file_buf(new char[mp4BufSize],[](char *ptr){ if(ptr){ delete [] ptr; } @@ -231,7 +232,7 @@ MP4MuxerFile::MP4MuxerFile(const char *file) { if(file_buf){ //设置文件io缓存 - setvbuf(fp, file_buf.get(), _IOFBF, FILE_BUF_SIZE); + setvbuf(fp, file_buf.get(), _IOFBF, mp4BufSize); } //创建智能指针 From 4d215a8e2bc0de5e4ab2c4c2bc3b52df6afc7408 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Thu, 1 Aug 2019 22:21:55 +0800 Subject: [PATCH 11/30] =?UTF-8?q?=E8=BF=98=E5=8E=9F=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_server.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_server.cpp b/tests/test_server.cpp index c34fd255..7aaac9f7 100644 --- a/tests/test_server.cpp +++ b/tests/test_server.cpp @@ -258,7 +258,7 @@ int main(int argc,char *argv[]) { //rtsp://127.0.0.1/record/live/0/2017-04-11/11-09-38.mp4 //rtmp://127.0.0.1/record/live/0/2017-04-11/11-09-38.mp4 - PlayerProxy::Ptr player(new PlayerProxy(DEFAULT_VHOST, "live", to_string(i).data(),false,false,false,true)); + PlayerProxy::Ptr player(new PlayerProxy(DEFAULT_VHOST, "live", to_string(i).data())); //指定RTP over TCP(播放rtsp时有效) (*player)[kRtpType] = Rtsp::RTP_TCP; //开始播放,如果播放失败或者播放中止,将会自动重试若干次,重试次数在配置文件中配置,默认一直重试 From d3d7fe1bd1bab81b2c9a4e69dfe1475e3b0e00e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=8F=E6=A5=9A?= <771730766@qq.com> Date: Thu, 1 Aug 2019 22:28:47 +0800 Subject: [PATCH 12/30] =?UTF-8?q?mp4=E5=BD=95=E5=88=B6=E6=94=AF=E6=8C=81H2?= =?UTF-8?q?65?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bfe534f7..7622e9cc 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ | RTMP --> RTSP[S] | Y | N | Y | N | | RTSP[S] --> HLS | Y | Y | Y | N | | RTMP --> HLS | Y | N | Y | N | -| RTSP[S] --> MP4 | Y | N | Y | N | +| RTSP[S] --> MP4 | Y | Y | Y | N | | RTMP --> MP4 | Y | N | Y | N | | MP4 --> RTSP[S] | Y | N | Y | N | | MP4 --> RTMP | Y | N | Y | N | From 0980bde12d0e8813277d86c6f1c3a14b92df83fb Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Thu, 1 Aug 2019 22:32:04 +0800 Subject: [PATCH 13/30] =?UTF-8?q?mp4=E5=BD=95=E5=88=B6=E6=94=AF=E6=8C=81h2?= =?UTF-8?q?65?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++-- README_CN.md | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7622e9cc..4e09398f 100644 --- a/README.md +++ b/README.md @@ -73,9 +73,9 @@ | feature/codec | H264 | H265 | AAC | other | | :-----------: | :--: | :--: | :--: | :---: | | RTSP[S] push | Y | Y | Y | Y | -| RTSP proxy | Y | Y | Y | N | +| RTSP proxy | Y | Y | Y | Y | | RTMP push | Y | Y | Y | Y | -| RTMP proxy | Y | N | Y | N | +| RTMP proxy | Y | Y | Y | Y | - RTP transport: diff --git a/README_CN.md b/README_CN.md index bc277367..866c5b3f 100644 --- a/README_CN.md +++ b/README_CN.md @@ -78,7 +78,7 @@ | RTMP --> RTSP[S] | Y | N | Y | N | | RTSP[S] --> HLS | Y | Y | Y | N | | RTMP --> HLS | Y | N | Y | N | - | RTSP[S] --> MP4 | Y | N | Y | N | + | RTSP[S] --> MP4 | Y | Y | Y | N | | RTMP --> MP4 | Y | N | Y | N | | MP4 --> RTSP[S] | Y | N | Y | N | | MP4 --> RTMP | Y | N | Y | N | @@ -88,9 +88,9 @@ | 功能/编码格式 | H264 | H265 | AAC | other | | :------------------------------: | :--: | :--: | :--: | :---: | | RTSP[S]推流 | Y | Y | Y | Y | - | RTSP拉流代理 | Y | Y | Y | N | + | RTSP拉流代理 | Y | Y | Y | Y | | RTMP推流 | Y | Y | Y | Y | - | RTMP拉流代理 | Y | N | Y | N | + | RTMP拉流代理 | Y | Y | Y | Y | - RTP传输方式: From 0d57664faca05405df730824680b75da3760d3e2 Mon Sep 17 00:00:00 2001 From: zqsong Date: Fri, 2 Aug 2019 10:46:16 +0800 Subject: [PATCH 14/30] =?UTF-8?q?=E5=AE=8C=E5=96=84H265=20sps=E8=A7=A3?= =?UTF-8?q?=E6=9E=90,=E7=BB=9F=E4=B8=80=E5=91=BD=E5=90=8D=E9=A3=8E?= =?UTF-8?q?=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Extension/H265.cpp | 42 +- src/Extension/H265.h | 6 +- src/Extension/SPSParser.c | 1047 ++++++++++++++++++++----------------- src/Extension/SPSParser.h | 276 +++++----- 4 files changed, 747 insertions(+), 624 deletions(-) diff --git a/src/Extension/H265.cpp b/src/Extension/H265.cpp index 5c4aa916..4287020a 100644 --- a/src/Extension/H265.cpp +++ b/src/Extension/H265.cpp @@ -32,24 +32,40 @@ namespace mediakit{ -bool getAVCH265Info(const string& strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps) { - return getAVC265Info(strSps.data(),strSps.size(),iVideoWidth,iVideoHeight,iVideoFps); +bool getAVCH265Info(const string& strVps, const string& strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps) { + return getAVC265Info(strVps.data(),strVps.size(),strSps.data(),strSps.size(),iVideoWidth,iVideoHeight,iVideoFps); } -bool getAVC265Info(const char * sps,int sps_len,int &iVideoWidth, int &iVideoHeight, float &iVideoFps){ +bool getAVC265Info(const char * vps, int vps_len,const char * sps,int sps_len,int &iVideoWidth, int &iVideoHeight, float &iVideoFps){ T_GetBitContext tGetBitBuf; - T_HEVCSPS tH265SpsInfo; - memset(&tGetBitBuf,0,sizeof(tGetBitBuf)); - memset(&tH265SpsInfo,0,sizeof(tH265SpsInfo)); - tGetBitBuf.pu8Buf = (uint8_t*)sps ; - tGetBitBuf.iBufSize = sps_len ; - if(0 != h265DecSeqParameterSet((void *) &tGetBitBuf, &tH265SpsInfo)){ - return false; - } + T_HEVCSPS tH265SpsInfo; + T_HEVCVPS tH265VpsInfo; + if ( vps_len > 2 ){ + memset(&tGetBitBuf,0,sizeof(tGetBitBuf)); + memset(&tH265VpsInfo,0,sizeof(tH265VpsInfo)); + tGetBitBuf.pu8Buf = (uint8_t*)vps+2; + tGetBitBuf.iBufSize = vps_len-2; + if(0 != h265DecVideoParameterSet((void *) &tGetBitBuf, &tH265VpsInfo)){ + return false; + } + } + + if ( sps_len > 2 ){ + memset(&tGetBitBuf,0,sizeof(tGetBitBuf)); + memset(&tH265SpsInfo,0,sizeof(tH265SpsInfo)); + tGetBitBuf.pu8Buf = (uint8_t*)sps+2; + tGetBitBuf.iBufSize = sps_len-2; + if(0 != h265DecSeqParameterSet((void *) &tGetBitBuf, &tH265SpsInfo)){ + return false; + } + } + else + return false; h265GetWidthHeight(&tH265SpsInfo, &iVideoWidth, &iVideoHeight); - h265GeFramerate(&tH265SpsInfo, &iVideoFps); - //ErrorL << iVideoWidth << " " << iVideoHeight << " " << iVideoFps; + iVideoFps = 0; + h265GeFramerate(&tH265VpsInfo, &tH265SpsInfo, &iVideoFps); +// ErrorL << iVideoWidth << " " << iVideoHeight << " " << iVideoFps; return true; } diff --git a/src/Extension/H265.h b/src/Extension/H265.h index 7063d470..e3bf890d 100644 --- a/src/Extension/H265.h +++ b/src/Extension/H265.h @@ -36,8 +36,8 @@ using namespace toolkit; namespace mediakit { -bool getAVCH265Info(const string& strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps); -bool getAVC265Info(const char * sps,int sps_len,int &iVideoWidth, int &iVideoHeight, float &iVideoFps); +bool getAVCH265Info(const string& strVps,const string& strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps); +bool getAVC265Info(const char * vps, int vps_len,const char * sps,int sps_len,int &iVideoWidth, int &iVideoHeight, float &iVideoFps); /** * 265帧类 @@ -312,7 +312,7 @@ private: * 解析sps获取宽高fps */ void onReady(){ - getAVCH265Info(_sps,_width,_height,_fps); + getAVCH265Info(_vps,_sps,_width,_height,_fps); } Track::Ptr clone() override { return std::make_shared::type>(*this); diff --git a/src/Extension/SPSParser.c b/src/Extension/SPSParser.c index 375af389..dbc90ed4 100644 --- a/src/Extension/SPSParser.c +++ b/src/Extension/SPSParser.c @@ -129,15 +129,15 @@ const uint8_t g_au8FfZigzagDirect[64] = { }; -static const uint8_t hevc_sub_width_c[] = { +static const uint8_t sg_au8HevcSubWidthC[] = { 1, 2, 2, 1 }; -static const uint8_t hevc_sub_height_c[] = { +static const uint8_t sg_au8HevcSubHeightC[] = { 1, 2, 1, 1 }; -static const uint8_t default_scaling_list_intra[] = { +static const uint8_t sg_au8DefaultScalingListIntra[] = { 16, 16, 16, 16, 17, 18, 21, 24, 16, 16, 16, 16, 17, 19, 22, 25, 16, 16, 17, 18, 20, 22, 25, 29, @@ -148,7 +148,7 @@ static const uint8_t default_scaling_list_intra[] = { 24, 25, 29, 36, 47, 65, 88, 115 }; -static const uint8_t default_scaling_list_inter[] = { +static const uint8_t sg_au8DefaultScalingListInter[] = { 16, 16, 16, 16, 17, 18, 20, 24, 16, 16, 16, 17, 18, 20, 24, 25, 16, 16, 17, 18, 20, 24, 25, 28, @@ -160,21 +160,21 @@ static const uint8_t default_scaling_list_inter[] = { }; -const uint8_t ff_hevc_diag_scan4x4_x[16] = { +const uint8_t g_au8HevcDiagScan4x4X[16] = { 0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 1, 2, 3, 2, 3, 3, }; -const uint8_t ff_hevc_diag_scan4x4_y[16] = { +const uint8_t g_au8HevcDiagScan4x4Y[16] = { 0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 3, 2, 3, }; -const uint8_t ff_hevc_diag_scan8x8_x[64] = { +const uint8_t g_au8HevcDiagScan8x8X[64] = { 0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, @@ -193,7 +193,7 @@ const uint8_t ff_hevc_diag_scan8x8_x[64] = { 7, 6, 7, 7, }; -const uint8_t ff_hevc_diag_scan8x8_y[64] = { +const uint8_t g_au8HevcDiagScan8x8Y[64] = { 0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 4, 3, @@ -212,7 +212,7 @@ const uint8_t ff_hevc_diag_scan8x8_y[64] = { 5, 7, 6, 7, }; -static const T_AVRational vui_sar[] = { +static const T_AVRational sg_atVuiSar[] = { { 0, 1 }, { 1, 1 }, { 12, 11 }, @@ -733,17 +733,17 @@ static inline int decodeVuiParameters(void *pvBuf, T_SPS *ptSps) ptSps->tSar.den = 0; } - if (getOneBit(pvBuf)) /* overscan_info_present_flag */ - getOneBit(pvBuf); /* overscan_appropriate_flag */ + if (getOneBit(pvBuf)) /* iOverscanInfoPresentFlag */ + getOneBit(pvBuf); /* iOverscanAppropriateFlag */ ptSps->iVideoSignalTypePresentFlag = getOneBit(pvBuf); if (ptSps->iVideoSignalTypePresentFlag) { getBits(pvBuf, 3); /* video_format */ - ptSps->iFullRange = getOneBit(pvBuf); /* video_full_range_flag */ + ptSps->iFullRange = getOneBit(pvBuf); /* iVideoFullRangeFlag */ ptSps->iColourDescriptionPresentFlag = getOneBit(pvBuf); if (ptSps->iColourDescriptionPresentFlag) { - ptSps->tColorPrimaries = getBits(pvBuf, 8); /* colour_primaries */ + ptSps->tColorPrimaries = getBits(pvBuf, 8); /* u8ColourPrimaries */ ptSps->tColorTrc = getBits(pvBuf, 8); /* transfer_characteristics */ ptSps->tColorspace = getBits(pvBuf, 8); /* matrix_coefficients */ if (ptSps->tColorPrimaries >= AVCOL_PRI_NB) @@ -800,7 +800,7 @@ static inline int decodeVuiParameters(void *pvBuf, T_SPS *ptSps) return 0; ptSps->iBitstreamRestrictionFlag = getOneBit(pvBuf); if (ptSps->iBitstreamRestrictionFlag) { - getOneBit(pvBuf); /* motion_vectors_over_pic_boundaries_flag */ + getOneBit(pvBuf); /* motion_vectors_over_pic_boundaries_flag */ parseUe(pvBuf); //get_ue_golomb(&h->gb); /* max_bytes_per_pic_denom */ parseUe(pvBuf); @@ -1035,8 +1035,8 @@ int h264DecSeqParameterSet(void *pvBufSrc, T_SPS *ptSps) unsigned int uiCropRight = parseUe(pvBuf); unsigned int uiCropTop = parseUe(pvBuf); unsigned int uiCropBottom = parseUe(pvBuf); - int width = 16 * ptSps->iMbWidth; - int height = 16 * ptSps->iMbHeight * (2 - ptSps->iFrameMbsOnlyFlag); + int iWidth = 16 * ptSps->iMbWidth; + int iHeight = 16 * ptSps->iMbHeight * (2 - ptSps->iFrameMbsOnlyFlag); if(1) { @@ -1055,11 +1055,11 @@ int h264DecSeqParameterSet(void *pvBufSrc, T_SPS *ptSps) uiCropRight > (unsigned)INT_MAX / 4 / step_x || uiCropTop > (unsigned)INT_MAX / 4 / step_y || uiCropBottom> (unsigned)INT_MAX / 4 / step_y || - (uiCropLeft + uiCropRight ) * step_x >= width || - (uiCropTop + uiCropBottom) * step_y >= height + (uiCropLeft + uiCropRight ) * step_x >= iWidth || + (uiCropTop + uiCropBottom) * step_y >= iHeight ) { - RPT(RPT_ERR, "crop values invalid %d %d %d %d / %d %d\n", uiCropLeft, uiCropRight, uiCropTop, uiCropBottom, width, height); + RPT(RPT_ERR, "crop values invalid %d %d %d %d / %d %d\n", uiCropLeft, uiCropRight, uiCropTop, uiCropBottom, iWidth, iHeight); iRet = -1; goto exit; } @@ -1129,37 +1129,37 @@ exit: } -static int decodeProfileTierLevel(T_GetBitContext *pvBuf, T_PTLCommon *ptl) +static int decodeProfileTierLevel(T_GetBitContext *pvBuf, T_PTLCommon *tPtl) { int i; if (getBitsLeft(pvBuf) < 2+1+5 + 32 + 4 + 16 + 16 + 12) return -1; - ptl->profile_space = getBits(pvBuf, 2); - ptl->tier_flag = getOneBit(pvBuf); - ptl->profile_idc = getBits(pvBuf, 5); - if (ptl->profile_idc == T_PROFILE_HEVC_MAIN) + tPtl->u8ProfileSpace = getBits(pvBuf, 2); + tPtl->u8TierFlag = getOneBit(pvBuf); + tPtl->u8ProfileIdc = getBits(pvBuf, 5); + if (tPtl->u8ProfileIdc == T_PROFILE_HEVC_MAIN) RPT(RPT_DBG, "Main profile bitstream\n"); - else if (ptl->profile_idc == T_PROFILE_HEVC_MAIN_10) + else if (tPtl->u8ProfileIdc == T_PROFILE_HEVC_MAIN_10) RPT(RPT_DBG, "Main 10 profile bitstream\n"); - else if (ptl->profile_idc == T_PROFILE_HEVC_MAIN_STILL_PICTURE) + else if (tPtl->u8ProfileIdc == T_PROFILE_HEVC_MAIN_STILL_PICTURE) RPT(RPT_DBG, "Main Still Picture profile bitstream\n"); - else if (ptl->profile_idc == T_PROFILE_HEVC_REXT) + else if (tPtl->u8ProfileIdc == T_PROFILE_HEVC_REXT) RPT(RPT_DBG, "Range Extension profile bitstream\n"); else - RPT(RPT_WRN, "Unknown HEVC profile: %d\n", ptl->profile_idc); + RPT(RPT_WRN, "Unknown HEVC profile: %d\n", tPtl->u8ProfileIdc); for (i = 0; i < 32; i++) { - ptl->profile_compatibility_flag[i] = getOneBit(pvBuf); + tPtl->au8ProfileCompatibilityFlag[i] = getOneBit(pvBuf); - if (ptl->profile_idc == 0 && i > 0 && ptl->profile_compatibility_flag[i]) - ptl->profile_idc = i; + if (tPtl->u8ProfileIdc == 0 && i > 0 && tPtl->au8ProfileCompatibilityFlag[i]) + tPtl->u8ProfileIdc = i; } - ptl->progressive_source_flag = getOneBit(pvBuf); - ptl->interlaced_source_flag = getOneBit(pvBuf); - ptl->non_packed_constraint_flag = getOneBit(pvBuf); - ptl->frame_only_constraint_flag = getOneBit(pvBuf); + tPtl->u8ProgressiveSourceFlag = getOneBit(pvBuf); + tPtl->u8InterlacedSourceFlag = getOneBit(pvBuf); + tPtl->u8NonPackedConstraintFlag = getOneBit(pvBuf); + tPtl->u8FrameOnlyConstraintFlag = getOneBit(pvBuf); getBits(pvBuf, 16); // XXX_reserved_zero_44bits[0..15] getBits(pvBuf, 16); // XXX_reserved_zero_44bits[16..31] @@ -1169,39 +1169,39 @@ static int decodeProfileTierLevel(T_GetBitContext *pvBuf, T_PTLCommon *ptl) } -static int parsePtl(T_GetBitContext *pvBuf, T_PTL *ptl, int max_num_sub_layers) +static int parsePtl(T_GetBitContext *pvBuf, T_PTL *tPtl, int max_num_sub_layers) { int i; - if (decodeProfileTierLevel(pvBuf, &ptl->general_ptl) < 0 || + if (decodeProfileTierLevel(pvBuf, &tPtl->tGeneralPtl) < 0 || getBitsLeft(pvBuf) < 8 + (8*2 * (max_num_sub_layers - 1 > 0))) { RPT(RPT_ERR, "PTL information too short\n"); return -1; } - ptl->general_ptl.level_idc = getBits(pvBuf, 8); + tPtl->tGeneralPtl.u8LevelIdc = getBits(pvBuf, 8); for (i = 0; i < max_num_sub_layers - 1; i++) { - ptl->sub_layer_profile_present_flag[i] = getOneBit(pvBuf); - ptl->sub_layer_level_present_flag[i] = getOneBit(pvBuf); + tPtl->au8SubLayerProfilePresentFlag[i] = getOneBit(pvBuf); + tPtl->au8SubLayerLevelPresentFlag[i] = getOneBit(pvBuf); } if (max_num_sub_layers - 1> 0) for (i = max_num_sub_layers - 1; i < 8; i++) getBits(pvBuf, 2); // reserved_zero_2bits[i] for (i = 0; i < max_num_sub_layers - 1; i++) { - if (ptl->sub_layer_profile_present_flag[i] && - decodeProfileTierLevel(pvBuf, &ptl->sub_layer_ptl[i]) < 0) { + if (tPtl->au8SubLayerProfilePresentFlag[i] && + decodeProfileTierLevel(pvBuf, &tPtl->atSubLayerPtl[i]) < 0) { RPT(RPT_ERR, "PTL information for sublayer %i too short\n", i); return -1; } - if (ptl->sub_layer_level_present_flag[i]) { + if (tPtl->au8SubLayerLevelPresentFlag[i]) { if (getBitsLeft(pvBuf) < 8) { RPT(RPT_ERR, "Not enough data for sublayer %i level_idc\n", i); return -1; } else - ptl->sub_layer_ptl[i].level_idc = getBits(pvBuf, 8); + tPtl->atSubLayerPtl[i].u8LevelIdc = getBits(pvBuf, 8); } } @@ -1215,31 +1215,31 @@ static void setDefaultScalingListData(T_ScalingList *sl) for (matrixId = 0; matrixId < 6; matrixId++) { // 4x4 default is 16 - memset(sl->sl[0][matrixId], 16, 16); - sl->sl_dc[0][matrixId] = 16; // default for 16x16 - sl->sl_dc[1][matrixId] = 16; // default for 32x32 + memset(sl->aaau8Sl[0][matrixId], 16, 16); + sl->aau8SlDc[0][matrixId] = 16; // default for 16x16 + sl->aau8SlDc[1][matrixId] = 16; // default for 32x32 } - memcpy(sl->sl[1][0], default_scaling_list_intra, 64); - memcpy(sl->sl[1][1], default_scaling_list_intra, 64); - memcpy(sl->sl[1][2], default_scaling_list_intra, 64); - memcpy(sl->sl[1][3], default_scaling_list_inter, 64); - memcpy(sl->sl[1][4], default_scaling_list_inter, 64); - memcpy(sl->sl[1][5], default_scaling_list_inter, 64); - memcpy(sl->sl[2][0], default_scaling_list_intra, 64); - memcpy(sl->sl[2][1], default_scaling_list_intra, 64); - memcpy(sl->sl[2][2], default_scaling_list_intra, 64); - memcpy(sl->sl[2][3], default_scaling_list_inter, 64); - memcpy(sl->sl[2][4], default_scaling_list_inter, 64); - memcpy(sl->sl[2][5], default_scaling_list_inter, 64); - memcpy(sl->sl[3][0], default_scaling_list_intra, 64); - memcpy(sl->sl[3][1], default_scaling_list_intra, 64); - memcpy(sl->sl[3][2], default_scaling_list_intra, 64); - memcpy(sl->sl[3][3], default_scaling_list_inter, 64); - memcpy(sl->sl[3][4], default_scaling_list_inter, 64); - memcpy(sl->sl[3][5], default_scaling_list_inter, 64); + memcpy(sl->aaau8Sl[1][0], sg_au8DefaultScalingListIntra, 64); + memcpy(sl->aaau8Sl[1][1], sg_au8DefaultScalingListIntra, 64); + memcpy(sl->aaau8Sl[1][2], sg_au8DefaultScalingListIntra, 64); + memcpy(sl->aaau8Sl[1][3], sg_au8DefaultScalingListInter, 64); + memcpy(sl->aaau8Sl[1][4], sg_au8DefaultScalingListInter, 64); + memcpy(sl->aaau8Sl[1][5], sg_au8DefaultScalingListInter, 64); + memcpy(sl->aaau8Sl[2][0], sg_au8DefaultScalingListIntra, 64); + memcpy(sl->aaau8Sl[2][1], sg_au8DefaultScalingListIntra, 64); + memcpy(sl->aaau8Sl[2][2], sg_au8DefaultScalingListIntra, 64); + memcpy(sl->aaau8Sl[2][3], sg_au8DefaultScalingListInter, 64); + memcpy(sl->aaau8Sl[2][4], sg_au8DefaultScalingListInter, 64); + memcpy(sl->aaau8Sl[2][5], sg_au8DefaultScalingListInter, 64); + memcpy(sl->aaau8Sl[3][0], sg_au8DefaultScalingListIntra, 64); + memcpy(sl->aaau8Sl[3][1], sg_au8DefaultScalingListIntra, 64); + memcpy(sl->aaau8Sl[3][2], sg_au8DefaultScalingListIntra, 64); + memcpy(sl->aaau8Sl[3][3], sg_au8DefaultScalingListInter, 64); + memcpy(sl->aaau8Sl[3][4], sg_au8DefaultScalingListInter, 64); + memcpy(sl->aaau8Sl[3][5], sg_au8DefaultScalingListInter, 64); } -static int scalingListData(T_GetBitContext *pvBuf, T_ScalingList *sl, T_HEVCSPS *sps) +static int scalingListData(T_GetBitContext *pvBuf, T_ScalingList *sl, T_HEVCSPS *ptSps) { uint8_t scaling_list_pred_mode_flag; int32_t scaling_list_dc_coef[2][6]; @@ -1262,11 +1262,11 @@ static int scalingListData(T_GetBitContext *pvBuf, T_ScalingList *sl, T_HEVCSPS return -1; } - memcpy(sl->sl[size_id][matrix_id], - sl->sl[size_id][matrix_id - delta], + memcpy(sl->aaau8Sl[size_id][matrix_id], + sl->aaau8Sl[size_id][matrix_id - delta], size_id > 0 ? 64 : 16); if (size_id > 1) - sl->sl_dc[size_id - 2][matrix_id] = sl->sl_dc[size_id - 2][matrix_id - delta]; + sl->aau8SlDc[size_id - 2][matrix_id] = sl->aau8SlDc[size_id - 2][matrix_id - delta]; } } else { int next_coef, coef_num; @@ -1277,34 +1277,34 @@ static int scalingListData(T_GetBitContext *pvBuf, T_ScalingList *sl, T_HEVCSPS if (size_id > 1) { scaling_list_dc_coef[size_id - 2][matrix_id] = parseSe(pvBuf) + 8; next_coef = scaling_list_dc_coef[size_id - 2][matrix_id]; - sl->sl_dc[size_id - 2][matrix_id] = next_coef; + sl->aau8SlDc[size_id - 2][matrix_id] = next_coef; } for (i = 0; i < coef_num; i++) { if (size_id == 0) - pos = 4 * ff_hevc_diag_scan4x4_y[i] + - ff_hevc_diag_scan4x4_x[i]; + pos = 4 * g_au8HevcDiagScan4x4Y[i] + + g_au8HevcDiagScan4x4X[i]; else - pos = 8 * ff_hevc_diag_scan8x8_y[i] + - ff_hevc_diag_scan8x8_x[i]; + pos = 8 * g_au8HevcDiagScan8x8Y[i] + + g_au8HevcDiagScan8x8X[i]; scaling_list_delta_coef = parseSe(pvBuf); next_coef = (next_coef + 256U + scaling_list_delta_coef) % 256; - sl->sl[size_id][matrix_id][pos] = next_coef; + sl->aaau8Sl[size_id][matrix_id][pos] = next_coef; } } } - if (sps->chroma_format_idc == 3) { + if (ptSps->iChromaFormatIdc == 3) { for (i = 0; i < 64; i++) { - sl->sl[3][1][i] = sl->sl[2][1][i]; - sl->sl[3][2][i] = sl->sl[2][2][i]; - sl->sl[3][4][i] = sl->sl[2][4][i]; - sl->sl[3][5][i] = sl->sl[2][5][i]; + sl->aaau8Sl[3][1][i] = sl->aaau8Sl[2][1][i]; + sl->aaau8Sl[3][2][i] = sl->aaau8Sl[2][2][i]; + sl->aaau8Sl[3][4][i] = sl->aaau8Sl[2][4][i]; + sl->aaau8Sl[3][5][i] = sl->aaau8Sl[2][5][i]; } - sl->sl_dc[1][1] = sl->sl_dc[0][1]; - sl->sl_dc[1][2] = sl->sl_dc[0][2]; - sl->sl_dc[1][4] = sl->sl_dc[0][4]; - sl->sl_dc[1][5] = sl->sl_dc[0][5]; + sl->aau8SlDc[1][1] = sl->aau8SlDc[0][1]; + sl->aau8SlDc[1][2] = sl->aau8SlDc[0][2]; + sl->aau8SlDc[1][4] = sl->aau8SlDc[0][4]; + sl->aau8SlDc[1][5] = sl->aau8SlDc[0][5]; } @@ -1312,60 +1312,60 @@ static int scalingListData(T_GetBitContext *pvBuf, T_ScalingList *sl, T_HEVCSPS } int hevcDecodeShortTermRps(T_GetBitContext *pvBuf, - T_ShortTermRPS *rps, const T_HEVCSPS *sps, int is_slice_header) + T_ShortTermRPS *rps, const T_HEVCSPS *ptSps, int is_slice_header) { uint8_t rps_predict = 0; - int delta_poc; + int au32DeltaPoc; int k0 = 0; int k1 = 0; int k = 0; int i; - if (rps != sps->st_rps && sps->nb_st_rps) + if (rps != ptSps->atStRps && ptSps->uiNbStRps) rps_predict = getOneBit(pvBuf); if (rps_predict) { - const T_ShortTermRPS *rps_ridx; - int delta_rps; - unsigned abs_delta_rps; - uint8_t use_delta_flag = 0; - uint8_t delta_rps_sign; + const T_ShortTermRPS *ptRpsRidx; + int iDeltaRps; + unsigned int uiAbsDeltaRps; + uint8_t u8UseDeltaFlag = 0; + uint8_t u8DeltaRpsSign; if (is_slice_header) { - unsigned int delta_idx = parseUe(pvBuf) + 1; - if (delta_idx > sps->nb_st_rps) { + unsigned int uiDeltaIdx = parseUe(pvBuf) + 1; + if (u8DeltaRpsSign > ptSps->uiNbStRps) { RPT(RPT_ERR, "Invalid value of delta_idx in slice header RPS: %d > %d.\n", - delta_idx, sps->nb_st_rps); + u8DeltaRpsSign, ptSps->uiNbStRps); return -1; } - rps_ridx = &sps->st_rps[sps->nb_st_rps - delta_idx]; - rps->rps_idx_num_delta_pocs = rps_ridx->num_delta_pocs; + ptRpsRidx = &ptSps->atStRps[ptSps->uiNbStRps - u8DeltaRpsSign]; + rps->iRpsIdxNumDeltaPocs = ptRpsRidx->iNumDeltaPocs; } else - rps_ridx = &sps->st_rps[rps - sps->st_rps - 1]; + ptRpsRidx = &ptSps->atStRps[rps - ptSps->atStRps - 1]; - delta_rps_sign = getOneBit(pvBuf); - abs_delta_rps = parseUe(pvBuf) + 1; - if (abs_delta_rps < 1 || abs_delta_rps > 32768) { + u8DeltaRpsSign = getOneBit(pvBuf); + uiAbsDeltaRps = parseUe(pvBuf) + 1; + if (uiAbsDeltaRps < 1 || uiAbsDeltaRps > 32768) { RPT(RPT_ERR, - "Invalid value of abs_delta_rps: %d\n", - abs_delta_rps); + "Invalid value of uiAbsDeltaRps: %d\n", + uiAbsDeltaRps); return -1; } - delta_rps = (1 - (delta_rps_sign << 1)) * abs_delta_rps; - for (i = 0; i <= rps_ridx->num_delta_pocs; i++) { - int used = rps->used[k] = getOneBit(pvBuf); + iDeltaRps = (1 - (u8DeltaRpsSign << 1)) * uiAbsDeltaRps; + for (i = 0; i <= ptRpsRidx->iNumDeltaPocs; i++) { + int used = rps->au8Used[k] = getOneBit(pvBuf); if (!used) - use_delta_flag = getOneBit(pvBuf); + u8UseDeltaFlag = getOneBit(pvBuf); - if (used || use_delta_flag) { - if (i < rps_ridx->num_delta_pocs) - delta_poc = delta_rps + rps_ridx->delta_poc[i]; + if (used || u8UseDeltaFlag) { + if (i < ptRpsRidx->iNumDeltaPocs) + au32DeltaPoc = iDeltaRps + ptRpsRidx->au32DeltaPoc[i]; else - delta_poc = delta_rps; - rps->delta_poc[k] = delta_poc; - if (delta_poc < 0) + au32DeltaPoc = iDeltaRps; + rps->au32DeltaPoc[k] = au32DeltaPoc; + if (au32DeltaPoc < 0) k0++; else k1++; @@ -1373,83 +1373,83 @@ int hevcDecodeShortTermRps(T_GetBitContext *pvBuf, } } - if (k >= FF_ARRAY_ELEMS(rps->used)) { + if (k >= FF_ARRAY_ELEMS(rps->au8Used)) { RPT(RPT_ERR, - "Invalid num_delta_pocs: %d\n", k); + "Invalid iNumDeltaPocs: %d\n", k); return -1; } - rps->num_delta_pocs = k; - rps->num_negative_pics = k0; + rps->iNumDeltaPocs = k; + rps->uiNumNegativePics = k0; // sort in increasing order (smallest first) - if (rps->num_delta_pocs != 0) { + if (rps->iNumDeltaPocs != 0) { int used, tmp; - for (i = 1; i < rps->num_delta_pocs; i++) { - delta_poc = rps->delta_poc[i]; - used = rps->used[i]; + for (i = 1; i < rps->iNumDeltaPocs; i++) { + au32DeltaPoc = rps->au32DeltaPoc[i]; + used = rps->au8Used[i]; for (k = i - 1; k >= 0; k--) { - tmp = rps->delta_poc[k]; - if (delta_poc < tmp) { - rps->delta_poc[k + 1] = tmp; - rps->used[k + 1] = rps->used[k]; - rps->delta_poc[k] = delta_poc; - rps->used[k] = used; + tmp = rps->au32DeltaPoc[k]; + if (au32DeltaPoc < tmp) { + rps->au32DeltaPoc[k + 1] = tmp; + rps->au8Used[k + 1] = rps->au8Used[k]; + rps->au32DeltaPoc[k] = au32DeltaPoc; + rps->au8Used[k] = used; } } } } - if ((rps->num_negative_pics >> 1) != 0) { + if ((rps->uiNumNegativePics >> 1) != 0) { int used; - k = rps->num_negative_pics - 1; + k = rps->uiNumNegativePics - 1; // flip the negative values to largest first - for (i = 0; i < rps->num_negative_pics >> 1; i++) { - delta_poc = rps->delta_poc[i]; - used = rps->used[i]; - rps->delta_poc[i] = rps->delta_poc[k]; - rps->used[i] = rps->used[k]; - rps->delta_poc[k] = delta_poc; - rps->used[k] = used; + for (i = 0; i < rps->uiNumNegativePics >> 1; i++) { + au32DeltaPoc = rps->au32DeltaPoc[i]; + used = rps->au8Used[i]; + rps->au32DeltaPoc[i] = rps->au32DeltaPoc[k]; + rps->au8Used[i] = rps->au8Used[k]; + rps->au32DeltaPoc[k] = au32DeltaPoc; + rps->au8Used[k] = used; k--; } } } else { - unsigned int prev, nb_positive_pics; - rps->num_negative_pics = parseUe(pvBuf); - nb_positive_pics = parseUe(pvBuf); + unsigned int uiPrev, uiNbPositivePics; + rps->uiNumNegativePics = parseUe(pvBuf); + uiNbPositivePics = parseUe(pvBuf); - if (rps->num_negative_pics >= HEVC_MAX_REFS || - nb_positive_pics >= HEVC_MAX_REFS) { + if (rps->uiNumNegativePics >= HEVC_MAX_REFS || + uiNbPositivePics >= HEVC_MAX_REFS) { RPT(RPT_ERR, "Too many refs in a short term RPS.\n"); return -1; } - rps->num_delta_pocs = rps->num_negative_pics + nb_positive_pics; - if (rps->num_delta_pocs) { - prev = 0; - for (i = 0; i < rps->num_negative_pics; i++) { - delta_poc = parseUe(pvBuf) + 1; - if (delta_poc < 1 || delta_poc > 32768) { + rps->iNumDeltaPocs = rps->uiNumNegativePics + uiNbPositivePics; + if (rps->iNumDeltaPocs) { + uiPrev = 0; + for (i = 0; i < rps->uiNumNegativePics; i++) { + au32DeltaPoc = parseUe(pvBuf) + 1; + if (au32DeltaPoc < 1 || au32DeltaPoc > 32768) { RPT(RPT_ERR, - "Invalid value of delta_poc: %d\n", - delta_poc); + "Invalid value of au32DeltaPoc: %d\n", + au32DeltaPoc); return -1; } - prev -= delta_poc; - rps->delta_poc[i] = prev; - rps->used[i] = getOneBit(pvBuf); + uiPrev -= au32DeltaPoc; + rps->au32DeltaPoc[i] = uiPrev; + rps->au8Used[i] = getOneBit(pvBuf); } - prev = 0; - for (i = 0; i < nb_positive_pics; i++) { - delta_poc = parseUe(pvBuf) + 1; - if (delta_poc < 1 || delta_poc > 32768) { + uiPrev = 0; + for (i = 0; i < uiNbPositivePics; i++) { + au32DeltaPoc = parseUe(pvBuf) + 1; + if (au32DeltaPoc < 1 || au32DeltaPoc > 32768) { RPT(RPT_ERR, - "Invalid value of delta_poc: %d\n", - delta_poc); + "Invalid value of au32DeltaPoc: %d\n", + au32DeltaPoc); return -1; } - prev += delta_poc; - rps->delta_poc[rps->num_negative_pics + i] = prev; - rps->used[rps->num_negative_pics + i] = getOneBit(pvBuf); + uiPrev += au32DeltaPoc; + rps->au32DeltaPoc[rps->uiNumNegativePics + i] = uiPrev; + rps->au8Used[rps->uiNumNegativePics + i] = getOneBit(pvBuf); } } } @@ -1457,7 +1457,7 @@ int hevcDecodeShortTermRps(T_GetBitContext *pvBuf, } static void decodeSublayerHrd(T_GetBitContext *pvBuf, unsigned int nb_cpb, - int subpic_params_present) + int iSubpicParamsPresent) { int i; @@ -1465,7 +1465,7 @@ static void decodeSublayerHrd(T_GetBitContext *pvBuf, unsigned int nb_cpb, parseUe(pvBuf); // bit_rate_value_minus1 parseUe(pvBuf); // cpb_size_value_minus1 - if (subpic_params_present) { + if (iSubpicParamsPresent) { parseUe(pvBuf); // cpb_size_du_value_minus1 parseUe(pvBuf); // bit_rate_du_value_minus1 } @@ -1476,18 +1476,18 @@ static void decodeSublayerHrd(T_GetBitContext *pvBuf, unsigned int nb_cpb, static int decodeHrd(T_GetBitContext *pvBuf, int common_inf_present, int max_sublayers) { - int nal_params_present = 0, vcl_params_present = 0; - int subpic_params_present = 0; + int iNalParamsPresent = 0, iVclParamsPresent = 0; + int iSubpicParamsPresent = 0; int i; if (common_inf_present) { - nal_params_present = getOneBit(pvBuf); - vcl_params_present = getOneBit(pvBuf); + iNalParamsPresent = getOneBit(pvBuf); + iVclParamsPresent = getOneBit(pvBuf); - if (nal_params_present || vcl_params_present) { - subpic_params_present = getOneBit(pvBuf); + if (iNalParamsPresent || iVclParamsPresent) { + iSubpicParamsPresent = getOneBit(pvBuf); - if (subpic_params_present) { + if (iSubpicParamsPresent) { getBits(pvBuf, 8); // tick_divisor_minus2 getBits(pvBuf, 5); // du_cpb_removal_delay_increment_length_minus1 getBits(pvBuf, 1); // sub_pic_cpb_params_in_pic_timing_sei_flag @@ -1497,7 +1497,7 @@ static int decodeHrd(T_GetBitContext *pvBuf, int common_inf_present, getBits(pvBuf, 4); // bit_rate_scale getBits(pvBuf, 4); // cpb_size_scale - if (subpic_params_present) + if (iSubpicParamsPresent) getBits(pvBuf, 4); // cpb_size_du_scale getBits(pvBuf, 5); // initial_cpb_removal_delay_length_minus1 @@ -1509,12 +1509,12 @@ static int decodeHrd(T_GetBitContext *pvBuf, int common_inf_present, for (i = 0; i < max_sublayers; i++) { int low_delay = 0; unsigned int nb_cpb = 1; - int fixed_rate = getOneBit(pvBuf); + int iFixedRate = getOneBit(pvBuf); - if (!fixed_rate) - fixed_rate = getOneBit(pvBuf); + if (!iFixedRate) + iFixedRate = getOneBit(pvBuf); - if (fixed_rate) + if (iFixedRate) parseUe(pvBuf); // elemental_duration_in_tc_minus1 else low_delay = getOneBit(pvBuf); @@ -1527,20 +1527,20 @@ static int decodeHrd(T_GetBitContext *pvBuf, int common_inf_present, } } - if (nal_params_present) - decodeSublayerHrd(pvBuf, nb_cpb, subpic_params_present); - if (vcl_params_present) - decodeSublayerHrd(pvBuf, nb_cpb, subpic_params_present); + if (iNalParamsPresent) + decodeSublayerHrd(pvBuf, nb_cpb, iSubpicParamsPresent); + if (iVclParamsPresent) + decodeSublayerHrd(pvBuf, nb_cpb, iSubpicParamsPresent); } return 0; } -static void decodeVui(T_GetBitContext *pvBuf, T_HEVCSPS *sps) +static void decodeVui(T_GetBitContext *pvBuf, T_HEVCSPS *ptSps) { - T_VUI backup_vui, *vui = &sps->vui; - T_GetBitContext backup; + T_VUI tBackupVui, *tVui = &ptSps->tVui; + T_GetBitContext tBackup; int sar_present, alt = 0; RPT(RPT_DBG, "Decoding VUI\n"); @@ -1548,166 +1548,145 @@ static void decodeVui(T_GetBitContext *pvBuf, T_HEVCSPS *sps) sar_present = getOneBit(pvBuf); if (sar_present) { uint8_t sar_idx = getBits(pvBuf, 8); - if (sar_idx < FF_ARRAY_ELEMS(vui_sar)) - vui->sar = vui_sar[sar_idx]; + if (sar_idx < FF_ARRAY_ELEMS(sg_atVuiSar)) + tVui->tSar = sg_atVuiSar[sar_idx]; else if (sar_idx == 255) { - vui->sar.num = getBits(pvBuf, 16); - vui->sar.den = getBits(pvBuf, 16); + tVui->tSar.num = getBits(pvBuf, 16); + tVui->tSar.den = getBits(pvBuf, 16); } else RPT(RPT_WRN, "Unknown SAR index: %u.\n", sar_idx); } - vui->overscan_info_present_flag = getOneBit(pvBuf); - if (vui->overscan_info_present_flag) - vui->overscan_appropriate_flag = getOneBit(pvBuf); + tVui->iOverscanInfoPresentFlag = getOneBit(pvBuf); + if (tVui->iOverscanInfoPresentFlag) + tVui->iOverscanAppropriateFlag = getOneBit(pvBuf); - vui->video_signal_type_present_flag = getOneBit(pvBuf); - if (vui->video_signal_type_present_flag) { - vui->video_format = getBits(pvBuf, 3); - vui->video_full_range_flag = getOneBit(pvBuf); - vui->colour_description_present_flag = getOneBit(pvBuf); -// if (vui->video_full_range_flag && sps->pix_fmt == AV_PIX_FMT_YUV420P) -// sps->pix_fmt = AV_PIX_FMT_YUVJ420P; - if (vui->colour_description_present_flag) { - vui->colour_primaries = getBits(pvBuf, 8); - vui->transfer_characteristic = getBits(pvBuf, 8); - vui->matrix_coeffs = getBits(pvBuf, 8); - -#if 0 - // Set invalid values to "unspecified" - if (!av_color_primaries_name(vui->colour_primaries)) - vui->colour_primaries = AVCOL_PRI_UNSPECIFIED; - if (!av_color_transfer_name(vui->transfer_characteristic)) - vui->transfer_characteristic = AVCOL_TRC_UNSPECIFIED; - if (!av_color_space_name(vui->matrix_coeffs)) - vui->matrix_coeffs = AVCOL_SPC_UNSPECIFIED; - if (vui->matrix_coeffs == AVCOL_SPC_RGB) { - switch (sps->pix_fmt) { - case AV_PIX_FMT_YUV444P: - sps->pix_fmt = AV_PIX_FMT_GBRP; - break; - case AV_PIX_FMT_YUV444P10: - sps->pix_fmt = AV_PIX_FMT_GBRP10; - break; - case AV_PIX_FMT_YUV444P12: - sps->pix_fmt = AV_PIX_FMT_GBRP12; - break; - } - } -#endif + tVui->iVideoSignalTypePresentFlag = getOneBit(pvBuf); + if (tVui->iVideoSignalTypePresentFlag) { + tVui->iVideoFormat = getBits(pvBuf, 3); + tVui->iVideoFullRangeFlag = getOneBit(pvBuf); + tVui->iColourDescriptionPresentFlag = getOneBit(pvBuf); +// if (tVui->iVideoFullRangeFlag && ptSps->pix_fmt == AV_PIX_FMT_YUV420P) +// ptSps->pix_fmt = AV_PIX_FMT_YUVJ420P; + if (tVui->iColourDescriptionPresentFlag) { + tVui->u8ColourPrimaries = getBits(pvBuf, 8); + tVui->u8TransferCharacteristic = getBits(pvBuf, 8); + tVui->u8MatrixCoeffs = getBits(pvBuf, 8); } } - vui->chroma_loc_info_present_flag = getOneBit(pvBuf); - if (vui->chroma_loc_info_present_flag) { - vui->chroma_sample_loc_type_top_field = parseUe(pvBuf); - vui->chroma_sample_loc_type_bottom_field = parseUe(pvBuf); + tVui->iChromaLocInfoPresentFlag = getOneBit(pvBuf); + if (tVui->iChromaLocInfoPresentFlag) { + tVui->iChromaSampleLocTypeTopField = parseUe(pvBuf); + tVui->iChromaSampleLocTypeBottomField = parseUe(pvBuf); } - vui->neutra_chroma_indication_flag = getOneBit(pvBuf); - vui->field_seq_flag = getOneBit(pvBuf); - vui->frame_field_info_present_flag = getOneBit(pvBuf); + tVui->iNeutraChromaIndicationFlag = getOneBit(pvBuf); + tVui->iFieldSeqFlag = getOneBit(pvBuf); + tVui->iFrameFieldInfoPresentFlag = getOneBit(pvBuf); // Backup context in case an alternate header is detected - memcpy(&backup, pvBuf, sizeof(backup)); - memcpy(&backup_vui, vui, sizeof(backup_vui)); + memcpy(&tBackup, pvBuf, sizeof(tBackup)); + memcpy(&tBackupVui, tVui, sizeof(tBackupVui)); if (getBitsLeft(pvBuf) >= 68 && showBitsLong(pvBuf, 21) == 0x100000) { - vui->default_display_window_flag = 0; + tVui->iDefaultDisplayWindowFlag = 0; RPT(RPT_WRN, "Invalid default display window\n"); } else - vui->default_display_window_flag = getOneBit(pvBuf); + tVui->iDefaultDisplayWindowFlag = getOneBit(pvBuf); - if (vui->default_display_window_flag) { - int vert_mult = hevc_sub_height_c[sps->chroma_format_idc]; - int horiz_mult = hevc_sub_width_c[sps->chroma_format_idc]; - vui->def_disp_win.left_offset = parseUe(pvBuf) * horiz_mult; - vui->def_disp_win.right_offset = parseUe(pvBuf) * horiz_mult; - vui->def_disp_win.top_offset = parseUe(pvBuf) * vert_mult; - vui->def_disp_win.bottom_offset = parseUe(pvBuf) * vert_mult; + if (tVui->iDefaultDisplayWindowFlag) { + int vert_mult = sg_au8HevcSubHeightC[ptSps->iChromaFormatIdc]; + int horiz_mult = sg_au8HevcSubWidthC[ptSps->iChromaFormatIdc]; + tVui->tDefDispWin.uiLeftOffset = parseUe(pvBuf) * horiz_mult; + tVui->tDefDispWin.uiRightOffset = parseUe(pvBuf) * horiz_mult; + tVui->tDefDispWin.uiTopOffset = parseUe(pvBuf) * vert_mult; + tVui->tDefDispWin.uiBottomOffset = parseUe(pvBuf) * vert_mult; } timing_info: - vui->vui_timing_info_present_flag = getOneBit(pvBuf); + tVui->iVuiTimingInfoPresentFlag = getOneBit(pvBuf); - if (vui->vui_timing_info_present_flag) { + if (tVui->iVuiTimingInfoPresentFlag) { if( getBitsLeft(pvBuf) < 66 && !alt) { // The alternate syntax seem to have timing info located - // at where def_disp_win is normally located + // at where tDefDispWin is normally located RPT(RPT_WRN, "Strange VUI timing information, retrying...\n"); - memcpy(vui, &backup_vui, sizeof(backup_vui)); - memcpy(pvBuf, &backup, sizeof(backup)); + memcpy(tVui, &tBackupVui, sizeof(tBackupVui)); + memcpy(pvBuf, &tBackup, sizeof(tBackup)); alt = 1; goto timing_info; } - vui->vui_num_units_in_tick = getBits(pvBuf, 32); - vui->vui_time_scale = getBits(pvBuf, 32); + tVui->u32VuiNumUnitsInTick = getBits(pvBuf, 32); + tVui->u32VuiTimeScale = getBits(pvBuf, 32); if (alt) { RPT(RPT_INF, "Retry got %u/%u fps\n", - vui->vui_time_scale, vui->vui_num_units_in_tick); + tVui->u32VuiTimeScale, tVui->u32VuiNumUnitsInTick); } - vui->vui_poc_proportional_to_timing_flag = getOneBit(pvBuf); - if (vui->vui_poc_proportional_to_timing_flag) - vui->vui_num_ticks_poc_diff_one_minus1 = parseUe(pvBuf); - vui->vui_hrd_parameters_present_flag = getOneBit(pvBuf); - if (vui->vui_hrd_parameters_present_flag) - decodeHrd(pvBuf, 1, sps->max_sub_layers); + tVui->iVuiPocProportionalToTimingFlag = getOneBit(pvBuf); + if (tVui->iVuiPocProportionalToTimingFlag) + tVui->iVuiNumTicksPocDiffOneMinus1 = parseUe(pvBuf); + tVui->iVuiHrdParametersPresentFlag = getOneBit(pvBuf); + if (tVui->iVuiHrdParametersPresentFlag) + decodeHrd(pvBuf, 1, ptSps->iMaxSubLayers); } - vui->bitstream_restriction_flag = getOneBit(pvBuf); - if (vui->bitstream_restriction_flag) { + tVui->iBitstreamRestrictionFlag = getOneBit(pvBuf); + if (tVui->iBitstreamRestrictionFlag) { if (getBitsLeft(pvBuf) < 8 && !alt) { RPT(RPT_WRN, "Strange VUI bitstream restriction information, retrying" " from timing information...\n"); - memcpy(vui, &backup_vui, sizeof(backup_vui)); - memcpy(pvBuf, &backup, sizeof(backup)); + memcpy(tVui, &tBackupVui, sizeof(tBackupVui)); + memcpy(pvBuf, &tBackup, sizeof(tBackup)); alt = 1; goto timing_info; } - vui->tiles_fixed_structure_flag = getOneBit(pvBuf); - vui->motion_vectors_over_pic_boundaries_flag = getOneBit(pvBuf); - vui->restricted_ref_pic_lists_flag = getOneBit(pvBuf); - vui->min_spatial_segmentation_idc = parseUe(pvBuf); - vui->max_bytes_per_pic_denom = parseUe(pvBuf); - vui->max_bits_per_min_cu_denom = parseUe(pvBuf); - vui->log2_max_mv_length_horizontal = parseUe(pvBuf); - vui->log2_max_mv_length_vertical = parseUe(pvBuf); + tVui->iTilesFixedStructureFlag = getOneBit(pvBuf); + tVui->iMotionVectorsOverPicBoundariesFlag = getOneBit(pvBuf); + tVui->iRestrictedRefPicListsFlag = getOneBit(pvBuf); + tVui->iMinSpatialSegmentationIdc = parseUe(pvBuf); + tVui->iMaxBytesPerPicDenom = parseUe(pvBuf); + tVui->iMaxBitsPerMinCuDenom = parseUe(pvBuf); + tVui->iLog2MaxMvLengthHorizontal = parseUe(pvBuf); + tVui->iLog2MaxMvLengthVertical = parseUe(pvBuf); } if (getBitsLeft(pvBuf) < 1 && !alt) { - // XXX: Alternate syntax when sps_range_extension_flag != 0? + // XXX: Alternate syntax when iSpsRangeExtensionFlag != 0? RPT(RPT_WRN, "Overread in VUI, retrying from timing information...\n"); - memcpy(vui, &backup_vui, sizeof(backup_vui)); - memcpy(pvBuf, &backup, sizeof(backup)); + memcpy(tVui, &tBackupVui, sizeof(tBackupVui)); + memcpy(pvBuf, &tBackup, sizeof(tBackup)); alt = 1; goto timing_info; } } +static unsigned avModUintp2c(unsigned a, unsigned p) +{ + return a & ((1 << p) - 1); +} -int h265DecSeqParameterSet( void *pvBufSrc, T_HEVCSPS *sps ) +int h265DecSeqParameterSet( void *pvBufSrc, T_HEVCSPS *ptSps ) { T_HEVCWindow *ow; -// int ret = 0; - int log2_diff_max_min_transform_block_size; - int bit_depth_chroma, start, vui_present, sublayer_ordering_info; + int iLog2DiffMaxMinTransformBlockSize; + int iBitDepthChroma, iStart, iVuiPresent, iSublayerOrderingInfo; int i; int iRet = 0; - void *pvBuf = NULL; - if(NULL == pvBufSrc || NULL == sps) + if(NULL == pvBufSrc || NULL == ptSps) { RPT(RPT_ERR,"ERR null pointer\n"); iRet = -1; goto exit; } - memset((void *)sps, 0, sizeof(T_HEVCSPS)); + memset((void *)ptSps, 0, sizeof(T_HEVCSPS)); pvBuf = deEmulationPrevention(pvBufSrc); if(NULL == pvBuf) @@ -1716,35 +1695,26 @@ int h265DecSeqParameterSet( void *pvBufSrc, T_HEVCSPS *sps ) iRet = -1; goto exit; } - // Coded parameters - sps->vps_id = getBits(pvBuf, 4); - if (sps->vps_id >= HEVC_MAX_VPS_COUNT) { - RPT(RPT_ERR, "VPS id out of range: %d\n", sps->vps_id); + ptSps->uiVpsId = getBits(pvBuf, 4); + if (ptSps->uiVpsId >= HEVC_MAX_VPS_COUNT) { + RPT(RPT_ERR, "VPS id out of range: %d\n", ptSps->uiVpsId); iRet = -1; goto exit; } -#if 0 - if (vps_list && !vps_list[sps->vps_id]) { - RPT(RPT_ERR, "VPS %d does not exist\n", - sps->vps_id); - return AVERROR_INVALIDDATA; - } -#endif - - sps->max_sub_layers = getBits(pvBuf, 3) + 1; - if (sps->max_sub_layers > HEVC_MAX_SUB_LAYERS) { + ptSps->iMaxSubLayers = getBits(pvBuf, 3) + 1; + if (ptSps->iMaxSubLayers > HEVC_MAX_SUB_LAYERS) { RPT(RPT_ERR, "sps_max_sub_layers out of range: %d\n", - sps->max_sub_layers); + ptSps->iMaxSubLayers); iRet = -1; goto exit; } - sps->temporal_id_nesting_flag = getBits(pvBuf, 1); - if ((iRet = parsePtl(pvBuf, &sps->ptl, sps->max_sub_layers)) < 0) + ptSps->u8temporalIdNestingFlag = getBits(pvBuf, 1); + if ((iRet = parsePtl(pvBuf, &ptSps->tPtl, ptSps->iMaxSubLayers)) < 0) goto exit; int sps_id = parseUe(pvBuf); @@ -1754,320 +1724,290 @@ int h265DecSeqParameterSet( void *pvBufSrc, T_HEVCSPS *sps ) goto exit; } - sps->chroma_format_idc = parseUe(pvBuf); - if (sps->chroma_format_idc > 3U) { - RPT(RPT_ERR, "chroma_format_idc %d is invalid\n", sps->chroma_format_idc); + ptSps->iChromaFormatIdc = parseUe(pvBuf); + if (ptSps->iChromaFormatIdc > 3U) { + RPT(RPT_ERR, "iChromaFormatIdc %d is invalid\n", ptSps->iChromaFormatIdc); iRet = -1; goto exit; } - if (sps->chroma_format_idc == 3) - sps->separate_colour_plane_flag = getOneBit(pvBuf); + if (ptSps->iChromaFormatIdc == 3) + ptSps->u8SeparateColourPlaneFlag = getOneBit(pvBuf); - if (sps->separate_colour_plane_flag) - sps->chroma_format_idc = 0; + if (ptSps->u8SeparateColourPlaneFlag) + ptSps->iChromaFormatIdc = 0; - sps->width = parseUe(pvBuf); - sps->height = parseUe(pvBuf); - -// if ((iRet = av_image_check_size(sps->width, -// sps->height, 0, avctx)) < 0) -// goto exit; + ptSps->iWidth = parseUe(pvBuf); + ptSps->iHeight = parseUe(pvBuf); if (getOneBit(pvBuf)) { // pic_conformance_flag - int vert_mult = hevc_sub_height_c[sps->chroma_format_idc]; - int horiz_mult = hevc_sub_width_c[sps->chroma_format_idc]; - sps->pic_conf_win.left_offset = parseUe(pvBuf) * horiz_mult; - sps->pic_conf_win.right_offset = parseUe(pvBuf) * horiz_mult; - sps->pic_conf_win.top_offset = parseUe(pvBuf) * vert_mult; - sps->pic_conf_win.bottom_offset = parseUe(pvBuf) * vert_mult; + int vert_mult = sg_au8HevcSubHeightC[ptSps->iChromaFormatIdc]; + int horiz_mult = sg_au8HevcSubWidthC[ptSps->iChromaFormatIdc]; + ptSps->tPicConfWin.uiLeftOffset = parseUe(pvBuf) * horiz_mult; + ptSps->tPicConfWin.uiRightOffset = parseUe(pvBuf) * horiz_mult; + ptSps->tPicConfWin.uiTopOffset = parseUe(pvBuf) * vert_mult; + ptSps->tPicConfWin.uiBottomOffset = parseUe(pvBuf) * vert_mult; - sps->output_window = sps->pic_conf_win; + ptSps->tOutputWindow = ptSps->tPicConfWin; } - sps->bit_depth = parseUe(pvBuf) + 8; - bit_depth_chroma = parseUe(pvBuf) + 8; + ptSps->iBitDepth = parseUe(pvBuf) + 8; + iBitDepthChroma = parseUe(pvBuf) + 8; - if (sps->chroma_format_idc && bit_depth_chroma != sps->bit_depth) { + if (ptSps->iChromaFormatIdc && iBitDepthChroma != ptSps->iBitDepth) { RPT(RPT_ERR, "Luma bit depth (%d) is different from chroma bit depth (%d), " "this is unsupported.\n", - sps->bit_depth, bit_depth_chroma); + ptSps->iBitDepth, iBitDepthChroma); iRet = -1; goto exit; } - sps->bit_depth_chroma = bit_depth_chroma; + ptSps->iBitDepthChroma = iBitDepthChroma; -#if 0 - iRet = map_pixel_format(avctx, sps); - if (iRet < 0) - goto exit; -#endif - -#if 0 - - sps->log2_max_poc_lsb = parseUe(pvBuf) + 4; - if (sps->log2_max_poc_lsb > 16) { + ptSps->uiLog2MaxPocLsb = parseUe(pvBuf) + 4; + if (ptSps->uiLog2MaxPocLsb > 16) { RPT(RPT_ERR, "log2_max_pic_order_cnt_lsb_minus4 out range: %d\n", - sps->log2_max_poc_lsb - 4); + ptSps->uiLog2MaxPocLsb - 4); iRet = -1; goto exit; } - sublayer_ordering_info = getOneBit(pvBuf); - start = sublayer_ordering_info ? 0 : sps->max_sub_layers - 1; - for (i = start; i < sps->max_sub_layers; i++) { - sps->temporal_layer[i].max_dec_pic_buffering = parseUe(pvBuf) + 1; - sps->temporal_layer[i].num_reorder_pics = parseUe(pvBuf); - sps->temporal_layer[i].max_latency_increase = parseUe(pvBuf) - 1; - if (sps->temporal_layer[i].max_dec_pic_buffering > (unsigned)HEVC_MAX_DPB_SIZE) { + iSublayerOrderingInfo = getOneBit(pvBuf); + iStart = iSublayerOrderingInfo ? 0 : ptSps->iMaxSubLayers - 1; + for (i = iStart; i < ptSps->iMaxSubLayers; i++) { + ptSps->stTemporalLayer[i].iMaxDecPicBuffering = parseUe(pvBuf) + 1; + ptSps->stTemporalLayer[i].iNumReorderPics = parseUe(pvBuf); + ptSps->stTemporalLayer[i].iMaxLatencyIncrease = parseUe(pvBuf) - 1; + if (ptSps->stTemporalLayer[i].iMaxDecPicBuffering > (unsigned)HEVC_MAX_DPB_SIZE) { RPT(RPT_ERR, "sps_max_dec_pic_buffering_minus1 out of range: %d\n", - sps->temporal_layer[i].max_dec_pic_buffering - 1U); + ptSps->stTemporalLayer[i].iMaxDecPicBuffering - 1U); iRet = -1; goto exit; } - if (sps->temporal_layer[i].num_reorder_pics > sps->temporal_layer[i].max_dec_pic_buffering - 1) { + if (ptSps->stTemporalLayer[i].iNumReorderPics > ptSps->stTemporalLayer[i].iMaxDecPicBuffering - 1) { RPT(RPT_WRN, "sps_max_num_reorder_pics out of range: %d\n", - sps->temporal_layer[i].num_reorder_pics); - if (sps->temporal_layer[i].num_reorder_pics > HEVC_MAX_DPB_SIZE - 1) { + ptSps->stTemporalLayer[i].iNumReorderPics); + if (ptSps->stTemporalLayer[i].iNumReorderPics > HEVC_MAX_DPB_SIZE - 1) { iRet = -1; goto exit; } - sps->temporal_layer[i].max_dec_pic_buffering = sps->temporal_layer[i].num_reorder_pics + 1; + ptSps->stTemporalLayer[i].iMaxDecPicBuffering = ptSps->stTemporalLayer[i].iNumReorderPics + 1; } } - if (!sublayer_ordering_info) { - for (i = 0; i < start; i++) { - sps->temporal_layer[i].max_dec_pic_buffering = sps->temporal_layer[start].max_dec_pic_buffering; - sps->temporal_layer[i].num_reorder_pics = sps->temporal_layer[start].num_reorder_pics; - sps->temporal_layer[i].max_latency_increase = sps->temporal_layer[start].max_latency_increase; + if (!iSublayerOrderingInfo) { + for (i = 0; i < iStart; i++) { + ptSps->stTemporalLayer[i].iMaxDecPicBuffering = ptSps->stTemporalLayer[iStart].iMaxDecPicBuffering; + ptSps->stTemporalLayer[i].iNumReorderPics = ptSps->stTemporalLayer[iStart].iNumReorderPics; + ptSps->stTemporalLayer[i].iMaxLatencyIncrease = ptSps->stTemporalLayer[iStart].iMaxLatencyIncrease; } } - sps->log2_min_cb_size = parseUe(pvBuf) + 3; - sps->log2_diff_max_min_coding_block_size = parseUe(pvBuf); - sps->log2_min_tb_size = parseUe(pvBuf) + 2; - log2_diff_max_min_transform_block_size = parseUe(pvBuf); - sps->log2_max_trafo_size = log2_diff_max_min_transform_block_size + - sps->log2_min_tb_size; + ptSps->uiLog2MinCbSize = parseUe(pvBuf) + 3; + ptSps->uiLog2DiffMaxMinCodingBlockSize = parseUe(pvBuf); + ptSps->uiLog2MinTbSize = parseUe(pvBuf) + 2; + iLog2DiffMaxMinTransformBlockSize = parseUe(pvBuf); + ptSps->uiLog2MaxTrafoSize = iLog2DiffMaxMinTransformBlockSize + + ptSps->uiLog2MinTbSize; - if (sps->log2_min_cb_size < 3 || sps->log2_min_cb_size > 30) { - RPT(RPT_ERR, "Invalid value %d for log2_min_cb_size", sps->log2_min_cb_size); + if (ptSps->uiLog2MinCbSize < 3 || ptSps->uiLog2MinCbSize > 30) { + RPT(RPT_ERR, "Invalid value %d for uiLog2MinCbSize", ptSps->uiLog2MinCbSize); iRet = -1; goto exit; } - if (sps->log2_diff_max_min_coding_block_size > 30) { - RPT(RPT_ERR, "Invalid value %d for log2_diff_max_min_coding_block_size", sps->log2_diff_max_min_coding_block_size); + if (ptSps->uiLog2DiffMaxMinCodingBlockSize > 30) { + RPT(RPT_ERR, "Invalid value %d for uiLog2DiffMaxMinCodingBlockSize", ptSps->uiLog2DiffMaxMinCodingBlockSize); iRet = -1; goto exit; } - if (sps->log2_min_tb_size >= sps->log2_min_cb_size || sps->log2_min_tb_size < 2) { - RPT(RPT_ERR, "Invalid value for log2_min_tb_size"); + if (ptSps->uiLog2MinTbSize >= ptSps->uiLog2MinCbSize || ptSps->uiLog2MinTbSize < 2) { + RPT(RPT_ERR, "Invalid value for uiLog2MinTbSize"); iRet = -1; goto exit; } - if (log2_diff_max_min_transform_block_size < 0 || log2_diff_max_min_transform_block_size > 30) { - RPT(RPT_ERR, "Invalid value %d for log2_diff_max_min_transform_block_size", log2_diff_max_min_transform_block_size); + if (iLog2DiffMaxMinTransformBlockSize < 0 || iLog2DiffMaxMinTransformBlockSize > 30) { + RPT(RPT_ERR, "Invalid value %d for iLog2DiffMaxMinTransformBlockSize", iLog2DiffMaxMinTransformBlockSize); iRet = -1; goto exit; } - sps->max_transform_hierarchy_depth_inter = parseUe(pvBuf); - sps->max_transform_hierarchy_depth_intra = parseUe(pvBuf); + ptSps->iMaxTransformHierarchyDepthInter = parseUe(pvBuf); + ptSps->iMaxTransformHierarchyDepthIntra = parseUe(pvBuf); - sps->scaling_list_enable_flag = getOneBit(pvBuf); - - printf("sps->scaling_list_enable_flag: %d\n",sps->scaling_list_enable_flag); + ptSps->u8ScalingListEnableFlag = getOneBit(pvBuf); - if (sps->scaling_list_enable_flag) { - setDefaultScalingListData(&sps->scaling_list); + if (ptSps->u8ScalingListEnableFlag) { + setDefaultScalingListData(&ptSps->tScalingList); if (getOneBit(pvBuf)) { - iRet = scalingListData(pvBuf, &sps->scaling_list, sps); + iRet = scalingListData(pvBuf, &ptSps->tScalingList, ptSps); if (iRet < 0) goto exit; } } - sps->amp_enabled_flag = getOneBit(pvBuf); - sps->sao_enabled = getOneBit(pvBuf); + ptSps->u8AmpEnabledFlag = getOneBit(pvBuf); + ptSps->u8SaoEnabled = getOneBit(pvBuf); - sps->pcm_enabled_flag = getOneBit(pvBuf); + ptSps->iPcmEnabledFlag = getOneBit(pvBuf); - printf("sps->pcm_enabled_flag: %d\n",sps->pcm_enabled_flag); - if (sps->pcm_enabled_flag) { - sps->pcm.bit_depth = getBits(pvBuf, 4) + 1; - sps->pcm.bit_depth_chroma = getBits(pvBuf, 4) + 1; - sps->pcm.log2_min_pcm_cb_size = parseUe(pvBuf) + 3; - sps->pcm.log2_max_pcm_cb_size = sps->pcm.log2_min_pcm_cb_size + + if (ptSps->iPcmEnabledFlag) { + ptSps->pcm.u8BitDepth = getBits(pvBuf, 4) + 1; + ptSps->pcm.u8BitDepthChroma = getBits(pvBuf, 4) + 1; + ptSps->pcm.uiLog2MinPcmCbSize = parseUe(pvBuf) + 3; + ptSps->pcm.uiLog2MaxPcmCbSize = ptSps->pcm.uiLog2MinPcmCbSize + parseUe(pvBuf); - if (FFMAX(sps->pcm.bit_depth, sps->pcm.bit_depth_chroma) > sps->bit_depth) { + if (FFMAX(ptSps->pcm.u8BitDepth, ptSps->pcm.u8BitDepthChroma) > ptSps->iBitDepth) { RPT(RPT_ERR, "PCM bit depth (%d, %d) is greater than normal bit depth (%d)\n", - sps->pcm.bit_depth, sps->pcm.bit_depth_chroma, sps->bit_depth); + ptSps->pcm.u8BitDepth, ptSps->pcm.u8BitDepthChroma, ptSps->iBitDepth); iRet = -1; goto exit; } - sps->pcm.loop_filter_disable_flag = getOneBit(pvBuf); + ptSps->pcm.u8LoopFilterDisableFlag = getOneBit(pvBuf); } - sps->nb_st_rps = parseUe(pvBuf); - if (sps->nb_st_rps > HEVC_MAX_SHORT_TERM_REF_PIC_SETS) { + ptSps->uiNbStRps = parseUe(pvBuf); + if (ptSps->uiNbStRps > HEVC_MAX_SHORT_TERM_REF_PIC_SETS) { RPT(RPT_ERR, "Too many short term RPS: %d.\n", - sps->nb_st_rps); + ptSps->uiNbStRps); iRet = -1; goto exit; } - printf("sps->nb_st_rps: %d\n",sps->nb_st_rps); - for (i = 0; i < sps->nb_st_rps; i++) { - if ((iRet = hevcDecodeShortTermRps(pvBuf, &sps->st_rps[i], - sps, 0)) < 0) + for (i = 0; i < ptSps->uiNbStRps; i++) { + if ((iRet = hevcDecodeShortTermRps(pvBuf, &ptSps->atStRps[i], + ptSps, 0)) < 0) goto exit; } - sps->long_term_ref_pics_present_flag = getOneBit(pvBuf); - if (sps->long_term_ref_pics_present_flag) { - sps->num_long_term_ref_pics_sps = parseUe(pvBuf); - if (sps->num_long_term_ref_pics_sps > HEVC_MAX_LONG_TERM_REF_PICS) { + ptSps->u8LongTermRefPicsPresentFlag = getOneBit(pvBuf); + if (ptSps->u8LongTermRefPicsPresentFlag) { + ptSps->u8NumLongTermRefPicsSps = parseUe(pvBuf); + if (ptSps->u8NumLongTermRefPicsSps > HEVC_MAX_LONG_TERM_REF_PICS) { RPT(RPT_ERR, "Too many long term ref pics: %d.\n", - sps->num_long_term_ref_pics_sps); + ptSps->u8NumLongTermRefPicsSps); iRet = -1; goto exit; } - for (i = 0; i < sps->num_long_term_ref_pics_sps; i++) { - sps->lt_ref_pic_poc_lsb_sps[i] = getBits(pvBuf, sps->log2_max_poc_lsb); - sps->used_by_curr_pic_lt_sps_flag[i] = getOneBit(pvBuf); + for (i = 0; i < ptSps->u8NumLongTermRefPicsSps; i++) { + ptSps->au16LtRefPicPocLsbSps[i] = getBits(pvBuf, ptSps->uiLog2MaxPocLsb); + ptSps->au8UsedByCurrPicLtSpsFlag[i] = getOneBit(pvBuf); } } - sps->sps_temporal_mvp_enabled_flag = getOneBit(pvBuf); - sps->sps_strong_intra_smoothing_enable_flag = getOneBit(pvBuf); - sps->vui.sar = (T_AVRational){0, 1}; - vui_present = getOneBit(pvBuf); - if (vui_present==1) - decodeVui(pvBuf, sps); - -#endif -#if 0 + ptSps->u8SpsTemporalMvpEnabledFlag = getOneBit(pvBuf); + ptSps->u8SpsStrongIntraMmoothingEnableFlag = getOneBit(pvBuf); + ptSps->tVui.tSar = (T_AVRational){0, 1}; + ptSps->iVuiPresent = getOneBit(pvBuf); + if (ptSps->iVuiPresent) + decodeVui(pvBuf, ptSps); + if (getOneBit(pvBuf)) { // sps_extension_flag - int sps_range_extension_flag = getOneBit(pvBuf); + int iSpsRangeExtensionFlag = getOneBit(pvBuf); getBits(pvBuf, 7); //sps_extension_7bits = getBits(pvBuf, 7); - if (sps_range_extension_flag) { - int extended_precision_processing_flag; - int cabac_bypass_alignment_enabled_flag; + if (iSpsRangeExtensionFlag) { + int iExtendedPrecisionProcessingFlag; + int iCabacBypassAlignmentEnabledFlag; - sps->transform_skip_rotation_enabled_flag = getOneBit(pvBuf); - sps->transform_skip_context_enabled_flag = getOneBit(pvBuf); - sps->implicit_rdpcm_enabled_flag = getOneBit(pvBuf); + ptSps->iTransformSkipRotationEnabledFlag = getOneBit(pvBuf); + ptSps->iTransformSkipContextEnabledFlag = getOneBit(pvBuf); + ptSps->iImplicitRdpcmEnabledFlag = getOneBit(pvBuf); - sps->explicit_rdpcm_enabled_flag = getOneBit(pvBuf); + ptSps->iExplicitRdpcmEnabledFlag = getOneBit(pvBuf); - extended_precision_processing_flag = getOneBit(pvBuf); - if (extended_precision_processing_flag) + iExtendedPrecisionProcessingFlag = getOneBit(pvBuf); + if (iExtendedPrecisionProcessingFlag) RPT(RPT_WRN, - "extended_precision_processing_flag not yet implemented\n"); + "iExtendedPrecisionProcessingFlag not yet implemented\n"); - sps->intra_smoothing_disabled_flag = getOneBit(pvBuf); - sps->high_precision_offsets_enabled_flag = getOneBit(pvBuf); - if (sps->high_precision_offsets_enabled_flag) + ptSps->iIntraSmoothingDisabledFlag = getOneBit(pvBuf); + ptSps->iHighPrecisionOffsetsEnabledFlag = getOneBit(pvBuf); + if (ptSps->iHighPrecisionOffsetsEnabledFlag) RPT(RPT_WRN, - "high_precision_offsets_enabled_flag not yet implemented\n"); + "iHighPrecisionOffsetsEnabledFlag not yet implemented\n"); - sps->persistent_rice_adaptation_enabled_flag = getOneBit(pvBuf); + ptSps->iPersistentRiceAdaptationEnabledFlag = getOneBit(pvBuf); - cabac_bypass_alignment_enabled_flag = getOneBit(pvBuf); - if (cabac_bypass_alignment_enabled_flag) + iCabacBypassAlignmentEnabledFlag = getOneBit(pvBuf); + if (iCabacBypassAlignmentEnabledFlag) RPT(RPT_WRN, - "cabac_bypass_alignment_enabled_flag not yet implemented\n"); + "iCabacBypassAlignmentEnabledFlag not yet implemented\n"); } } - if (apply_defdispwin) { - sps->output_window.left_offset += sps->vui.def_disp_win.left_offset; - sps->output_window.right_offset += sps->vui.def_disp_win.right_offset; - sps->output_window.top_offset += sps->vui.def_disp_win.top_offset; - sps->output_window.bottom_offset += sps->vui.def_disp_win.bottom_offset; - } - ow = &sps->output_window; - if (ow->left_offset >= INT_MAX - ow->right_offset || - ow->top_offset >= INT_MAX - ow->bottom_offset || - ow->left_offset + ow->right_offset >= sps->width || - ow->top_offset + ow->bottom_offset >= sps->height) { + ow = &ptSps->tOutputWindow; + if (ow->uiLeftOffset >= INT_MAX - ow->uiRightOffset || + ow->uiTopOffset >= INT_MAX - ow->uiBottomOffset || + ow->uiLeftOffset + ow->uiRightOffset >= ptSps->iWidth || + ow->uiTopOffset + ow->uiBottomOffset >= ptSps->iHeight) { RPT(RPT_WRN, "Invalid cropping offsets: %u/%u/%u/%u\n", - ow->left_offset, ow->right_offset, ow->top_offset, ow->bottom_offset); - if (avctx->err_recognition & AV_EF_EXPLODE) { - return AVERROR_INVALIDDATA; - } + ow->uiLeftOffset, ow->uiRightOffset, ow->uiTopOffset, ow->uiBottomOffset); RPT(RPT_WRN, "Displaying the whole video surface.\n"); memset(ow, 0, sizeof(*ow)); - memset(&sps->pic_conf_win, 0, sizeof(sps->pic_conf_win)); + memset(&ptSps->tPicConfWin, 0, sizeof(ptSps->tPicConfWin)); } // Inferred parameters - sps->log2_ctb_size = sps->log2_min_cb_size + - sps->log2_diff_max_min_coding_block_size; - sps->log2_min_pu_size = sps->log2_min_cb_size - 1; + ptSps->uiLog2CtbSize = ptSps->uiLog2MinCbSize + + ptSps->uiLog2DiffMaxMinCodingBlockSize; + ptSps->uiLog2MinPuSize = ptSps->uiLog2MinCbSize - 1; - if (sps->log2_ctb_size > HEVC_MAX_LOG2_CTB_SIZE) { - RPT(RPT_ERR, "CTB size out of range: 2^%d\n", sps->log2_ctb_size); - iRet = -1; + if (ptSps->uiLog2CtbSize > HEVC_MAX_LOG2_CTB_SIZE) { + RPT(RPT_ERR, "CTB size out of range: 2^%d\n", ptSps->uiLog2CtbSize); iRet = -1; goto exit; } - if (sps->log2_ctb_size < 4) { + if (ptSps->uiLog2CtbSize < 4) { RPT(RPT_ERR, - "log2_ctb_size %d differs from the bounds of any known profile\n", - sps->log2_ctb_size); - avpriv_request_sample(avctx, "log2_ctb_size %d", sps->log2_ctb_size); - iRet = -1; + "uiLog2CtbSize %d differs from the bounds of any known profile\n", + ptSps->uiLog2CtbSize); iRet = -1; goto exit; } - sps->ctb_width = (sps->width + (1 << sps->log2_ctb_size) - 1) >> sps->log2_ctb_size; - sps->ctb_height = (sps->height + (1 << sps->log2_ctb_size) - 1) >> sps->log2_ctb_size; - sps->ctb_size = sps->ctb_width * sps->ctb_height; + ptSps->iCtbWidth = (ptSps->iWidth + (1 << ptSps->uiLog2CtbSize) - 1) >> ptSps->uiLog2CtbSize; + ptSps->iCtbHeight = (ptSps->iHeight + (1 << ptSps->uiLog2CtbSize) - 1) >> ptSps->uiLog2CtbSize; + ptSps->iCtbSize = ptSps->iCtbWidth * ptSps->iCtbHeight; - sps->min_cb_width = sps->width >> sps->log2_min_cb_size; - sps->min_cb_height = sps->height >> sps->log2_min_cb_size; - sps->min_tb_width = sps->width >> sps->log2_min_tb_size; - sps->min_tb_height = sps->height >> sps->log2_min_tb_size; - sps->min_pu_width = sps->width >> sps->log2_min_pu_size; - sps->min_pu_height = sps->height >> sps->log2_min_pu_size; - sps->tb_mask = (1 << (sps->log2_ctb_size - sps->log2_min_tb_size)) - 1; + ptSps->iMinCbWidth = ptSps->iWidth >> ptSps->uiLog2MinCbSize; + ptSps->iMinCbHeight = ptSps->iHeight >> ptSps->uiLog2MinCbSize; + ptSps->iMinTbWidth = ptSps->iWidth >> ptSps->uiLog2MinTbSize; + ptSps->iMinTbHeight = ptSps->iHeight >> ptSps->uiLog2MinTbSize; + ptSps->iMinPuWidth = ptSps->iWidth >> ptSps->uiLog2MinPuSize; + ptSps->iMinPuHeight = ptSps->iHeight >> ptSps->uiLog2MinPuSize; + ptSps->iTbMask = (1 << (ptSps->uiLog2CtbSize - ptSps->uiLog2MinTbSize)) - 1; - sps->qp_bd_offset = 6 * (sps->bit_depth - 8); + ptSps->iQpBdOffset = 6 * (ptSps->iBitDepth - 8); - if (av_mod_uintp2(sps->width, sps->log2_min_cb_size) || - av_mod_uintp2(sps->height, sps->log2_min_cb_size)) { + if (avModUintp2c(ptSps->iWidth, ptSps->uiLog2MinCbSize) || + avModUintp2c(ptSps->iHeight, ptSps->uiLog2MinCbSize)) { RPT(RPT_ERR, "Invalid coded frame dimensions.\n"); iRet = -1; goto exit; } - if (sps->max_transform_hierarchy_depth_inter > sps->log2_ctb_size - sps->log2_min_tb_size) { - RPT(RPT_ERR, "max_transform_hierarchy_depth_inter out of range: %d\n", - sps->max_transform_hierarchy_depth_inter); + if (ptSps->iMaxTransformHierarchyDepthInter > ptSps->uiLog2CtbSize - ptSps->uiLog2MinTbSize) { + RPT(RPT_ERR, "iMaxTransformHierarchyDepthInter out of range: %d\n", + ptSps->iMaxTransformHierarchyDepthInter); iRet = -1; goto exit; } - if (sps->max_transform_hierarchy_depth_intra > sps->log2_ctb_size - sps->log2_min_tb_size) { - RPT(RPT_ERR, "max_transform_hierarchy_depth_intra out of range: %d\n", - sps->max_transform_hierarchy_depth_intra); + if (ptSps->iMaxTransformHierarchyDepthIntra > ptSps->uiLog2CtbSize - ptSps->uiLog2MinTbSize) { + RPT(RPT_ERR, "iMaxTransformHierarchyDepthIntra out of range: %d\n", + ptSps->iMaxTransformHierarchyDepthIntra); iRet = -1; goto exit; } - if (sps->log2_max_trafo_size > FFMIN(sps->log2_ctb_size, 5)) { + if (ptSps->uiLog2MaxTrafoSize > FFMIN(ptSps->uiLog2CtbSize, 5)) { RPT(RPT_ERR, "max transform block size out of range: %d\n", - sps->log2_max_trafo_size); + ptSps->uiLog2MaxTrafoSize); iRet = -1; goto exit; } @@ -2078,7 +2018,6 @@ int h265DecSeqParameterSet( void *pvBufSrc, T_HEVCSPS *sps ) iRet = -1; goto exit; } -#endif exit: @@ -2088,6 +2027,141 @@ exit: } + +int h265DecVideoParameterSet( void *pvBufSrc, T_HEVCVPS *ptVps ) +{ + int iRet = 0; + int i,j; + int uiVpsId = 0; + + void *pvBuf = NULL; + if(NULL == pvBufSrc || NULL == ptVps) + { + RPT(RPT_ERR,"ERR null pointer\n"); + iRet = -1; + goto exit; + } + + memset((void *)ptVps, 0, sizeof(T_HEVCVPS)); + + pvBuf = deEmulationPrevention(pvBufSrc); + if(NULL == pvBuf) + { + RPT(RPT_ERR,"ERR null pointer\n"); + iRet = -1; + goto exit; + } + + RPT(RPT_DBG, "Decoding VPS\n"); + + uiVpsId = getBits(pvBuf, 4); + if (uiVpsId >= HEVC_MAX_VPS_COUNT) { + RPT(RPT_ERR, "VPS id out of range: %d\n", uiVpsId); + iRet = -1; + goto exit; + } + + if (getBits(pvBuf, 2) != 3) { // vps_reserved_three_2bits + RPT(RPT_ERR, "vps_reserved_three_2bits is not three\n"); + iRet = -1; + goto exit; + } + + ptVps->iVpsMaxLayers = getBits(pvBuf, 6) + 1; + ptVps->iVpsMaxSubLayers = getBits(pvBuf, 3) + 1; + ptVps->u8VpsTemporalIdNestingFlag = getOneBit(pvBuf); + + if (getBits(pvBuf, 16) != 0xffff) { // vps_reserved_ffff_16bits + RPT(RPT_ERR, "vps_reserved_ffff_16bits is not 0xffff\n"); + iRet = -1; + goto exit; + } + + if (ptVps->iVpsMaxSubLayers > HEVC_MAX_SUB_LAYERS) { + RPT(RPT_ERR, "iVpsMaxSubLayers out of range: %d\n", + ptVps->iVpsMaxSubLayers); + iRet = -1; + goto exit; + } + + if (parsePtl(pvBuf, &ptVps->tPtl, ptVps->iVpsMaxSubLayers) < 0){ + iRet = -1; + goto exit; + } + + ptVps->iVpsSubLayerOrderingInfoPresentFlag = getOneBit(pvBuf); + + i = ptVps->iVpsSubLayerOrderingInfoPresentFlag ? 0 : ptVps->iVpsMaxSubLayers - 1; + for (; i < ptVps->iVpsMaxSubLayers; i++) { + ptVps->uiVpsMaxDecPicBuffering[i] = parseUe(pvBuf) + 1; + ptVps->auiVpsNumReorderPics[i] = parseUe(pvBuf); + ptVps->auiVpsMaxLatencyIncrease[i] = parseUe(pvBuf) - 1; + + if (ptVps->uiVpsMaxDecPicBuffering[i] > HEVC_MAX_DPB_SIZE || !ptVps->uiVpsMaxDecPicBuffering[i]) { + RPT(RPT_ERR, "vps_max_dec_pic_buffering_minus1 out of range: %d\n", + ptVps->uiVpsMaxDecPicBuffering[i] - 1); + iRet = -1; + goto exit; + } + if (ptVps->auiVpsNumReorderPics[i] > ptVps->uiVpsMaxDecPicBuffering[i] - 1) { + RPT(RPT_WRN, "vps_max_num_reorder_pics out of range: %d\n", + ptVps->auiVpsNumReorderPics[i]); + } + } + + ptVps->iVpsMaxLayerId = getBits(pvBuf, 6); + ptVps->iVpsNumLayerSets = parseUe(pvBuf) + 1; + if (ptVps->iVpsNumLayerSets < 1 || ptVps->iVpsNumLayerSets > 1024 || + (ptVps->iVpsNumLayerSets - 1LL) * (ptVps->iVpsMaxLayerId + 1LL) > getBitsLeft(pvBuf)) { + RPT(RPT_ERR, "too many layer_id_included_flags\n"); + iRet = -1; + goto exit; + } + + for (i = 1; i < ptVps->iVpsNumLayerSets; i++) + for (j = 0; j <= ptVps->iVpsMaxLayerId; j++) + getBits(pvBuf, 1); // layer_id_included_flag[i][j] + + ptVps->u8VpsTimingInfoPresentFlag = getOneBit(pvBuf); + if (ptVps->u8VpsTimingInfoPresentFlag) { + ptVps->u32VpsNumUnitsInTick = getBits(pvBuf, 32); + ptVps->u32VpsTimeScale = getBits(pvBuf, 32); + ptVps->u8VpsPocProportionalToTimingFlag = getOneBit(pvBuf); + if (ptVps->u8VpsPocProportionalToTimingFlag) + ptVps->iVpsNumTicksPocDiffOne = parseUe(pvBuf) + 1; + ptVps->iVpsNumHrdParameters = parseUe(pvBuf); + if (ptVps->iVpsNumHrdParameters > (unsigned)ptVps->iVpsNumLayerSets) { + RPT(RPT_ERR, + "iVpsNumHrdParameters %d is invalid\n", ptVps->iVpsNumHrdParameters); + iRet = -1; + goto exit; + } + for (i = 0; i < ptVps->iVpsNumHrdParameters; i++) { + int common_inf_present = 1; + + parseUe(pvBuf); // hrd_layer_set_idx + if (i) + common_inf_present = getOneBit(pvBuf); + decodeHrd(pvBuf, common_inf_present, ptVps->iVpsMaxSubLayers); + } + } + getOneBit(pvBuf); /* vps_extension_flag */ + + if (getBitsLeft(pvBuf) < 0) { + RPT(RPT_ERR, + "Overread VPS by %d bits\n", -getBitsLeft(pvBuf)); + + iRet = -1; + goto exit; + } + + +exit: + + getBitContextFree(pvBuf); + return iRet; + +} void h264GetWidthHeight(T_SPS *ptSps, int *piWidth, int *piHeight) { @@ -2191,28 +2265,39 @@ void h264GeFramerate(T_SPS *ptSps, float *pfFramerate) void h265GetWidthHeight(T_HEVCSPS *ptSps, int *piWidth, int *piHeight) { #if 1 - // ¿í¸ß¼ÆË㹫ʽ int iCodeWidth = 0; int iCodedHeight = 0; - iCodeWidth = ptSps->width; - iCodedHeight = ptSps->height; - *piWidth = ptSps->width - ptSps->pic_conf_win.left_offset - ptSps->pic_conf_win.right_offset; - *piHeight = ptSps->height - ptSps->pic_conf_win.top_offset - ptSps->pic_conf_win.bottom_offset; + iCodeWidth = ptSps->iWidth; + iCodedHeight = ptSps->iHeight; + *piWidth = ptSps->iWidth - ptSps->tOutputWindow.uiLeftOffset - ptSps->tOutputWindow.uiRightOffset; + *piHeight = ptSps->iHeight - ptSps->tOutputWindow.uiTopOffset - ptSps->tOutputWindow.uiBottomOffset; + RPT(RPT_DBG, "iCodeWidth:%d, iCodedHeight:%d\n", iCodeWidth, iCodedHeight); RPT(RPT_DBG, "*piWidth:%d, *piHeight:%d\n", *piWidth, *piHeight); -// RPT(RPT_DBG, "ptSps->uiCropRight:%d, ptSps->uiCropLeft:%d\n", ptSps->uiCropRight, ptSps->uiCropLeft); + RPT(RPT_DBG, "ptSps->tOutputWindow.uiRightOffset:%d, ptSps->tOutputWindow.uiLeftOffset:%d\n", ptSps->tOutputWindow.uiRightOffset, ptSps->tOutputWindow.uiLeftOffset); -// RPT(RPT_DBG, "ptSps->uiCropTop:%d, ptSps->uiCropBottom:%d\n", ptSps->uiCropTop, ptSps->uiCropBottom); + RPT(RPT_DBG, "ptSps->tOutputWindow.uiTopOffset:%d, ptSps->tOutputWindow.uiBottomOffset:%d\n", ptSps->tOutputWindow.uiTopOffset, ptSps->tOutputWindow.uiBottomOffset); #endif } -void h265GeFramerate(T_HEVCSPS *ptSps, float *pfFramerate) +void h265GeFramerate(T_HEVCVPS *ptVps, T_HEVCSPS *ptSps,float *pfFramerate) { + if (ptVps && ptVps->u8VpsTimingInfoPresentFlag) { + *pfFramerate = (float)(ptVps->u32VpsTimeScale) / (float)(ptVps->u32VpsNumUnitsInTick); + + } else if (ptSps && ptSps->tVui.iVuiTimingInfoPresentFlag && ptSps->iVuiPresent) { + *pfFramerate = (float)(ptSps->tVui.u32VuiTimeScale) / (float)(ptSps->tVui.u32VuiNumUnitsInTick); + } + else{ + //vps sps可能不包含帧率 + *pfFramerate = 0.0F; + RPT(RPT_WRN, "frame rate:0"); + } } diff --git a/src/Extension/SPSParser.h b/src/Extension/SPSParser.h index 63f8d5f6..1fb97adc 100644 --- a/src/Extension/SPSParser.h +++ b/src/Extension/SPSParser.h @@ -237,184 +237,204 @@ typedef struct T_PPS { typedef struct T_HEVCWindow { - unsigned int left_offset; - unsigned int right_offset; - unsigned int top_offset; - unsigned int bottom_offset; + unsigned int uiLeftOffset; + unsigned int uiRightOffset; + unsigned int uiTopOffset; + unsigned int uiBottomOffset; } T_HEVCWindow; typedef struct T_VUI { - T_AVRational sar; + T_AVRational tSar; - int overscan_info_present_flag; - int overscan_appropriate_flag; + int iOverscanInfoPresentFlag; + int iOverscanAppropriateFlag; - int video_signal_type_present_flag; - int video_format; - int video_full_range_flag; - int colour_description_present_flag; - uint8_t colour_primaries; - uint8_t transfer_characteristic; - uint8_t matrix_coeffs; + int iVideoSignalTypePresentFlag; + int iVideoFormat; + int iVideoFullRangeFlag; + int iColourDescriptionPresentFlag; + uint8_t u8ColourPrimaries; + uint8_t u8TransferCharacteristic; + uint8_t u8MatrixCoeffs; - int chroma_loc_info_present_flag; - int chroma_sample_loc_type_top_field; - int chroma_sample_loc_type_bottom_field; - int neutra_chroma_indication_flag; + int iChromaLocInfoPresentFlag; + int iChromaSampleLocTypeTopField; + int iChromaSampleLocTypeBottomField; + int iNeutraChromaIndicationFlag; - int field_seq_flag; - int frame_field_info_present_flag; + int iFieldSeqFlag; + int iFrameFieldInfoPresentFlag; - int default_display_window_flag; - T_HEVCWindow def_disp_win; + int iDefaultDisplayWindowFlag; + T_HEVCWindow tDefDispWin; - int vui_timing_info_present_flag; - uint32_t vui_num_units_in_tick; - uint32_t vui_time_scale; - int vui_poc_proportional_to_timing_flag; - int vui_num_ticks_poc_diff_one_minus1; - int vui_hrd_parameters_present_flag; + int iVuiTimingInfoPresentFlag; + uint32_t u32VuiNumUnitsInTick; + uint32_t u32VuiTimeScale; + int iVuiPocProportionalToTimingFlag; + int iVuiNumTicksPocDiffOneMinus1; + int iVuiHrdParametersPresentFlag; - int bitstream_restriction_flag; - int tiles_fixed_structure_flag; - int motion_vectors_over_pic_boundaries_flag; - int restricted_ref_pic_lists_flag; - int min_spatial_segmentation_idc; - int max_bytes_per_pic_denom; - int max_bits_per_min_cu_denom; - int log2_max_mv_length_horizontal; - int log2_max_mv_length_vertical; + int iBitstreamRestrictionFlag; + int iTilesFixedStructureFlag; + int iMotionVectorsOverPicBoundariesFlag; + int iRestrictedRefPicListsFlag; + int iMinSpatialSegmentationIdc; + int iMaxBytesPerPicDenom; + int iMaxBitsPerMinCuDenom; + int iLog2MaxMvLengthHorizontal; + int iLog2MaxMvLengthVertical; } T_VUI; typedef struct T_PTLCommon { - uint8_t profile_space; - uint8_t tier_flag; - uint8_t profile_idc; - uint8_t profile_compatibility_flag[32]; - uint8_t level_idc; - uint8_t progressive_source_flag; - uint8_t interlaced_source_flag; - uint8_t non_packed_constraint_flag; - uint8_t frame_only_constraint_flag; + uint8_t u8ProfileSpace; + uint8_t u8TierFlag; + uint8_t u8ProfileIdc; + uint8_t au8ProfileCompatibilityFlag[32]; + uint8_t u8LevelIdc; + uint8_t u8ProgressiveSourceFlag; + uint8_t u8InterlacedSourceFlag; + uint8_t u8NonPackedConstraintFlag; + uint8_t u8FrameOnlyConstraintFlag; } T_PTLCommon; typedef struct T_PTL { - T_PTLCommon general_ptl; - T_PTLCommon sub_layer_ptl[HEVC_MAX_SUB_LAYERS]; + T_PTLCommon tGeneralPtl; + T_PTLCommon atSubLayerPtl[HEVC_MAX_SUB_LAYERS]; - uint8_t sub_layer_profile_present_flag[HEVC_MAX_SUB_LAYERS]; - uint8_t sub_layer_level_present_flag[HEVC_MAX_SUB_LAYERS]; + uint8_t au8SubLayerProfilePresentFlag[HEVC_MAX_SUB_LAYERS]; + uint8_t au8SubLayerLevelPresentFlag[HEVC_MAX_SUB_LAYERS]; } T_PTL; typedef struct T_ScalingList { /* This is a little wasteful, since sizeID 0 only needs 8 coeffs, * and size ID 3 only has 2 arrays, not 6. */ - uint8_t sl[4][6][64]; - uint8_t sl_dc[2][6]; + uint8_t aaau8Sl[4][6][64]; + uint8_t aau8SlDc[2][6]; } T_ScalingList; typedef struct T_ShortTermRPS { - unsigned int num_negative_pics; - int num_delta_pocs; - int rps_idx_num_delta_pocs; - int32_t delta_poc[32]; - uint8_t used[32]; + unsigned int uiNumNegativePics; + int iNumDeltaPocs; + int iRpsIdxNumDeltaPocs; + int32_t au32DeltaPoc[32]; + uint8_t au8Used[32]; } T_ShortTermRPS; +typedef struct T_HEVCVPS { + uint8_t u8VpsTemporalIdNestingFlag; + int iVpsMaxLayers; + int iVpsMaxSubLayers; ///< vps_max_temporal_layers_minus1 + 1 + + T_PTL tPtl; + int iVpsSubLayerOrderingInfoPresentFlag; + unsigned int uiVpsMaxDecPicBuffering[HEVC_MAX_SUB_LAYERS]; + unsigned int auiVpsNumReorderPics[HEVC_MAX_SUB_LAYERS]; + unsigned int auiVpsMaxLatencyIncrease[HEVC_MAX_SUB_LAYERS]; + int iVpsMaxLayerId; + int iVpsNumLayerSets; ///< vps_num_layer_sets_minus1 + 1 + uint8_t u8VpsTimingInfoPresentFlag; + uint32_t u32VpsNumUnitsInTick; + uint32_t u32VpsTimeScale; + uint8_t u8VpsPocProportionalToTimingFlag; + int iVpsNumTicksPocDiffOne; ///< vps_num_ticks_poc_diff_one_minus1 + 1 + int iVpsNumHrdParameters; + +} T_HEVCVPS; + typedef struct T_HEVCSPS { - unsigned vps_id; - int chroma_format_idc; - uint8_t separate_colour_plane_flag; + unsigned int uiVpsId; + int iChromaFormatIdc; + uint8_t u8SeparateColourPlaneFlag; ///< output (i.e. cropped) values - int output_width, output_height; - T_HEVCWindow output_window; + int iIutputWidth, iOutputHeight; + T_HEVCWindow tOutputWindow; - T_HEVCWindow pic_conf_win; + T_HEVCWindow tPicConfWin; - int bit_depth; - int bit_depth_chroma; - int pixel_shift; -// enum AVPixelFormat pix_fmt; + int iBitDepth; + int iBitDepthChroma; + int iPixelShift; - unsigned int log2_max_poc_lsb; - int pcm_enabled_flag; + unsigned int uiLog2MaxPocLsb; + int iPcmEnabledFlag; - int max_sub_layers; + int iMaxSubLayers; struct { - int max_dec_pic_buffering; - int num_reorder_pics; - int max_latency_increase; - } temporal_layer[HEVC_MAX_SUB_LAYERS]; - uint8_t temporal_id_nesting_flag; + int iMaxDecPicBuffering; + int iNumReorderPics; + int iMaxLatencyIncrease; + } stTemporalLayer[HEVC_MAX_SUB_LAYERS]; + uint8_t u8temporalIdNestingFlag; - T_VUI vui; - T_PTL ptl; + T_VUI tVui; + T_PTL tPtl; - uint8_t scaling_list_enable_flag; - T_ScalingList scaling_list; + uint8_t u8ScalingListEnableFlag; + T_ScalingList tScalingList; - unsigned int nb_st_rps; - T_ShortTermRPS st_rps[HEVC_MAX_SHORT_TERM_RPS_COUNT]; + unsigned int uiNbStRps; + T_ShortTermRPS atStRps[HEVC_MAX_SHORT_TERM_RPS_COUNT]; - uint8_t amp_enabled_flag; - uint8_t sao_enabled; + uint8_t u8AmpEnabledFlag; + uint8_t u8SaoEnabled; - uint8_t long_term_ref_pics_present_flag; - uint16_t lt_ref_pic_poc_lsb_sps[32]; - uint8_t used_by_curr_pic_lt_sps_flag[32]; - uint8_t num_long_term_ref_pics_sps; + uint8_t u8LongTermRefPicsPresentFlag; + uint16_t au16LtRefPicPocLsbSps[32]; + uint8_t au8UsedByCurrPicLtSpsFlag[32]; + uint8_t u8NumLongTermRefPicsSps; struct { - uint8_t bit_depth; - uint8_t bit_depth_chroma; - unsigned int log2_min_pcm_cb_size; - unsigned int log2_max_pcm_cb_size; - uint8_t loop_filter_disable_flag; + uint8_t u8BitDepth; + uint8_t u8BitDepthChroma; + unsigned int uiLog2MinPcmCbSize; + unsigned int uiLog2MaxPcmCbSize; + uint8_t u8LoopFilterDisableFlag; } pcm; - uint8_t sps_temporal_mvp_enabled_flag; - uint8_t sps_strong_intra_smoothing_enable_flag; + uint8_t u8SpsTemporalMvpEnabledFlag; + uint8_t u8SpsStrongIntraMmoothingEnableFlag; - unsigned int log2_min_cb_size; - unsigned int log2_diff_max_min_coding_block_size; - unsigned int log2_min_tb_size; - unsigned int log2_max_trafo_size; - unsigned int log2_ctb_size; - unsigned int log2_min_pu_size; + unsigned int uiLog2MinCbSize; + unsigned int uiLog2DiffMaxMinCodingBlockSize; + unsigned int uiLog2MinTbSize; + unsigned int uiLog2MaxTrafoSize; + unsigned int uiLog2CtbSize; + unsigned int uiLog2MinPuSize; - int max_transform_hierarchy_depth_inter; - int max_transform_hierarchy_depth_intra; + int iMaxTransformHierarchyDepthInter; + int iMaxTransformHierarchyDepthIntra; - int transform_skip_rotation_enabled_flag; - int transform_skip_context_enabled_flag; - int implicit_rdpcm_enabled_flag; - int explicit_rdpcm_enabled_flag; - int intra_smoothing_disabled_flag; - int persistent_rice_adaptation_enabled_flag; + int iTransformSkipRotationEnabledFlag; + int iTransformSkipContextEnabledFlag; + int iImplicitRdpcmEnabledFlag; + int iExplicitRdpcmEnabledFlag; + int iIntraSmoothingDisabledFlag; + int iHighPrecisionOffsetsEnabledFlag; + int iPersistentRiceAdaptationEnabledFlag; ///< coded frame dimension in various units - int width; - int height; - int ctb_width; - int ctb_height; - int ctb_size; - int min_cb_width; - int min_cb_height; - int min_tb_width; - int min_tb_height; - int min_pu_width; - int min_pu_height; - int tb_mask; + int iWidth; + int iHeight; + int iCtbWidth; + int iCtbHeight; + int iCtbSize; + int iMinCbWidth; + int iMinCbHeight; + int iMinTbWidth; + int iMinTbHeight; + int iMinPuWidth; + int iMinPuHeight; + int iTbMask; - int hshift[3]; - int vshift[3]; + int aiHshift[3]; + int aiVshift[3]; - int qp_bd_offset; + int iQpBdOffset; - uint8_t data[4096]; - int data_size; + int iVuiPresent; }T_HEVCSPS; @@ -428,13 +448,15 @@ typedef struct T_GetBitContext{ int h264DecSeqParameterSet(void *pvBuf, T_SPS *ptSps); -int h265DecSeqParameterSet( void *pvBufSrc, T_HEVCSPS *p_sps ); +int h265DecSeqParameterSet( void *pvBufSrc, T_HEVCSPS *ptSps ); +int h265DecVideoParameterSet( void *pvBufSrc, T_HEVCVPS *ptVps ); + void h264GetWidthHeight(T_SPS *ptSps, int *piWidth, int *piHeight); void h265GetWidthHeight(T_HEVCSPS *ptSps, int *piWidth, int *piHeight); void h264GeFramerate(T_SPS *ptSps, float *pfFramerate); -void h265GeFramerate(T_HEVCSPS *ptSps, float *pfFramerate); +void h265GeFramerate(T_HEVCVPS *ptVps, T_HEVCSPS *ptSps,float *pfFramerate); #if defined (__cplusplus) } From 35c324b6b4da464682992a4e59576f77d50b87ea Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Fri, 2 Aug 2019 10:53:00 +0800 Subject: [PATCH 15/30] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E9=A6=96=E5=B8=A7?= =?UTF-8?q?=E4=B8=8D=E6=98=AFI=E5=B8=A7=20=E5=AF=BC=E8=87=B4=E8=8A=B1?= =?UTF-8?q?=E5=B1=8F=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/MediaFile/MP4Muxer.cpp | 8 ++++++++ src/MediaFile/MP4Muxer.h | 1 + src/MediaFile/Mp4Maker.cpp | 6 ++---- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/MediaFile/MP4Muxer.cpp b/src/MediaFile/MP4Muxer.cpp index afa78762..cedc7c4f 100644 --- a/src/MediaFile/MP4Muxer.cpp +++ b/src/MediaFile/MP4Muxer.cpp @@ -79,6 +79,14 @@ void MP4Muxer::onTrackFrame(const Frame::Ptr &frame) { return; } + if(frame->getTrackType() == TrackVideo){ + if(!_started && !frame->keyFrame()){ + //第一帧必须是I帧,防止花屏 + return; + } + _started = true; + } + int with_nalu_size ; switch (frame->getCodecId()){ case CodecH264: diff --git a/src/MediaFile/MP4Muxer.h b/src/MediaFile/MP4Muxer.h index a458b4ca..5b8d2f27 100644 --- a/src/MediaFile/MP4Muxer.h +++ b/src/MediaFile/MP4Muxer.h @@ -80,6 +80,7 @@ private: uint32_t start_pts = 0; }; map _codec_to_trackid; + bool _started = false; }; diff --git a/src/MediaFile/Mp4Maker.cpp b/src/MediaFile/Mp4Maker.cpp index a4ec0d89..3cf2a7ec 100644 --- a/src/MediaFile/Mp4Maker.cpp +++ b/src/MediaFile/Mp4Maker.cpp @@ -89,10 +89,8 @@ void Mp4Maker::createFile() { try { _muxer = std::make_shared(strFileTmp.data()); for(auto &track :_tracks){ - if(track){ - //添加track - _muxer->addTrack(track); - } + //添加track + _muxer->addTrack(track); } _strFileTmp = strFileTmp; _strFile = strFile; From a400b39fab17cf70b740c5dc1f857208d286e719 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Fri, 2 Aug 2019 11:09:17 +0800 Subject: [PATCH 16/30] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=8F=AF=E8=83=BD?= =?UTF-8?q?=E4=B8=A2=E5=B8=A7=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Common/MediaSink.cpp | 5 +++-- src/Common/MediaSink.h | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Common/MediaSink.cpp b/src/Common/MediaSink.cpp index a83fc855..4d45f82e 100644 --- a/src/Common/MediaSink.cpp +++ b/src/Common/MediaSink.cpp @@ -41,7 +41,7 @@ void MediaSink::addTrack(const Track::Ptr &track_in) { if(!strongSelf){ return; } - if(strongSelf->_allTrackReady){ + if(!strongSelf->_anyTrackUnReady){ strongSelf->onTrackFrame(frame); } })); @@ -53,6 +53,7 @@ void MediaSink::addTrack(const Track::Ptr &track_in) { if(track->ready()){ lam(); }else{ + _anyTrackUnReady = true; _allTrackReady = false; _trackReadyCallback[codec_id] = lam; _ticker.resetTime(); @@ -79,7 +80,7 @@ void MediaSink::inputFrame(const Frame::Ptr &frame) { if(!_allTrackReady && (_trackReadyCallback.empty() || _ticker.elapsedTime() > MAX_WAIT_MS)){ _allTrackReady = true; - + _anyTrackUnReady = false; if(!_trackReadyCallback.empty()){ //这是超时强制忽略未准备好的Track _trackReadyCallback.clear(); diff --git a/src/Common/MediaSink.h b/src/Common/MediaSink.h index 7dc9fff0..a45b9638 100644 --- a/src/Common/MediaSink.h +++ b/src/Common/MediaSink.h @@ -99,6 +99,7 @@ private: map _track_map; map > _trackReadyCallback; bool _allTrackReady = false; + bool _anyTrackUnReady = false; Ticker _ticker; }; From 892734bfd83aaef726b6d772c9e97a217a87e698 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Fri, 2 Aug 2019 11:54:05 +0800 Subject: [PATCH 17/30] =?UTF-8?q?=E5=AE=8C=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/MediaFile/MP4Muxer.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/MediaFile/MP4Muxer.cpp b/src/MediaFile/MP4Muxer.cpp index cedc7c4f..076cc86c 100644 --- a/src/MediaFile/MP4Muxer.cpp +++ b/src/MediaFile/MP4Muxer.cpp @@ -79,11 +79,13 @@ void MP4Muxer::onTrackFrame(const Frame::Ptr &frame) { return; } - if(frame->getTrackType() == TrackVideo){ - if(!_started && !frame->keyFrame()){ - //第一帧必须是I帧,防止花屏 + if(!_started){ + //还没开始 + if(frame->getTrackType() != TrackVideo || !frame->keyFrame()){ + //如果首帧是音频或者是视频但是不是i帧,那么不能开始写文件 return; } + //开始写文件 _started = true; } From 36ed78ba1ff25a959ac313b6f898d45988b2ae2e Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Fri, 2 Aug 2019 13:51:24 +0800 Subject: [PATCH 18/30] =?UTF-8?q?=E8=A7=84=E8=8C=83=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E5=91=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Extension/H264.cpp | 6 +++--- src/Extension/H264.h | 1 - src/Extension/H265.cpp | 13 ++++--------- src/Extension/H265.h | 5 ++--- 4 files changed, 9 insertions(+), 16 deletions(-) diff --git a/src/Extension/H264.cpp b/src/Extension/H264.cpp index 83336248..2d93db34 100644 --- a/src/Extension/H264.cpp +++ b/src/Extension/H264.cpp @@ -32,9 +32,6 @@ using namespace toolkit; namespace mediakit{ -bool getAVCInfo(const string& strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps) { - return getAVCInfo(strSps.data(),strSps.size(),iVideoWidth,iVideoHeight,iVideoFps); -} bool getAVCInfo(const char * sps,int sps_len,int &iVideoWidth, int &iVideoHeight, float &iVideoFps){ T_GetBitContext tGetBitBuf; T_SPS tH264SpsInfo; @@ -51,6 +48,9 @@ bool getAVCInfo(const char * sps,int sps_len,int &iVideoWidth, int &iVideoHeight return true; } +bool getAVCInfo(const string& strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps) { + return getAVCInfo(strSps.data(),strSps.size(),iVideoWidth,iVideoHeight,iVideoFps); +} const char *memfind(const char *buf, int len, const char *subbuf, int sublen) { for (auto i = 0; i < len - sublen; ++i) { diff --git a/src/Extension/H264.h b/src/Extension/H264.h index 4cb91135..bfe77861 100644 --- a/src/Extension/H264.h +++ b/src/Extension/H264.h @@ -36,7 +36,6 @@ using namespace toolkit; namespace mediakit{ bool getAVCInfo(const string &strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps); -bool getAVCInfo(const char * sps,int sps_len,int &iVideoWidth, int &iVideoHeight, float &iVideoFps); void splitH264(const char *ptr, int len, const std::function &cb); /** diff --git a/src/Extension/H265.cpp b/src/Extension/H265.cpp index 4287020a..fc7fd8f2 100644 --- a/src/Extension/H265.cpp +++ b/src/Extension/H265.cpp @@ -30,14 +30,7 @@ namespace mediakit{ - - -bool getAVCH265Info(const string& strVps, const string& strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps) { - return getAVC265Info(strVps.data(),strVps.size(),strSps.data(),strSps.size(),iVideoWidth,iVideoHeight,iVideoFps); - -} - -bool getAVC265Info(const char * vps, int vps_len,const char * sps,int sps_len,int &iVideoWidth, int &iVideoHeight, float &iVideoFps){ +bool getHEVCInfo(const char * vps, int vps_len,const char * sps,int sps_len,int &iVideoWidth, int &iVideoHeight, float &iVideoFps){ T_GetBitContext tGetBitBuf; T_HEVCSPS tH265SpsInfo; T_HEVCVPS tH265VpsInfo; @@ -69,7 +62,9 @@ bool getAVC265Info(const char * vps, int vps_len,const char * sps,int sps_len,in return true; } - +bool getHEVCInfo(const string &strVps, const string &strSps, int &iVideoWidth, int &iVideoHeight, float &iVideoFps) { + return getHEVCInfo(strVps.data(),strVps.size(),strSps.data(),strSps.size(),iVideoWidth,iVideoHeight,iVideoFps); +} Sdp::Ptr H265Track::getSdp() { if(!ready()){ diff --git a/src/Extension/H265.h b/src/Extension/H265.h index 12022424..295a98ac 100644 --- a/src/Extension/H265.h +++ b/src/Extension/H265.h @@ -36,8 +36,7 @@ using namespace toolkit; namespace mediakit { -bool getAVCH265Info(const string& strVps,const string& strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps); -bool getAVC265Info(const char * vps, int vps_len,const char * sps,int sps_len,int &iVideoWidth, int &iVideoHeight, float &iVideoFps); +bool getHEVCInfo(const string &strVps, const string &strSps, int &iVideoWidth, int &iVideoHeight, float &iVideoFps); /** * 265帧类 @@ -336,7 +335,7 @@ private: * 解析sps获取宽高fps */ void onReady(){ - getAVCH265Info(_vps,_sps,_width,_height,_fps); + getHEVCInfo(_vps, _sps, _width, _height, _fps); } Track::Ptr clone() override { return std::make_shared::type>(*this); From 6a9eb8d54bd8a4aae0723d252622a8f1eb90ab05 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Fri, 2 Aug 2019 17:33:31 +0800 Subject: [PATCH 19/30] =?UTF-8?q?=E5=B0=9D=E8=AF=95=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E6=97=B6=E9=97=B4=E6=88=B3=E5=9B=9E=E7=8E=AF=E6=88=96=E4=B9=B1?= =?UTF-8?q?=E5=BA=8F=E5=AF=BC=E8=87=B4=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/MediaFile/MP4Muxer.cpp | 32 +++++++++++++++++++++++++------- src/MediaFile/MP4Muxer.h | 4 ++-- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/src/MediaFile/MP4Muxer.cpp b/src/MediaFile/MP4Muxer.cpp index 076cc86c..3e279d15 100644 --- a/src/MediaFile/MP4Muxer.cpp +++ b/src/MediaFile/MP4Muxer.cpp @@ -107,20 +107,38 @@ void MP4Muxer::onTrackFrame(const Frame::Ptr &frame) { if(!track_info.start_dts){ track_info.start_dts = frame->dts(); } - if(!track_info.start_pts){ - track_info.start_pts = frame->pts(); - } //相对时间戳 - int dts_inc = frame->dts() - track_info.start_dts; - int pts_inc = frame->pts() - track_info.start_pts; + int64_t dts_inc = frame->dts() - track_info.start_dts; + //pts和dts的差值 + int pts_dts_diff = frame->pts() - frame->dts(); + if(pts_dts_diff > 200 || pts_dts_diff < -200){ + //如果差值大于200毫秒,则认为由于回环导致时间戳错乱了 + pts_dts_diff = 0; + } + + if(dts_inc < track_info.dts_inc){ + //本次相对时间戳竟然小于上次? + if(dts_inc < 0){ + //时间戳回环,保证下次相对时间戳与本次相对合理增长 + track_info.start_dts = frame->dts() - track_info.dts_inc; + //本次时间戳强制等于上次时间戳+10 + dts_inc = track_info.dts_inc + 10; + }else{ + //时间戳变小了?,那么取上次时间戳+10 + dts_inc = track_info.dts_inc + 10; + } + } + + //保留上次相对时间戳 + track_info.dts_inc = dts_inc; mov_writer_write_l(_mov_writter.get(), track_info.track_id, frame->data() + frame->prefixSize(), frame->size() - frame->prefixSize(), - pts_inc >= 0 ? pts_inc : 0, - dts_inc >= 0 ? dts_inc : 0, + pts_dts_diff + dts_inc, + dts_inc, frame->keyFrame() ? MOV_AV_FLAG_KEYFREAME : 0, with_nalu_size); } diff --git a/src/MediaFile/MP4Muxer.h b/src/MediaFile/MP4Muxer.h index 5b8d2f27..79793323 100644 --- a/src/MediaFile/MP4Muxer.h +++ b/src/MediaFile/MP4Muxer.h @@ -76,8 +76,8 @@ protected: private: struct track_info{ int track_id = -1; - uint32_t start_dts = 0; - uint32_t start_pts = 0; + int64_t start_dts = 0; + int64_t dts_inc = 0; }; map _codec_to_trackid; bool _started = false; From f9426c2cfb0027603328b4f2aae377a60b3d8def Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Fri, 2 Aug 2019 18:06:37 +0800 Subject: [PATCH 20/30] =?UTF-8?q?=E5=B0=9D=E8=AF=95=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E6=97=B6=E9=97=B4=E6=88=B3=E5=9B=9E=E7=8E=AF=E6=88=96=E4=B9=B1?= =?UTF-8?q?=E5=BA=8F=E5=AF=BC=E8=87=B4=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/MediaFile/MP4Muxer.cpp | 34 +++--------------- src/MediaFile/MP4Muxer.h | 6 ++-- src/MediaFile/Stamp.cpp | 74 ++++++++++++++++++++++++++++++++++++++ src/MediaFile/Stamp.h | 48 +++++++++++++++++++++++++ src/MediaFile/TsMuxer.cpp | 44 ++++++++++++++--------- src/MediaFile/TsMuxer.h | 9 ++++- 6 files changed, 165 insertions(+), 50 deletions(-) create mode 100644 src/MediaFile/Stamp.cpp create mode 100644 src/MediaFile/Stamp.h diff --git a/src/MediaFile/MP4Muxer.cpp b/src/MediaFile/MP4Muxer.cpp index 3e279d15..3f575e83 100644 --- a/src/MediaFile/MP4Muxer.cpp +++ b/src/MediaFile/MP4Muxer.cpp @@ -104,41 +104,15 @@ void MP4Muxer::onTrackFrame(const Frame::Ptr &frame) { //mp4文件时间戳需要从0开始 auto &track_info = it->second; - if(!track_info.start_dts){ - track_info.start_dts = frame->dts(); - } - - //相对时间戳 - int64_t dts_inc = frame->dts() - track_info.start_dts; - //pts和dts的差值 - int pts_dts_diff = frame->pts() - frame->dts(); - if(pts_dts_diff > 200 || pts_dts_diff < -200){ - //如果差值大于200毫秒,则认为由于回环导致时间戳错乱了 - pts_dts_diff = 0; - } - - if(dts_inc < track_info.dts_inc){ - //本次相对时间戳竟然小于上次? - if(dts_inc < 0){ - //时间戳回环,保证下次相对时间戳与本次相对合理增长 - track_info.start_dts = frame->dts() - track_info.dts_inc; - //本次时间戳强制等于上次时间戳+10 - dts_inc = track_info.dts_inc + 10; - }else{ - //时间戳变小了?,那么取上次时间戳+10 - dts_inc = track_info.dts_inc + 10; - } - } - - //保留上次相对时间戳 - track_info.dts_inc = dts_inc; + int64_t dts_out, pts_out; + track_info.stamp.revise(frame->dts(),frame->pts(),dts_out,pts_out); mov_writer_write_l(_mov_writter.get(), track_info.track_id, frame->data() + frame->prefixSize(), frame->size() - frame->prefixSize(), - pts_dts_diff + dts_inc, - dts_inc, + pts_out, + dts_out, frame->keyFrame() ? MOV_AV_FLAG_KEYFREAME : 0, with_nalu_size); } diff --git a/src/MediaFile/MP4Muxer.h b/src/MediaFile/MP4Muxer.h index 79793323..a1191b79 100644 --- a/src/MediaFile/MP4Muxer.h +++ b/src/MediaFile/MP4Muxer.h @@ -39,6 +39,7 @@ #include "Extension/AAC.h" #include "Extension/H264.h" #include "Extension/H265.h" +#include "Stamp.h" namespace mediakit{ @@ -76,10 +77,9 @@ protected: private: struct track_info{ int track_id = -1; - int64_t start_dts = 0; - int64_t dts_inc = 0; + Stamp stamp; }; - map _codec_to_trackid; + unordered_map _codec_to_trackid; bool _started = false; }; diff --git a/src/MediaFile/Stamp.cpp b/src/MediaFile/Stamp.cpp new file mode 100644 index 00000000..d90679b5 --- /dev/null +++ b/src/MediaFile/Stamp.cpp @@ -0,0 +1,74 @@ +/* + * MIT License + * + * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> + * + * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "Stamp.h" + +namespace mediakit { + +void Stamp::revise(uint32_t dts, uint32_t pts, int64_t &dts_out, int64_t &pts_out) { + if(_first){ + //记录第一次时间戳,后面好计算时间戳增量 + _start_dts = dts; + _first = false; + } + + //相对时间戳 + dts_out = dts - _start_dts; + if(dts_out < _dts_inc){ + //本次相对时间戳竟然小于上次? + if(dts_out < 0 || _dts_inc - dts_out > 0xFFFF){ + //时间戳回环,保证下次相对时间戳与本次相对合理增长 + _start_dts = dts - _dts_inc; + //本次时间戳强制等于上次时间戳 + dts_out = _dts_inc; + }else{ + //时间戳变小了?,那么取上次时间戳 + dts_out = _dts_inc; + } + } + + //保留这次相对时间戳,以便下次对比是否回环或乱序 + _dts_inc = dts_out; + + //////////////以下是播放时间戳的计算////////////////// + if(!pts){ + //没有播放时间戳 + pts = dts; + } + //pts和dts的差值 + int pts_dts_diff = pts - dts; + if(pts_dts_diff > 200 || pts_dts_diff < -200){ + //如果差值大于200毫秒,则认为由于回环导致时间戳错乱了 + pts_dts_diff = 0; + } + pts_out = dts_out + pts_dts_diff; + if(pts_out < 0){ + //时间戳不能小于0 + pts_out = 0; + } +} + +}//namespace mediakit \ No newline at end of file diff --git a/src/MediaFile/Stamp.h b/src/MediaFile/Stamp.h new file mode 100644 index 00000000..d111c947 --- /dev/null +++ b/src/MediaFile/Stamp.h @@ -0,0 +1,48 @@ +/* + * MIT License + * + * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> + * + * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef ZLMEDIAKIT_STAMP_H +#define ZLMEDIAKIT_STAMP_H + + +#include + +namespace mediakit { + +class Stamp { +public: + Stamp() = default; + ~Stamp() = default; + void revise(uint32_t dts, uint32_t pts, int64_t &dts_out, int64_t &pts_out); +private: + int64_t _start_dts = 0; + int64_t _dts_inc = 0; + bool _first = true; +}; + +}//namespace mediakit + +#endif //ZLMEDIAKIT_STAMP_H diff --git a/src/MediaFile/TsMuxer.cpp b/src/MediaFile/TsMuxer.cpp index 2eabd145..d1eeee1b 100644 --- a/src/MediaFile/TsMuxer.cpp +++ b/src/MediaFile/TsMuxer.cpp @@ -41,25 +41,35 @@ TsMuxer::~TsMuxer() { void TsMuxer::addTrack(const Track::Ptr &track) { switch (track->getCodecId()){ - case CodecH264: - _codecid_to_stream_id[CodecH264] = mpeg_ts_add_stream(_context,PSI_STREAM_H264, nullptr,0); - break; - case CodecH265: - _codecid_to_stream_id[CodecH265] = mpeg_ts_add_stream(_context,PSI_STREAM_H265, nullptr,0); - break; - case CodecAAC: - _codecid_to_stream_id[CodecAAC] = mpeg_ts_add_stream(_context,PSI_STREAM_AAC, nullptr,0); - break; + case CodecH264: { + track_info info; + info.track_id = mpeg_ts_add_stream(_context, PSI_STREAM_H264, nullptr, 0); + _codec_to_trackid[track->getCodecId()] = info; + } break; + case CodecH265: { + track_info info; + info.track_id = mpeg_ts_add_stream(_context, PSI_STREAM_H265, nullptr, 0); + _codec_to_trackid[track->getCodecId()] = info; + }break; + case CodecAAC: { + track_info info; + info.track_id = mpeg_ts_add_stream(_context, PSI_STREAM_AAC, nullptr, 0); + _codec_to_trackid[track->getCodecId()] = info; + }break; default: break; } } void TsMuxer::inputFrame(const Frame::Ptr &frame) { - auto it = _codecid_to_stream_id.find(frame->getCodecId()); - if(it == _codecid_to_stream_id.end()){ + auto it = _codec_to_trackid.find(frame->getCodecId()); + if(it == _codec_to_trackid.end()){ return; } + //mp4文件时间戳需要从0开始 + auto &track_info = it->second; + int64_t dts_out, pts_out; + switch (frame->getCodecId()){ case CodecH265: case CodecH264: { @@ -79,16 +89,18 @@ void TsMuxer::inputFrame(const Frame::Ptr &frame) { }); merged_frame = std::make_shared(std::move(merged)); } - _timestamp = back->dts(); - mpeg_ts_write(_context, it->second, back->keyFrame() ? 0x0001 : 0, back->pts() * 90LL, back->dts() * 90LL, merged_frame->data(), merged_frame->size()); + track_info.stamp.revise(back->dts(),back->pts(),dts_out,pts_out); + _timestamp = dts_out; + mpeg_ts_write(_context, track_info.track_id, back->keyFrame() ? 0x0001 : 0, pts_out * 90LL, dts_out * 90LL, merged_frame->data(), merged_frame->size()); _frameCached.clear(); } _frameCached.emplace_back(Frame::getCacheAbleFrame(frame)); } break; default: { - _timestamp = frame->dts(); - mpeg_ts_write(_context, it->second, frame->keyFrame() ? 0x0001 : 0, frame->pts() * 90LL, frame->dts() * 90LL, frame->data(), frame->size()); + track_info.stamp.revise(frame->dts(),frame->pts(),dts_out,pts_out); + _timestamp = dts_out; + mpeg_ts_write(_context, track_info.track_id, frame->keyFrame() ? 0x0001 : 0, pts_out * 90LL, dts_out * 90LL, frame->data(), frame->size()); } break; } @@ -124,7 +136,7 @@ void TsMuxer::uninit() { mpeg_ts_destroy(_context); _context = nullptr; } - _codecid_to_stream_id.clear(); + _codec_to_trackid.clear(); } }//namespace mediakit diff --git a/src/MediaFile/TsMuxer.h b/src/MediaFile/TsMuxer.h index 8185307f..06230bb5 100644 --- a/src/MediaFile/TsMuxer.h +++ b/src/MediaFile/TsMuxer.h @@ -32,6 +32,8 @@ #include "Extension/Track.h" #include "Util/File.h" #include "Common/MediaSink.h" +#include "Stamp.h" + using namespace toolkit; namespace mediakit { @@ -52,7 +54,12 @@ private: void *_context = nullptr; char *_tsbuf[188]; uint32_t _timestamp = 0; - unordered_map _codecid_to_stream_id; + + struct track_info{ + int track_id = -1; + Stamp stamp; + }; + unordered_map _codec_to_trackid; List _frameCached; }; From 462eac9aeaab80dac0dd55fa5bc1eb1482138746 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Sun, 4 Aug 2019 23:16:05 +0800 Subject: [PATCH 21/30] =?UTF-8?q?=E6=9B=B4=E6=96=B0ZLToolKit(=E4=BC=98?= =?UTF-8?q?=E5=8C=96windows=E4=B8=8B=E7=BA=BF=E7=A8=8B=E5=88=87=E6=8D=A2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 3rdpart/ZLToolKit | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/3rdpart/ZLToolKit b/3rdpart/ZLToolKit index 936d3c05..07b04c5d 160000 --- a/3rdpart/ZLToolKit +++ b/3rdpart/ZLToolKit @@ -1 +1 @@ -Subproject commit 936d3c05b183cba279bb348f8eac9eca0cc810c2 +Subproject commit 07b04c5d8b0cc4702fd216b2740efcd259829c75 From 008df0ab85e686bc6aa3e0b989e1d50131aad7f7 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Sun, 4 Aug 2019 23:58:54 +0800 Subject: [PATCH 22/30] =?UTF-8?q?=E5=8E=BB=E9=99=A4=E7=BB=A7=E6=89=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/MediaFile/TsMuxer.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/MediaFile/TsMuxer.h b/src/MediaFile/TsMuxer.h index 06230bb5..f639bf6a 100644 --- a/src/MediaFile/TsMuxer.h +++ b/src/MediaFile/TsMuxer.h @@ -38,12 +38,12 @@ using namespace toolkit; namespace mediakit { -class TsMuxer : public MediaSink{ +class TsMuxer { public: TsMuxer(); virtual ~TsMuxer(); - void addTrack(const Track::Ptr &track) override; - void inputFrame(const Frame::Ptr &frame) override ; + void addTrack(const Track::Ptr &track) ; + void inputFrame(const Frame::Ptr &frame) ; protected: virtual void onTs(const void *packet, int bytes,uint32_t timestamp,int flags) = 0; void resetTracks(); From 2020e23437504b45a53cfa2d1b034114abfb5ee3 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Tue, 6 Aug 2019 16:23:20 +0800 Subject: [PATCH 23/30] =?UTF-8?q?=E5=85=BC=E5=AE=B9=E6=9F=90=E4=BA=9B?= =?UTF-8?q?=E4=B8=8D=E8=A7=84=E8=8C=83=E7=9A=84sdp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Extension/Factory.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Extension/Factory.cpp b/src/Extension/Factory.cpp index afc278a7..36dbc772 100644 --- a/src/Extension/Factory.cpp +++ b/src/Extension/Factory.cpp @@ -36,10 +36,10 @@ namespace mediakit{ Track::Ptr Factory::getTrackBySdp(const SdpTrack::Ptr &track) { if (strcasecmp(track->_codec.data(), "mpeg4-generic") == 0) { string aac_cfg_str = FindField(track->_fmtp.data(), "config=", nullptr); - if (aac_cfg_str.size() != 4) { + if (aac_cfg_str.empty()) { aac_cfg_str = FindField(track->_fmtp.data(), "config=", ";"); } - if (aac_cfg_str.size() != 4) { + if (aac_cfg_str.empty()) { //延后获取adts头 return std::make_shared(); } From 0007734bbb533d7b69d082c3bf7c907513143908 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Tue, 6 Aug 2019 22:51:40 +0800 Subject: [PATCH 24/30] =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E5=88=86=E5=A4=A9=E4=BB=A5=E5=8F=8A=E8=87=AA=E5=8A=A8=E6=B8=85?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/main.cpp | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/server/main.cpp b/server/main.cpp index e796d065..d3d4c27f 100644 --- a/server/main.cpp +++ b/server/main.cpp @@ -127,6 +127,14 @@ public: "日志等级,LTrace~LError(0~4)",/*该选项说明文字*/ nullptr); + (*_parser) << Option('m',/*该选项简称,如果是\x00则说明无简称*/ + "max_day",/*该选项全称,每个选项必须有全称;不得为null或空字符串*/ + Option::ArgRequired,/*该选项后面必须跟值*/ + "7",/*该选项默认值*/ + false,/*该选项是否必须赋值,如果没有默认值且为ArgRequired时用户必须提供该参数否则将抛异常*/ + "日志等级最多保存天数",/*该选项说明文字*/ + nullptr); + (*_parser) << Option('c',/*该选项简称,如果是\x00则说明无简称*/ "config",/*该选项全称,每个选项必须有全称;不得为null或空字符串*/ Option::ArgRequired,/*该选项后面必须跟值*/ @@ -216,11 +224,10 @@ int main(int argc,char *argv[]) { //设置日志 Logger::Instance().add(std::make_shared("ConsoleChannel", logLevel)); -#if defined(__linux__) || defined(__linux) - Logger::Instance().add(std::make_shared("SysLogChannel",logLevel)); -#else - Logger::Instance().add(std::make_shared("FileChannel", exePath() + ".log", logLevel)); -#endif + auto fileChannel = std::make_shared("FileChannel", exeDir() + "log/", logLevel); + //日志最多保存天数 + fileChannel->setMaxDay(cmd_main["max_day"]); + Logger::Instance().add(fileChannel); #if !defined(_WIN32) if (bDaemon) { From 749fb984390b977ae9e99845e0922a32cb6fe4b4 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Tue, 6 Aug 2019 22:52:19 +0800 Subject: [PATCH 25/30] =?UTF-8?q?=E6=9B=B4=E6=96=B0ZLToolKit=EF=BC=88?= =?UTF-8?q?=E6=97=A5=E5=BF=97=E5=88=86=E5=A4=A9=E4=BB=A5=E5=8F=8A=E6=B8=85?= =?UTF-8?q?=E7=90=86=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 3rdpart/ZLToolKit | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/3rdpart/ZLToolKit b/3rdpart/ZLToolKit index 07b04c5d..3bc5bcf9 160000 --- a/3rdpart/ZLToolKit +++ b/3rdpart/ZLToolKit @@ -1 +1 @@ -Subproject commit 07b04c5d8b0cc4702fd216b2740efcd259829c75 +Subproject commit 3bc5bcf917a6ff9fe0c50ed1751e61c04aacc413 From b70d6cd2c2090de7bb0d8669d457f0671c1c09f4 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Tue, 6 Aug 2019 22:54:37 +0800 Subject: [PATCH 26/30] =?UTF-8?q?=E6=94=AF=E6=8C=81=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E6=97=B6=E9=97=B4=E6=88=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/MediaFile/Stamp.cpp | 9 +++++++-- src/MediaFile/Stamp.h | 7 +++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/MediaFile/Stamp.cpp b/src/MediaFile/Stamp.cpp index d90679b5..544559c5 100644 --- a/src/MediaFile/Stamp.cpp +++ b/src/MediaFile/Stamp.cpp @@ -33,6 +33,12 @@ void Stamp::revise(uint32_t dts, uint32_t pts, int64_t &dts_out, int64_t &pts_ou //记录第一次时间戳,后面好计算时间戳增量 _start_dts = dts; _first = false; + _ticker = std::make_shared(); + } + //pts和dts的差值 + int pts_dts_diff = pts - dts; + if(_modifyStamp){ + dts = _ticker->elapsedTime(); } //相对时间戳 @@ -58,8 +64,7 @@ void Stamp::revise(uint32_t dts, uint32_t pts, int64_t &dts_out, int64_t &pts_ou //没有播放时间戳 pts = dts; } - //pts和dts的差值 - int pts_dts_diff = pts - dts; + if(pts_dts_diff > 200 || pts_dts_diff < -200){ //如果差值大于200毫秒,则认为由于回环导致时间戳错乱了 pts_dts_diff = 0; diff --git a/src/MediaFile/Stamp.h b/src/MediaFile/Stamp.h index d111c947..a99269a8 100644 --- a/src/MediaFile/Stamp.h +++ b/src/MediaFile/Stamp.h @@ -27,20 +27,23 @@ #ifndef ZLMEDIAKIT_STAMP_H #define ZLMEDIAKIT_STAMP_H - +#include "Util/TimeTicker.h" #include +using namespace toolkit; namespace mediakit { class Stamp { public: - Stamp() = default; + Stamp(bool modifyStamp = false) {_modifyStamp = modifyStamp;}; ~Stamp() = default; void revise(uint32_t dts, uint32_t pts, int64_t &dts_out, int64_t &pts_out); private: int64_t _start_dts = 0; int64_t _dts_inc = 0; bool _first = true; + bool _modifyStamp; + std::shared_ptr _ticker; }; }//namespace mediakit From 4480dad36f20fcc8c5471b2c701b69f62ac21f53 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Tue, 6 Aug 2019 22:56:09 +0800 Subject: [PATCH 27/30] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/main.cpp b/server/main.cpp index d3d4c27f..cb64df2e 100644 --- a/server/main.cpp +++ b/server/main.cpp @@ -132,7 +132,7 @@ public: Option::ArgRequired,/*该选项后面必须跟值*/ "7",/*该选项默认值*/ false,/*该选项是否必须赋值,如果没有默认值且为ArgRequired时用户必须提供该参数否则将抛异常*/ - "日志等级最多保存天数",/*该选项说明文字*/ + "日志最多保存天数",/*该选项说明文字*/ nullptr); (*_parser) << Option('c',/*该选项简称,如果是\x00则说明无简称*/ From ef61c56cc2dad1e54f5734b125b533740d6e9bf3 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Wed, 7 Aug 2019 18:24:08 +0800 Subject: [PATCH 28/30] =?UTF-8?q?=E4=BC=98=E5=8C=96hls=E7=94=9F=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/MediaFile/TsMuxer.cpp | 52 +++++++++++++++++++++++---------------- src/MediaFile/TsMuxer.h | 2 +- 2 files changed, 32 insertions(+), 22 deletions(-) diff --git a/src/MediaFile/TsMuxer.cpp b/src/MediaFile/TsMuxer.cpp index d1eeee1b..cc685a73 100644 --- a/src/MediaFile/TsMuxer.cpp +++ b/src/MediaFile/TsMuxer.cpp @@ -73,28 +73,38 @@ void TsMuxer::inputFrame(const Frame::Ptr &frame) { switch (frame->getCodecId()){ case CodecH265: case CodecH264: { - //这里的代码逻辑是让SPS、PPS、IDR这些时间戳相同的帧打包到一起当做一个帧处理, - if (!_frameCached.empty() && _frameCached.back()->dts() != frame->dts()) { - Frame::Ptr back = _frameCached.back(); - Buffer::Ptr merged_frame = back; - if(_frameCached.size() != 1){ - string merged; - _frameCached.for_each([&](const Frame::Ptr &frame){ - if(frame->prefixSize()){ - merged.append(frame->data(),frame->size()); - } else{ - merged.append("\x00\x00\x00\x01",4); - merged.append(frame->data(),frame->size()); - } - }); - merged_frame = std::make_shared(std::move(merged)); - } - track_info.stamp.revise(back->dts(),back->pts(),dts_out,pts_out); - _timestamp = dts_out; - mpeg_ts_write(_context, track_info.track_id, back->keyFrame() ? 0x0001 : 0, pts_out * 90LL, dts_out * 90LL, merged_frame->data(), merged_frame->size()); - _frameCached.clear(); + + Buffer::Ptr merged_frame ; + if(frame->configFrame()){ + //配置帧,缓存后直接返回,以便下次输入关键帧时使用 + _config_frame_cache.append("\x00\x00\x00\x01",4); + _config_frame_cache.append(frame->data() + frame->prefixSize(),frame->size() - frame->prefixSize()); + break; } - _frameCached.emplace_back(Frame::getCacheAbleFrame(frame)); + + if(frame->keyFrame()){ + //关键帧 + if(!_config_frame_cache.empty()){ + //有配置帧,那么配置帧合并关键帧后输入ts打包 + _config_frame_cache.append("\x00\x00\x00\x01",4); + _config_frame_cache.append(frame->data() + frame->prefixSize(),frame->size() - frame->prefixSize()); + merged_frame = std::make_shared(std::move(_config_frame_cache)); + _config_frame_cache.clear(); + }else{ + //这是非第一个的关键帧(h265有多种关键帧) + merged_frame = frame; + } + }else{ + //这里是普通帧,例如B/P, + merged_frame = frame; + //sps、pps这些配置帧清空掉 + _config_frame_cache.clear(); + } + + //输入到ts文件 + track_info.stamp.revise(frame->dts(),frame->pts(),dts_out,pts_out); + _timestamp = dts_out; + mpeg_ts_write(_context, track_info.track_id, frame->keyFrame() ? 0x0001 : 0, pts_out * 90LL, dts_out * 90LL, merged_frame->data(), merged_frame->size()); } break; default: { diff --git a/src/MediaFile/TsMuxer.h b/src/MediaFile/TsMuxer.h index f639bf6a..14a65f6c 100644 --- a/src/MediaFile/TsMuxer.h +++ b/src/MediaFile/TsMuxer.h @@ -60,7 +60,7 @@ private: Stamp stamp; }; unordered_map _codec_to_trackid; - List _frameCached; + string _config_frame_cache; }; }//namespace mediakit From 7c7b9e560e343d3e8df3b8c700beeab857dce5e9 Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Thu, 8 Aug 2019 19:01:45 +0800 Subject: [PATCH 29/30] =?UTF-8?q?=E7=BB=9F=E4=B8=80=E6=B7=BB=E5=8A=A0bom?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 3rdpart/ZLToolKit | 2 +- Android/app/src/main/cpp/native-lib.cpp | 2 +- server/FFmpegSource.cpp | 2 +- server/FFmpegSource.h | 2 +- server/Process.cpp | 2 +- server/Process.h | 2 +- server/System.cpp | 2 +- server/System.h | 2 +- server/WebApi.h | 2 +- server/WebHook.cpp | 2 +- server/WebHook.h | 2 +- src/Common/Parser.cpp | 2 +- src/Common/Parser.h | 2 +- src/Extension/H264.h | 2 +- src/Http/HttpClient.cpp | 2 +- src/Http/HttpCookieManager.cpp | 2 +- src/Http/HttpCookieManager.h | 2 +- src/MediaFile/HlsMaker.cpp | 2 +- src/MediaFile/HlsMaker.h | 2 +- src/MediaFile/HlsMakerImp.cpp | 2 +- src/MediaFile/HlsMakerImp.h | 2 +- src/MediaFile/HlsRecorder.h | 2 +- src/MediaFile/MP4Muxer.cpp | 2 +- src/MediaFile/MP4Muxer.h | 2 +- src/MediaFile/Stamp.cpp | 2 +- src/MediaFile/Stamp.h | 2 +- src/MediaFile/TsMuxer.cpp | 2 +- src/MediaFile/TsMuxer.h | 2 +- src/Pusher/MediaPusher.cpp | 2 +- src/Pusher/MediaPusher.h | 2 +- src/Pusher/PusherBase.cpp | 2 +- src/Pusher/PusherBase.h | 2 +- src/Rtsp/RtspPusher.cpp | 2 +- src/Rtsp/RtspPusher.h | 2 +- src/Rtsp/RtspSession.cpp | 2 +- src/Rtsp/RtspSession.h | 2 +- tests/test_httpClient.cpp | 2 +- 37 files changed, 37 insertions(+), 37 deletions(-) diff --git a/3rdpart/ZLToolKit b/3rdpart/ZLToolKit index 3bc5bcf9..2bb23400 160000 --- a/3rdpart/ZLToolKit +++ b/3rdpart/ZLToolKit @@ -1 +1 @@ -Subproject commit 3bc5bcf917a6ff9fe0c50ed1751e61c04aacc413 +Subproject commit 2bb234006c852b1d1a61a0e9a7f39dde7105fe34 diff --git a/Android/app/src/main/cpp/native-lib.cpp b/Android/app/src/main/cpp/native-lib.cpp index 79538cfd..91faeb28 100644 --- a/Android/app/src/main/cpp/native-lib.cpp +++ b/Android/app/src/main/cpp/native-lib.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include "test_server.cpp" diff --git a/server/FFmpegSource.cpp b/server/FFmpegSource.cpp index c05c8dc5..90805cd5 100644 --- a/server/FFmpegSource.cpp +++ b/server/FFmpegSource.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/server/FFmpegSource.h b/server/FFmpegSource.h index 9607bc18..6be92fc3 100644 --- a/server/FFmpegSource.h +++ b/server/FFmpegSource.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/server/Process.cpp b/server/Process.cpp index bde961b8..984657a7 100644 --- a/server/Process.cpp +++ b/server/Process.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/server/Process.h b/server/Process.h index c86ef678..1276cf28 100644 --- a/server/Process.h +++ b/server/Process.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/server/System.cpp b/server/System.cpp index c74c3699..0a0e3dde 100644 --- a/server/System.cpp +++ b/server/System.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/server/System.h b/server/System.h index 84cd46a3..c8857a73 100644 --- a/server/System.h +++ b/server/System.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/server/WebApi.h b/server/WebApi.h index e758abed..c3ffecf1 100644 --- a/server/WebApi.h +++ b/server/WebApi.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/server/WebHook.cpp b/server/WebHook.cpp index 5e413193..dffaf735 100644 --- a/server/WebHook.cpp +++ b/server/WebHook.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/server/WebHook.h b/server/WebHook.h index ce3b49bc..14af5974 100644 --- a/server/WebHook.h +++ b/server/WebHook.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/Common/Parser.cpp b/src/Common/Parser.cpp index 58bb8ffd..e24fa630 100644 --- a/src/Common/Parser.cpp +++ b/src/Common/Parser.cpp @@ -1,4 +1,4 @@ -// +// // Created by xzl on 2019/6/28. // diff --git a/src/Common/Parser.h b/src/Common/Parser.h index bfe2ceed..bf9854a7 100644 --- a/src/Common/Parser.h +++ b/src/Common/Parser.h @@ -1,4 +1,4 @@ -// +// // Created by xzl on 2019/6/28. // diff --git a/src/Extension/H264.h b/src/Extension/H264.h index bfe77861..df14031d 100644 --- a/src/Extension/H264.h +++ b/src/Extension/H264.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/Http/HttpClient.cpp b/src/Http/HttpClient.cpp index 3f98c60c..d9eafee0 100644 --- a/src/Http/HttpClient.cpp +++ b/src/Http/HttpClient.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/Http/HttpCookieManager.cpp b/src/Http/HttpCookieManager.cpp index 46fbad6a..8bd5da1b 100644 --- a/src/Http/HttpCookieManager.cpp +++ b/src/Http/HttpCookieManager.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/Http/HttpCookieManager.h b/src/Http/HttpCookieManager.h index 0bf18c98..172f4b08 100644 --- a/src/Http/HttpCookieManager.h +++ b/src/Http/HttpCookieManager.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/MediaFile/HlsMaker.cpp b/src/MediaFile/HlsMaker.cpp index b3ea0cea..5e88b31a 100644 --- a/src/MediaFile/HlsMaker.cpp +++ b/src/MediaFile/HlsMaker.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/MediaFile/HlsMaker.h b/src/MediaFile/HlsMaker.h index 69dc3c6f..37f6d671 100644 --- a/src/MediaFile/HlsMaker.h +++ b/src/MediaFile/HlsMaker.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/MediaFile/HlsMakerImp.cpp b/src/MediaFile/HlsMakerImp.cpp index f1f3e80f..ece25b73 100644 --- a/src/MediaFile/HlsMakerImp.cpp +++ b/src/MediaFile/HlsMakerImp.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/MediaFile/HlsMakerImp.h b/src/MediaFile/HlsMakerImp.h index 447aa126..d04de216 100644 --- a/src/MediaFile/HlsMakerImp.h +++ b/src/MediaFile/HlsMakerImp.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/MediaFile/HlsRecorder.h b/src/MediaFile/HlsRecorder.h index 1684f28c..7b876ae0 100644 --- a/src/MediaFile/HlsRecorder.h +++ b/src/MediaFile/HlsRecorder.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/MediaFile/MP4Muxer.cpp b/src/MediaFile/MP4Muxer.cpp index 3f575e83..92b0135c 100644 --- a/src/MediaFile/MP4Muxer.cpp +++ b/src/MediaFile/MP4Muxer.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/MediaFile/MP4Muxer.h b/src/MediaFile/MP4Muxer.h index a1191b79..de15d4cc 100644 --- a/src/MediaFile/MP4Muxer.h +++ b/src/MediaFile/MP4Muxer.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/MediaFile/Stamp.cpp b/src/MediaFile/Stamp.cpp index 544559c5..d4b67df9 100644 --- a/src/MediaFile/Stamp.cpp +++ b/src/MediaFile/Stamp.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/MediaFile/Stamp.h b/src/MediaFile/Stamp.h index a99269a8..e6b2d3b2 100644 --- a/src/MediaFile/Stamp.h +++ b/src/MediaFile/Stamp.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/MediaFile/TsMuxer.cpp b/src/MediaFile/TsMuxer.cpp index cc685a73..6bd4840e 100644 --- a/src/MediaFile/TsMuxer.cpp +++ b/src/MediaFile/TsMuxer.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/MediaFile/TsMuxer.h b/src/MediaFile/TsMuxer.h index 14a65f6c..476a56ae 100644 --- a/src/MediaFile/TsMuxer.h +++ b/src/MediaFile/TsMuxer.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/Pusher/MediaPusher.cpp b/src/Pusher/MediaPusher.cpp index d46f9579..78475fb1 100644 --- a/src/Pusher/MediaPusher.cpp +++ b/src/Pusher/MediaPusher.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/Pusher/MediaPusher.h b/src/Pusher/MediaPusher.h index c4b8b957..aba11f64 100644 --- a/src/Pusher/MediaPusher.h +++ b/src/Pusher/MediaPusher.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/Pusher/PusherBase.cpp b/src/Pusher/PusherBase.cpp index a8f47d92..7637e389 100644 --- a/src/Pusher/PusherBase.cpp +++ b/src/Pusher/PusherBase.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/Pusher/PusherBase.h b/src/Pusher/PusherBase.h index cf9b1d8d..6fc86e5b 100644 --- a/src/Pusher/PusherBase.h +++ b/src/Pusher/PusherBase.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/Rtsp/RtspPusher.cpp b/src/Rtsp/RtspPusher.cpp index bb5f9431..d468ddc8 100644 --- a/src/Rtsp/RtspPusher.cpp +++ b/src/Rtsp/RtspPusher.cpp @@ -1,4 +1,4 @@ -// +// // Created by xzl on 2019/3/27. // diff --git a/src/Rtsp/RtspPusher.h b/src/Rtsp/RtspPusher.h index b01af46f..aa8232bd 100644 --- a/src/Rtsp/RtspPusher.h +++ b/src/Rtsp/RtspPusher.h @@ -1,4 +1,4 @@ -// +// // Created by xzl on 2019/3/27. // diff --git a/src/Rtsp/RtspSession.cpp b/src/Rtsp/RtspSession.cpp index d3677ca5..a7449920 100644 --- a/src/Rtsp/RtspSession.cpp +++ b/src/Rtsp/RtspSession.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/src/Rtsp/RtspSession.h b/src/Rtsp/RtspSession.h index 35019881..51561c6c 100644 --- a/src/Rtsp/RtspSession.h +++ b/src/Rtsp/RtspSession.h @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> diff --git a/tests/test_httpClient.cpp b/tests/test_httpClient.cpp index 4b6f12d2..7aaf167d 100644 --- a/tests/test_httpClient.cpp +++ b/tests/test_httpClient.cpp @@ -1,4 +1,4 @@ -/* +/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> From 8e17300a17001047327263bb80b7d72d0ae88d0f Mon Sep 17 00:00:00 2001 From: xiongziliang <771730766@qq.com> Date: Mon, 12 Aug 2019 18:14:51 +0800 Subject: [PATCH 30/30] =?UTF-8?q?=E5=88=9D=E6=AD=A5=E6=94=AF=E6=8C=81webso?= =?UTF-8?q?cket-flv=E7=9B=B4=E6=92=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Http/HttpSession.cpp | 44 ++++++++++++++++++++++++++++++---------- src/Http/HttpSession.h | 9 +++++++- 2 files changed, 41 insertions(+), 12 deletions(-) diff --git a/src/Http/HttpSession.cpp b/src/Http/HttpSession.cpp index a32e0506..367790c5 100644 --- a/src/Http/HttpSession.cpp +++ b/src/Http/HttpSession.cpp @@ -212,11 +212,12 @@ inline bool HttpSession::checkWebSocket(){ headerOut["Sec-WebSocket-Protocol"] = _parser["Sec-WebSocket-Protocol"]; } sendResponse("101 Switching Protocols",headerOut,""); + checkLiveFlvStream(true); return true; } //http-flv 链接格式:http://vhost-url:port/app/streamid.flv?key1=value1&key2=value2 //如果url(除去?以及后面的参数)后缀是.flv,那么表明该url是一个http-flv直播。 -inline bool HttpSession::checkLiveFlvStream(){ +inline bool HttpSession::checkLiveFlvStream(bool over_websocket){ auto pos = strrchr(_parser.Url().data(),'.'); if(!pos){ //未找到".flv"后缀 @@ -239,7 +240,7 @@ inline bool HttpSession::checkLiveFlvStream(){ bool bClose = (strcasecmp(_parser["Connection"].data(),"close") == 0) || ( ++_iReqCnt > reqCnt); weak_ptr weakSelf = dynamic_pointer_cast(shared_from_this()); - MediaSource::findAsync(_mediaInfo,weakSelf.lock(), true,[weakSelf,bClose,this](const MediaSource::Ptr &src){ + MediaSource::findAsync(_mediaInfo,weakSelf.lock(), true,[weakSelf,bClose,this,over_websocket](const MediaSource::Ptr &src){ auto strongSelf = weakSelf.lock(); if(!strongSelf){ //本对象已经销毁 @@ -248,29 +249,35 @@ inline bool HttpSession::checkLiveFlvStream(){ auto rtmp_src = dynamic_pointer_cast(src); if(!rtmp_src){ //未找到该流 - sendNotFound(bClose); + if(!over_websocket){ + sendNotFound(bClose); + } if(bClose){ shutdown(SockException(Err_shutdown,"flv stream not found")); } return; } //找到流了 - auto onRes = [this,rtmp_src](const string &err){ + auto onRes = [this,rtmp_src,over_websocket](const string &err){ bool authSuccess = err.empty(); if(!authSuccess){ - sendResponse("401 Unauthorized", makeHttpHeader(true,err.size()),err); + if(!over_websocket){ + sendResponse("401 Unauthorized", makeHttpHeader(true,err.size()),err); + } shutdown(SockException(Err_shutdown,StrPrinter << "401 Unauthorized:" << err)); return ; } - //找到rtmp源,发送http头,负载后续发送 - sendResponse("200 OK", makeHttpHeader(false,0,get_mime_type(".flv")), ""); + if(!over_websocket) { + //找到rtmp源,发送http头,负载后续发送 + sendResponse("200 OK", makeHttpHeader(false, 0, get_mime_type(".flv")), ""); + } //开始发送rtmp负载 //关闭tcp_nodelay ,优化性能 SockUtil::setNoDelay(_sock->rawFD(),false); (*this) << SocketFlags(kSockFlags); - + _flv_over_websocket = over_websocket; try{ start(getPoller(),rtmp_src); }catch (std::exception &ex){ @@ -473,7 +480,7 @@ inline void HttpSession::Handle_Req_GET(int64_t &content_len) { } //再看看是否为http-flv直播请求 - if(checkLiveFlvStream()){ + if(checkLiveFlvStream(false)){ return; } @@ -936,8 +943,23 @@ inline void HttpSession::sendNotFound(bool bClose) { void HttpSession::onWrite(const Buffer::Ptr &buffer) { _ticker.resetTime(); - _ui64TotalBytes += buffer->size(); - send(buffer); + if(!_flv_over_websocket){ + _ui64TotalBytes += buffer->size(); + send(buffer); + return; + } + + WebSocketHeader header; + header._fin = true; + header._reserved = 0; + header._opcode = WebSocketHeader::BINARY; + header._mask_flag = false; + WebSocketSplitter::encode(header,(uint8_t *)buffer->data(),buffer->size()); +} + +void HttpSession::onWebSocketEncodeData(const uint8_t *ptr,uint64_t len){ + _ui64TotalBytes += len; + SocketHelper::send((char *)ptr,len); } void HttpSession::onDetach() { diff --git a/src/Http/HttpSession.h b/src/Http/HttpSession.h index 9cd4bfbe..e1df8b1c 100644 --- a/src/Http/HttpSession.h +++ b/src/Http/HttpSession.h @@ -102,10 +102,16 @@ protected: WebSocketSplitter::decode((uint8_t *)data,len); } + /** + * 发送数据进行websocket协议打包后回调 + * @param ptr + * @param len + */ + void onWebSocketEncodeData(const uint8_t *ptr,uint64_t len) override; private: inline void Handle_Req_GET(int64_t &content_len); inline void Handle_Req_POST(int64_t &content_len); - inline bool checkLiveFlvStream(); + inline bool checkLiveFlvStream(bool over_websocket = false); inline bool checkWebSocket(); inline bool emitHttpEvent(bool doInvoke); inline void urlDecode(Parser &parser); @@ -148,6 +154,7 @@ private: MediaInfo _mediaInfo; //处理content数据的callback function _contentCallBack; + bool _flv_over_websocket = false; };