diff options
Diffstat (limited to 'tinyDAV/src/video/tdav_session_video.c')
-rwxr-xr-x | tinyDAV/src/video/tdav_session_video.c | 1234 |
1 files changed, 676 insertions, 558 deletions
diff --git a/tinyDAV/src/video/tdav_session_video.c b/tinyDAV/src/video/tdav_session_video.c index 4ee6812..f773ede 100755 --- a/tinyDAV/src/video/tdav_session_video.c +++ b/tinyDAV/src/video/tdav_session_video.c @@ -1,6 +1,6 @@ /* - * Copyright (C) 2010-2014 Mamadou DIOP. - * Copyright (C) 2011-2014 Doubango Telecom. + * Copyright (C) 2010-2016 Mamadou DIOP. + * Copyright (C) 2011-2016 Doubango Telecom. * * * This file is part of Open Source Doubango Framework. @@ -62,25 +62,12 @@ # define TDAV_SESSION_VIDEO_AVPF_FIR_REQUEST_INTERVAL_MIN 1500 // millis #endif -#define TDAV_SESSION_VIDEO_PKT_LOSS_PROB_BAD 2 -#define TDAV_SESSION_VIDEO_PKT_LOSS_PROB_GOOD 6 -#define TDAV_SESSION_VIDEO_PKT_LOSS_FACT_MIN 0 -#define TDAV_SESSION_VIDEO_PKT_LOSS_FACT_MAX 8 -#define TDAV_SESSION_VIDEO_PKT_LOSS_LOW 9 -#define TDAV_SESSION_VIDEO_PKT_LOSS_MEDIUM 22 -#define TDAV_SESSION_VIDEO_PKT_LOSS_HIGH 63 - -#if !defined(TDAV_SESSION_VIDEO_PKT_LOSS_NO_REPORT_BEFORE_INCREASING_BW) -# define TDAV_SESSION_VIDEO_PKT_LOSS_NO_REPORT_BEFORE_INCREASING_BW 5000 // millis -#endif +// Interval to compute average quality metrics +#define TDAV_SESSION_VIDEO_QOS_COMPUTE_INTERVAL 3000 // The maximum number of pakcet loss allowed #define TDAV_SESSION_VIDEO_PKT_LOSS_MAX_COUNT_TO_REQUEST_FIR 50 -#if !defined (TDAV_GOOG_REMB_FULL_SUPPORT) -# define TDAV_GOOG_REMB_FULL_SUPPORT 0 -#endif - static const tmedia_codec_action_t __action_encode_idr = tmedia_codec_action_encode_idr; static const tmedia_codec_action_t __action_encode_bw_up = tmedia_codec_action_bw_up; static const tmedia_codec_action_t __action_encode_bw_down = tmedia_codec_action_bw_down; @@ -150,6 +137,9 @@ static int _tdav_session_video_jb_cb(const tdav_video_jb_cb_data_xt* data); static int _tdav_session_video_open_decoder(tdav_session_video_t* self, uint8_t payload_type); static int _tdav_session_video_decode(tdav_session_video_t* self, const trtp_rtp_packet_t* packet); static int _tdav_session_video_set_callbacks(tmedia_session_t* self); +static int _tdav_session_video_timer_cb(const void* arg, tsk_timer_id_t timer_id); +static int _tdav_session_video_get_bw_usage_est(tdav_session_video_t* self, uint64_t* bw_kbps, tsk_bool_t in, tsk_bool_t reset); +static int _tdav_session_video_report_bw_usage_and_jcng(tdav_session_video_t* self); // Codec callback (From codec to the network) // or Producer callback to sendRaw() data "as is" @@ -161,22 +151,22 @@ static int tdav_session_video_raw_cb(const tmedia_video_encode_result_xt* result trtp_rtp_packet_t* packet = tsk_null; int ret = 0; tsk_size_t s; - - if(base->rtp_manager && base->rtp_manager->is_started){ - if(rtp_header){ + + if(base->rtp_manager && base->rtp_manager->is_started) { + if(rtp_header) { // uses negotiated SSRC (SDP) rtp_header->ssrc = base->rtp_manager->rtp.ssrc.local; // uses negotiated payload type - if(base->pt_map.local != base->rtp_manager->rtp.payload_type || base->pt_map.remote != rtp_header->payload_type || base->pt_map.neg == -1){ - if(rtp_header->codec_id == tmedia_codec_id_none){ + if(base->pt_map.local != base->rtp_manager->rtp.payload_type || base->pt_map.remote != rtp_header->payload_type || base->pt_map.neg == -1) { + if(rtp_header->codec_id == tmedia_codec_id_none) { TSK_DEBUG_WARN("Internal codec id is equal to none"); } - else{ + else { const tsk_list_item_t* item; tsk_bool_t found = tsk_false; tsk_list_lock(TMEDIA_SESSION(base)->neg_codecs); - tsk_list_foreach(item, TMEDIA_SESSION(base)->neg_codecs){ - if((item->data) && ((const tmedia_codec_t*)item->data)->id == rtp_header->codec_id){ + tsk_list_foreach(item, TMEDIA_SESSION(base)->neg_codecs) { + if((item->data) && ((const tmedia_codec_t*)item->data)->id == rtp_header->codec_id) { base->pt_map.local = base->rtp_manager->rtp.payload_type; base->pt_map.remote = rtp_header->payload_type; base->pt_map.neg = atoi(((const tmedia_codec_t*)item->data)->neg_format); @@ -185,10 +175,10 @@ static int tdav_session_video_raw_cb(const tmedia_video_encode_result_xt* result } } tsk_list_unlock(TMEDIA_SESSION(base)->neg_codecs); - if(found){ + if(found) { TSK_DEBUG_INFO("Codec PT mapping: local=%d, remote=%d, neg=%d", base->pt_map.local, base->pt_map.remote, base->pt_map.neg); } - else{ + else { TSK_DEBUG_ERROR("Failed to map codec PT: local=%d, remote=%d", base->rtp_manager->rtp.payload_type, rtp_header->payload_type); } } @@ -196,12 +186,12 @@ static int tdav_session_video_raw_cb(const tmedia_video_encode_result_xt* result rtp_header->payload_type = base->pt_map.neg; } packet = rtp_header - ? trtp_rtp_packet_create_2(rtp_header) - : trtp_rtp_packet_create(base->rtp_manager->rtp.ssrc.local, base->rtp_manager->rtp.seq_num, base->rtp_manager->rtp.timestamp, base->rtp_manager->rtp.payload_type, result->last_chunck); - - if(packet ){ + ? trtp_rtp_packet_create_2(rtp_header) + : trtp_rtp_packet_create(base->rtp_manager->rtp.ssrc.local, base->rtp_manager->rtp.seq_num, base->rtp_manager->rtp.timestamp, base->rtp_manager->rtp.payload_type, result->last_chunck); + + if(packet ) { tsk_size_t rtp_hdr_size; - if(result->last_chunck){ + if(result->last_chunck) { #if 1 #if 1 /* http://www.cs.columbia.edu/~hgs/rtp/faq.html#timestamp-computed @@ -210,14 +200,14 @@ static int tdav_session_video_raw_cb(const tmedia_video_encode_result_xt* result If a frame is transmitted as several RTP packets, these packets would all bear the same timestamp. If the frame number cannot be determined or if frames are sampled aperiodically, as is typically the case for software codecs, the timestamp has to be computed from the system clock (e.g., gettimeofday()) */ - - if(!video->encoder.last_frame_time){ + + if(!video->encoder.last_frame_time) { // For the first frame it's not possible to compute the duration as there is no previous one. // In this case, we trust the duration from the result (computed based on the codec fps and rate). video->encoder.last_frame_time = tsk_time_now(); base->rtp_manager->rtp.timestamp += result->duration; } - else{ + else { uint64_t now = tsk_time_now(); uint32_t duration = (uint32_t)(now - video->encoder.last_frame_time); base->rtp_manager->rtp.timestamp += (duration * 90/* 90KHz */); @@ -229,9 +219,9 @@ static int tdav_session_video_raw_cb(const tmedia_video_encode_result_xt* result #else base->rtp_manager->rtp.timestamp += result->duration; #endif - + } - + packet->payload.data_const = result->buffer.ptr; packet->payload.size = result->buffer.size; s = trtp_manager_send_rtp_packet(base->rtp_manager, packet, tsk_false); // encrypt and send data @@ -240,14 +230,14 @@ static int tdav_session_video_raw_cb(const tmedia_video_encode_result_xt* result // without audio session iOS "audio" background mode is useless and UDP sockets will be closed: e.g. GE's video-only sessions #if TDAV_UNDER_IPHONE if (tnet_geterrno() == TNET_ERROR_BROKENPIPE) { - TSK_DEBUG_INFO("iOS UDP pipe is broken (restoration is progress): failed to send packet with seqnum=%u. %u expected but only %u sent", (unsigned)packet->header->seq_num, (unsigned)packet->payload.size, (unsigned)s); + TSK_DEBUG_INFO("iOS UDP pipe is broken (restoration in progress): failed to send packet with seqnum=%u. %u expected but only %u sent", (unsigned)packet->header->seq_num, (unsigned)packet->payload.size, (unsigned)s); } #endif /* TDAV_UNDER_IPHONE */ TSK_DEBUG_ERROR("Failed to send packet with seqnum=%u. %u expected but only %u sent", (unsigned)packet->header->seq_num, (unsigned)packet->payload.size, (unsigned)s); // save data expected to be sent in order to honor RTCP-NACK requests s = base->rtp_manager->rtp.serial_buffer.index; } - + rtp_hdr_size = TRTP_RTP_HEADER_MIN_SIZE + (packet->header->csrc_count << 2); // Save packet if (base->avpf_mode_neg && (s > TRTP_RTP_HEADER_MIN_SIZE)) { @@ -256,19 +246,19 @@ static int tdav_session_video_raw_cb(const tmedia_video_encode_result_xt* result // Hack the RTP packet payload to point to the the SRTP data instead of unencrypted ptr packet_avpf->payload.size = (s - rtp_hdr_size); packet_avpf->payload.data_const = tsk_null; - if(!(packet_avpf->payload.data = tsk_malloc(packet_avpf->payload.size))){// FIXME: to be optimized (reuse memory address) + if(!(packet_avpf->payload.data = tsk_malloc(packet_avpf->payload.size))) { // FIXME: to be optimized (reuse memory address) TSK_DEBUG_ERROR("failed to allocate buffer"); goto bail; } memcpy(packet_avpf->payload.data, (((const uint8_t*)base->rtp_manager->rtp.serial_buffer.ptr) + rtp_hdr_size), packet_avpf->payload.size); tsk_list_lock(video->avpf.packets); - if(video->avpf.count > video->avpf.max){ + if(video->avpf.count > video->avpf.max) { tsk_list_remove_first_item(video->avpf.packets); } - else{ + else { ++video->avpf.count; } - + // The packet must not added 'ascending' but 'back' because the sequence number coult wrap // For example: // - send(65533, 65534, 65535, 0, 1) @@ -278,19 +268,19 @@ static int tdav_session_video_raw_cb(const tmedia_video_encode_result_xt* result tsk_list_push_back_data(video->avpf.packets, (void**)&packet_avpf); tsk_list_unlock(video->avpf.packets); } - + // Send FEC packet // FIXME: protect only Intra and Params packets - if(base->ulpfec.codec && (s > TRTP_RTP_HEADER_MIN_SIZE)){ + if(base->ulpfec.codec && (s > TRTP_RTP_HEADER_MIN_SIZE)) { packet->payload.data_const = (((const uint8_t*)base->rtp_manager->rtp.serial_buffer.ptr) + rtp_hdr_size); packet->payload.size = (s - rtp_hdr_size); ret = tdav_codec_ulpfec_enc_protect((struct tdav_codec_ulpfec_s*)base->ulpfec.codec, packet); - if(result->last_chunck){ + if(result->last_chunck) { trtp_rtp_packet_t* packet_fec; - if((packet_fec = trtp_rtp_packet_create(base->rtp_manager->rtp.ssrc.local, base->ulpfec.seq_num++, base->ulpfec.timestamp, base->ulpfec.payload_type, tsk_true))){ + if((packet_fec = trtp_rtp_packet_create(base->rtp_manager->rtp.ssrc.local, base->ulpfec.seq_num++, base->ulpfec.timestamp, base->ulpfec.payload_type, tsk_true))) { // serialize the FEC payload packet packet s = tdav_codec_ulpfec_enc_serialize((const struct tdav_codec_ulpfec_s*)base->ulpfec.codec, &video->encoder.buffer, &video->encoder.buffer_size); - if(s > 0){ + if(s > 0) { packet_fec->payload.data_const = video->encoder.buffer; packet_fec->payload.size = s; s = trtp_manager_send_rtp_packet(base->rtp_manager, packet_fec, tsk_true/* already encrypted */); @@ -306,11 +296,11 @@ static int tdav_session_video_raw_cb(const tmedia_video_encode_result_xt* result if (ret == 0 && video->red.codec) { // don't need to lock as the buffer is never used by other codecs tsk_size_t red_pay_size = video->red.codec->plugin->encode( - video->red.codec, - buffer, size, - &video->encoder.buffer, &video->encoder.buffer_size - ); - if(red_pay_size > 1){ + video->red.codec, + buffer, size, + &video->encoder.buffer, &video->encoder.buffer_size + ); + if(red_pay_size > 1) { packet->header->payload_type = video->red.payload_type; ((uint8_t*)video->encoder.buffer)[0] = packet->header->payload_type; packet->payload.data_const = video->encoder.buffer; @@ -324,10 +314,10 @@ static int tdav_session_video_raw_cb(const tmedia_video_encode_result_xt* result TSK_DEBUG_ERROR("Failed to create packet"); } } - else{ + else { //--TSK_DEBUG_WARN("Session not ready yet"); } - + bail: TSK_OBJECT_SAFE_FREE(packet); return ret; @@ -338,26 +328,25 @@ static int tdav_session_video_decode_cb(const tmedia_video_decode_result_xt* res { tdav_session_av_t* base = (tdav_session_av_t*)result->usr_data; tdav_session_video_t* video = (tdav_session_video_t*)base; - - switch(result->type){ - case tmedia_video_decode_result_type_idr: - { - if(video->decoder.last_corrupted_timestamp != ((const trtp_rtp_header_t*)result->proto_hdr)->timestamp){ - TSK_DEBUG_INFO("IDR frame decoded"); - video->decoder.stream_corrupted = tsk_false; - } - else{ - TSK_DEBUG_INFO("IDR frame decoded but corrupted :("); - } - break; + + switch(result->type) { + case tmedia_video_decode_result_type_idr: { + if(video->decoder.last_corrupted_timestamp != ((const trtp_rtp_header_t*)result->proto_hdr)->timestamp) { + TSK_DEBUG_INFO("IDR frame decoded"); + video->decoder.stream_corrupted = tsk_false; } - case tmedia_video_decode_result_type_error: - { - TSK_DEBUG_INFO("Decoding failed -> request Full Intra Refresh (FIR)"); - _tdav_session_video_local_request_idr(TMEDIA_SESSION(video), "DECODED_FAILED", ((const trtp_rtp_header_t*)result->proto_hdr)->ssrc); - break; + else { + TSK_DEBUG_INFO("IDR frame decoded but corrupted :("); } - default: break; + break; + } + case tmedia_video_decode_result_type_error: { + TSK_DEBUG_INFO("Decoding failed -> request Full Intra Refresh (FIR)"); + _tdav_session_video_local_request_idr(TMEDIA_SESSION(video), "DECODED_FAILED", ((const trtp_rtp_header_t*)result->proto_hdr)->ssrc); + break; + } + default: + break; } return 0; } @@ -367,26 +356,27 @@ static int tdav_session_video_producer_enc_cb(const void* callback_data, const v { tdav_session_video_t* video = (tdav_session_video_t*)callback_data; tdav_session_av_t* base = (tdav_session_av_t*)callback_data; + tmedia_session_t* session = (tmedia_session_t*)callback_data; tsk_size_t yuv420p_size = 0; int ret = 0; - - if(!base){ + + if(!base) { TSK_DEBUG_ERROR("Null session"); return 0; } - + // do nothing if session is held // when the session is held the end user will get feedback he also has possibilities to put the consumer and producer on pause - if (TMEDIA_SESSION(base)->lo_held) { + if (session->lo_held) { return 0; } - + // do nothing if not started yet if (!video->started) { TSK_DEBUG_INFO("Video session not started yet"); return 0; } - + // get best negotiated codec if not already done // the encoder codec could be null when session is renegotiated without re-starting (e.g. hold/resume) if (!video->encoder.codec) { @@ -400,25 +390,28 @@ static int tdav_session_video_producer_enc_cb(const void* callback_data, const v video->encoder.codec = tsk_object_ref(TSK_OBJECT(codec)); tsk_safeobj_unlock(base); } - + if (base->rtp_manager) { //static int __rotation_counter = 0; /* encode */ tsk_size_t out_size = 0; tmedia_codec_t* codec_encoder = tsk_null; - + uint64_t encode_start_time, encode_duration; // This time chroma conversion, scaling and encoding + if (!base->rtp_manager->is_started) { TSK_DEBUG_ERROR("Not started"); goto bail; } - + // take a reference to the encoder to make sure it'll not be destroyed while we're using it codec_encoder = tsk_object_ref(video->encoder.codec); if (!codec_encoder) { TSK_DEBUG_ERROR("The encoder is null"); goto bail; } - + + encode_start_time = tsk_time_now(); + #define PRODUCER_OUTPUT_FIXSIZE (base->producer->video.chroma != tmedia_chroma_mjpeg) // whether the output data has a fixed size/length #define PRODUCER_OUTPUT_RAW (base->producer->encoder.codec_id == tmedia_codec_id_none) // Otherwise, frames from the producer are already encoded #define PRODUCER_SIZE_CHANGED ((video->conv.producerWidth && video->conv.producerWidth != base->producer->video.width) || (video->conv.producerHeight && video->conv.producerHeight != base->producer->video.height) \ @@ -431,15 +424,15 @@ static int tdav_session_video_producer_enc_cb(const void* callback_data, const v // Video codecs only accept YUV420P buffers ==> do conversion if needed or producer doesn't have the right size if (PRODUCER_OUTPUT_RAW && (PRODUCED_FRAME_NEED_CHROMA_CONVERSION || PRODUCER_SIZE_CHANGED || ENCODED_NEED_FLIP || ENCODED_NEED_RESIZE ||PRODUCED_FRAME_NEED_ROTATION || PRODUCED_FRAME_NEED_MIRROR)) { // Create video converter if not already done or producer size have changed - if(!video->conv.toYUV420 || PRODUCER_SIZE_CHANGED){ + if(!video->conv.toYUV420 || PRODUCER_SIZE_CHANGED) { TSK_OBJECT_SAFE_FREE(video->conv.toYUV420); video->conv.producerWidth = base->producer->video.width; video->conv.producerHeight = base->producer->video.height; video->conv.xProducerSize = size; - + TSK_DEBUG_INFO("producer size = (%d, %d)", (int)base->producer->video.width, (int)base->producer->video.height); if (!(video->conv.toYUV420 = tmedia_converter_video_create(base->producer->video.width, base->producer->video.height, base->producer->video.chroma, TMEDIA_CODEC_VIDEO(codec_encoder)->out.width, TMEDIA_CODEC_VIDEO(codec_encoder)->out.height, - TMEDIA_CODEC_VIDEO(codec_encoder)->out.chroma))){ + TMEDIA_CODEC_VIDEO(codec_encoder)->out.chroma))) { TSK_DEBUG_ERROR("Failed to create video converter"); ret = -5; goto bail; @@ -448,19 +441,19 @@ static int tdav_session_video_producer_enc_cb(const void* callback_data, const v tmedia_converter_video_set_scale_rotated_frames(video->conv.toYUV420, video->encoder.scale_rotated_frames); } } - - if(video->conv.toYUV420){ + + if(video->conv.toYUV420) { video->encoder.scale_rotated_frames = video->conv.toYUV420->scale_rotated_frames; // check if rotation have changed and alert the codec // we avoid scalling the frame after rotation because it's CPU intensive and keeping the image ratio is difficult // it's up to the encoder to swap (w,h) and to track the rotation value - if(video->encoder.rotation != base->producer->video.rotation){ + if(video->encoder.rotation != base->producer->video.rotation) { tmedia_param_t* param = tmedia_param_create(tmedia_pat_set, - tmedia_video, - tmedia_ppt_codec, - tmedia_pvt_int32, - "rotation", - (void*)&base->producer->video.rotation); + tmedia_video, + tmedia_ppt_codec, + tmedia_pvt_int32, + "rotation", + (void*)&base->producer->video.rotation); if (!param) { TSK_DEBUG_ERROR("Failed to create a media parameter"); return -1; @@ -471,10 +464,10 @@ static int tdav_session_video_producer_enc_cb(const void* callback_data, const v // (ret != 0) -> not supported by the codec -> to be done by the converter video->encoder.scale_rotated_frames = (ret != 0); } - + // update one-shot parameters tmedia_converter_video_set(video->conv.toYUV420, base->producer->video.rotation, TMEDIA_CODEC_VIDEO(codec_encoder)->out.flip, base->producer->video.mirror, video->encoder.scale_rotated_frames); - + yuv420p_size = tmedia_converter_video_process(video->conv.toYUV420, buffer, size, &video->encoder.conv_buffer, &video->encoder.conv_buffer_size); if (!yuv420p_size || !video->encoder.conv_buffer) { TSK_DEBUG_ERROR("Failed to convert XXX buffer to YUV42P"); @@ -482,7 +475,7 @@ static int tdav_session_video_producer_enc_cb(const void* callback_data, const v goto bail; } } - + // Encode data tsk_mutex_lock(video->encoder.h_mutex); if (video->started && codec_encoder->opened) { // stop() function locks the encoder mutex before changing "started" @@ -496,19 +489,27 @@ static int tdav_session_video_producer_enc_cb(const void* callback_data, const v } } tsk_mutex_unlock(video->encoder.h_mutex); - + if (out_size) { /* Never called, see tdav_session_video_raw_cb() */ trtp_manager_send_rtp(base->rtp_manager, video->encoder.buffer, out_size, 6006, tsk_true, tsk_true); } - bail: + + // This block of code is called on success, otherwise we'd jump to bail + encode_duration = (tsk_time_now() - encode_start_time); + if (base->congestion_ctrl_enabled) { + tsk_mutex_lock(video->h_mutex_qos); + session->qos_metrics.video_enc_avg_time = (unsigned)((session->qos_metrics.video_enc_avg_time + encode_duration) / (video->enc_avg_time_n++ ? 2 : 1)); + tsk_mutex_unlock(video->h_mutex_qos); + } +bail: TSK_OBJECT_SAFE_FREE(codec_encoder); } else { TSK_DEBUG_ERROR("Invalid parameter"); ret = -1; } - + return ret; } @@ -517,40 +518,40 @@ static int tdav_session_video_rtp_cb(const void* callback_data, const trtp_rtp_p { tdav_session_video_t* video = (tdav_session_video_t*)callback_data; tdav_session_av_t* base = (tdav_session_av_t*)callback_data; - - if(!video || !packet || !packet->header){ + + if(!video || !packet || !packet->header) { TSK_DEBUG_ERROR("Invalid parameter"); return -1; } - - if(packet->header->payload_type == base->red.payload_type){ + + if(packet->header->payload_type == base->red.payload_type) { static void* __red_buffer_ptr = tsk_null; // Never used static tsk_size_t __red_buffer_size = 0; // Never used - if(!base->red.codec){ + if(!base->red.codec) { TSK_DEBUG_ERROR("No RED codec could be found"); return -2; } // Decode RED data base->red.codec->plugin->decode( - base->red.codec, - (packet->payload.data ? packet->payload.data : packet->payload.data_const), packet->payload.size, - &__red_buffer_ptr, &__red_buffer_size, - packet->header - ); + base->red.codec, + (packet->payload.data ? packet->payload.data : packet->payload.data_const), packet->payload.size, + &__red_buffer_ptr, &__red_buffer_size, + packet->header + ); return 0; } - else if(packet->header->payload_type == base->ulpfec.payload_type){ - if(!base->ulpfec.codec){ + else if(packet->header->payload_type == base->ulpfec.payload_type) { + if(!base->ulpfec.codec) { TSK_DEBUG_ERROR("No ULPFEC codec could be found"); return -2; } // FIXME: do something return 0; } - else{ + else { return video->jb - ? tdav_video_jb_put(video->jb, (trtp_rtp_packet_t*)packet) - : _tdav_session_video_decode(video, packet); + ? tdav_video_jb_put(video->jb, (trtp_rtp_packet_t*)packet) + : _tdav_session_video_decode(video, packet); } } @@ -561,200 +562,167 @@ static int tdav_session_video_rtcp_cb(const void* callback_data, const trtp_rtcp const trtp_rtcp_report_psfb_t* psfb; const trtp_rtcp_report_rtpfb_t* rtpfb; const trtp_rtcp_rblocks_L_t* blocks = tsk_null; - + tdav_session_video_t* video = (tdav_session_video_t*)callback_data; tdav_session_av_t* base = (tdav_session_av_t*)callback_data; + tmedia_session_t* session = (tmedia_session_t*)callback_data; tsk_size_t i; - + if((blocks = (packet->header->type == trtp_rtcp_packet_type_rr) ? ((const trtp_rtcp_report_rr_t*)packet)->blocks : - (packet->header->type == trtp_rtcp_packet_type_sr ? ((const trtp_rtcp_report_sr_t*)packet)->blocks : tsk_null))){ + (packet->header->type == trtp_rtcp_packet_type_sr ? ((const trtp_rtcp_report_sr_t*)packet)->blocks : tsk_null))) { const tsk_list_item_t* item; const trtp_rtcp_rblock_t* block; - tsk_list_foreach(item, blocks){ - if(!(block = item->data)) continue; - if(base->rtp_manager->rtp.ssrc.local == block->ssrc){ - tdav_session_video_pkt_loss_level_t pkt_loss_level = tdav_session_video_pkt_loss_level_low; - TSK_DEBUG_INFO("RTCP pkt loss fraction=%d", block->fraction); - if(block->fraction > TDAV_SESSION_VIDEO_PKT_LOSS_HIGH) pkt_loss_level = tdav_session_video_pkt_loss_level_high; - else if(block->fraction > TDAV_SESSION_VIDEO_PKT_LOSS_MEDIUM) pkt_loss_level = tdav_session_video_pkt_loss_level_medium; - if (pkt_loss_level == tdav_session_video_pkt_loss_level_high || (pkt_loss_level > video->encoder.pkt_loss_level)){ // high or low -> medium - video->encoder.pkt_loss_level = pkt_loss_level; - if(video->encoder.pkt_loss_prob_bad-- <= 0){ - int32_t new_pkt_loss_fact = TSK_CLAMP(TDAV_SESSION_VIDEO_PKT_LOSS_FACT_MIN, (video->encoder.pkt_loss_fact + 1), TDAV_SESSION_VIDEO_PKT_LOSS_FACT_MAX); - if (video->encoder.pkt_loss_fact != new_pkt_loss_fact) { - TSK_DEBUG_INFO("Downgrade bandwidth %d->%d", video->encoder.pkt_loss_fact, new_pkt_loss_fact); - video->encoder.pkt_loss_fact = new_pkt_loss_fact; - _tdav_session_video_bw_down(video); - } - _tdav_session_video_reset_loss_prob(video); - } - } - else{ - if (video->encoder.pkt_loss_prob_good-- <= 0) { - int32_t new_pkt_loss_fact = TSK_CLAMP(TDAV_SESSION_VIDEO_PKT_LOSS_FACT_MIN, (video->encoder.pkt_loss_fact - 1), TDAV_SESSION_VIDEO_PKT_LOSS_FACT_MAX); - if (video->encoder.pkt_loss_fact != new_pkt_loss_fact) { - TSK_DEBUG_INFO("Upgrade bandwidth %d->%d", video->encoder.pkt_loss_fact, new_pkt_loss_fact); - video->encoder.pkt_loss_fact = new_pkt_loss_fact; - _tdav_session_video_bw_up(video); - } - _tdav_session_video_reset_loss_prob(video); - } + tsk_list_foreach(item, blocks) { + if(!(block = item->data)) { + continue; + } + if(base->rtp_manager->rtp.ssrc.local == block->ssrc) { + TSK_DEBUG_INFO("RTCP pkt loss fraction=%d, congestion_ctrl_enabled=%d", block->fraction, (int)base->congestion_ctrl_enabled); + // Global packet loss estimation + if (base->congestion_ctrl_enabled) { + float q2; + q2 = block->fraction == 0 ? 1.f : ((float)block->fraction / 256.f); + tsk_mutex_lock(video->h_mutex_qos); + session->qos_metrics.q2 = (session->qos_metrics.q2 + q2) / (video->q2_n++ ? 2.f : 1.f); + tsk_mutex_unlock(video->h_mutex_qos); } break; } } } - + i = 0; - while((psfb = (const trtp_rtcp_report_psfb_t*)trtp_rtcp_packet_get_at(packet, trtp_rtcp_packet_type_psfb, i++))){ - switch(psfb->fci_type){ - case trtp_rtcp_psfb_fci_type_fir: - { - TSK_DEBUG_INFO("Receiving RTCP-FIR (%u)", ((const trtp_rtcp_report_fb_t*)psfb)->ssrc_media); + while((psfb = (const trtp_rtcp_report_psfb_t*)trtp_rtcp_packet_get_at(packet, trtp_rtcp_packet_type_psfb, i++))) { + switch(psfb->fci_type) { + case trtp_rtcp_psfb_fci_type_fir: { + TSK_DEBUG_INFO("Receiving RTCP-FIR (%u)", ((const trtp_rtcp_report_fb_t*)psfb)->ssrc_media); + _tdav_session_video_remote_requested_idr(video, ((const trtp_rtcp_report_fb_t*)psfb)->ssrc_media); + break; + } + case trtp_rtcp_psfb_fci_type_pli: { + uint64_t now; + TSK_DEBUG_INFO("Receiving RTCP-PLI (%u)", ((const trtp_rtcp_report_fb_t*)psfb)->ssrc_media); + now = tsk_time_now(); + // more than one PLI in 500ms ? + // "if" removed because PLI really means codec prediction chain is broken + /*if((now - video->avpf.last_pli_time) < 500)*/{ _tdav_session_video_remote_requested_idr(video, ((const trtp_rtcp_report_fb_t*)psfb)->ssrc_media); - break; } - case trtp_rtcp_psfb_fci_type_pli: - { - uint64_t now; - TSK_DEBUG_INFO("Receiving RTCP-PLI (%u)", ((const trtp_rtcp_report_fb_t*)psfb)->ssrc_media); - now = tsk_time_now(); - // more than one PLI in 500ms ? - // "if" removed because PLI really means codec prediction chain is broken - /*if((now - video->avpf.last_pli_time) < 500)*/{ - _tdav_session_video_remote_requested_idr(video, ((const trtp_rtcp_report_fb_t*)psfb)->ssrc_media); + video->avpf.last_pli_time = now; + break; + } + case trtp_rtcp_psfb_fci_type_afb: { + if (psfb->afb.type == trtp_rtcp_psfb_afb_type_remb) { + uint64_t bw_up_reported_kpbs = ((psfb->afb.remb.mantissa << psfb->afb.remb.exp) >> 10); + TSK_DEBUG_INFO("Receiving RTCP-AFB-REMB (%u), exp=%u, mantissa=%u, bandwidth=%ukbps", ((const trtp_rtcp_report_fb_t*)psfb)->ssrc_media, psfb->afb.remb.exp, psfb->afb.remb.mantissa, bw_up_reported_kpbs); + if (base->congestion_ctrl_enabled) { + if (session->qos_metrics.bw_up_est_kbps != 0) { + float q3 = bw_up_reported_kpbs / (float)session->qos_metrics.bw_up_est_kbps; + q3 = TSK_CLAMP(0.f, q3, 1.f); + TSK_DEBUG_INFO("bw_up_estimated_kbps=%llu, bw_up_reported_kpbs=%llu, q3=%f", session->qos_metrics.bw_up_est_kbps, bw_up_reported_kpbs, q3); + tsk_mutex_lock(video->h_mutex_qos); + session->qos_metrics.q3 = (session->qos_metrics.q3 + q3) / (video->q3_n++ ? 2.f : 1.f); + tsk_mutex_unlock(video->h_mutex_qos); + } } - video->avpf.last_pli_time = now; - break; } - case trtp_rtcp_psfb_fci_type_afb: - { - if (psfb->afb.type == trtp_rtcp_psfb_afb_type_remb) { - uint32_t bandwidth_up_reported_kpbs = ((psfb->afb.remb.mantissa << psfb->afb.remb.exp) / 1024); - TSK_DEBUG_INFO("Receiving RTCP-AFB-REMB (%u), exp=%u, mantissa=%u, bandwidth = %ukbps, congestion_ctrl_enabled=%s", ((const trtp_rtcp_report_fb_t*)psfb)->ssrc_media, psfb->afb.remb.exp, psfb->afb.remb.mantissa, bandwidth_up_reported_kpbs, base->congestion_ctrl_enabled ? "yes" : "no"); -#if TDAV_GOOG_REMB_FULL_SUPPORT - if (base->congestion_ctrl_enabled) { - uint32_t remb_upload_kbps = 0; - tsk_bool_t remb_ok = tsk_false; - uint64_t bytes_count_now; - uint64_t bytes_count_out; - static uint64_t* bytes_count_in_ptr_null = tsk_null; - - if ((ret = trtp_manager_get_bytes_count(base->rtp_manager, bytes_count_in_ptr_null, &bytes_count_out)) == 0) { - uint64_t duration; - bytes_count_now = tsk_time_now(); - duration = (bytes_count_now - base->bytes_out.count_last_time); - remb_ok = (base->bytes_out.count_last_time != 0 && duration > 0); - if (remb_ok) { - remb_upload_kbps = (int32_t)((((bytes_count_out - base->bytes_out.count) * 8 * 1000) / 1024) / duration); - TSK_DEBUG_INFO("remb_upload_kbps=%u, bandwidth_up_reported_kpbs=%u", remb_upload_kbps, bandwidth_up_reported_kpbs); - } - base->bytes_out.count_last_time = bytes_count_now; - base->bytes_out.count = bytes_count_out; - } - if (remb_ok) { - int32_t pkt_loss_percent = bandwidth_up_reported_kpbs >= remb_upload_kbps ? 0 : ((remb_upload_kbps - bandwidth_up_reported_kpbs) / remb_upload_kbps) * 100; - TSK_DEBUG_INFO("GOO-REMB: pkt_loss_percent=%d", pkt_loss_percent); - if (pkt_loss_percent > 5) { - // more than 5% pkt loss - TSK_DEBUG_WARN("pkt_loss_percent(%u) > 5%%, using lower bw(%d)", pkt_loss_percent, bandwidth_up_reported_kpbs); - _tdav_session_video_bw_kbps(video, bandwidth_up_reported_kpbs); - } - else if (pkt_loss_percent == 0) { -#if 0 - // no pkt loss --> increase bw - int32_t target_bw_max_upload_kbps = base->bandwidth_max_upload_kbps; // user-defined (guard), INT_MAX if not defined - if (video->encoder.codec) { - target_bw_max_upload_kbps = TSK_MIN( - tmedia_get_video_bandwidth_kbps_2(TMEDIA_CODEC_VIDEO(video->encoder.codec)->out.width, TMEDIA_CODEC_VIDEO(video->encoder.codec)->out.height, TMEDIA_CODEC_VIDEO(video->encoder.codec)->out.fps), - target_bw_max_upload_kbps); - } - if (target_bw_max_upload_kbps > remb_upload_kbps + ((remb_upload_kbps / 100) * 20)) { - // target (best) bw is 20% less than what we're sending --> increase by 5% - uint32_t new_upload_kbps = remb_upload_kbps + ((remb_upload_kbps / 100) * 5); - TSK_DEBUG_INFO("current upload bw is too low, increasing from %u to %u", remb_upload_kbps, new_upload_kbps); - _tdav_session_video_bw_kbps(video, new_upload_kbps); - } -#endif /* 0 */ - } - } - - } -#else - // for now we just don't respect the requested bandwidth -#endif /* TDAV_GOOG_REMB_FULL_SUPPORT */ + else if (psfb->afb.type == trtp_rtcp_psfb_afb_type_jcng) { + float jcng_q = ((float)psfb->afb.jcng.q / 255.f); + TSK_DEBUG_INFO("Receiving RTCP-AFB-JCNG (%u), q_recv=%u, q_dec=%f", ((const trtp_rtcp_report_fb_t*)psfb)->ssrc_media, psfb->afb.jcng.q, jcng_q); + if (base->congestion_ctrl_enabled) { + tsk_mutex_lock(video->h_mutex_qos); + session->qos_metrics.q5 = (session->qos_metrics.q5 + jcng_q) / (video->q5_n++ ? 2.f : 1.f); + tsk_mutex_unlock(video->h_mutex_qos); } - break; } - default: break; + break; + } + default: + break; } } i = 0; - while((rtpfb = (const trtp_rtcp_report_rtpfb_t*)trtp_rtcp_packet_get_at(packet, trtp_rtcp_packet_type_rtpfb, i++))){ - switch(rtpfb->fci_type){ - default: break; - case trtp_rtcp_rtpfb_fci_type_nack: - { - if(rtpfb->nack.blp && rtpfb->nack.pid){ - tsk_size_t i; - int32_t j; - uint16_t pid, blp; - const tsk_list_item_t* item; - const trtp_rtp_packet_t* pkt_rtp; - for(i = 0; i < rtpfb->nack.count; ++i){ - static const int32_t __Pow2[16] = { 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000 }; - int32_t blp_count; - blp = rtpfb->nack.blp[i]; - blp_count = blp ? 16 : 0; - - for(j = -1/*Packet ID (PID)*/; j < blp_count; ++j){ - if(j == -1 || (blp & __Pow2[j])){ - pid = (rtpfb->nack.pid[i] + (j + 1)); - tsk_list_lock(video->avpf.packets); - tsk_list_foreach(item, video->avpf.packets){ - if(!(pkt_rtp = item->data)){ - continue; - } - - // Very Important: the seq_nums are not consecutive because of wrapping. - // For example, '65533, 65534, 65535, 0, 1' is a valid sequences which means we have to check all packets (probaly need somthing smarter) - if(pkt_rtp->header->seq_num == pid){ - TSK_DEBUG_INFO("NACK Found, pid=%d, blp=%u", pid, blp); - trtp_manager_send_rtp_packet(base->rtp_manager, pkt_rtp, tsk_true); - break; - } - if(item == video->avpf.packets->tail){ - // should never be called unless the tail is too small - int32_t old_max = (int32_t)video->avpf.max; - int32_t len_drop = (pkt_rtp->header->seq_num - pid); - video->avpf.max = TSK_CLAMP((int32_t)tmedia_defaults_get_avpf_tail_min(), (old_max + len_drop), (int32_t)tmedia_defaults_get_avpf_tail_max()); - TSK_DEBUG_INFO("**NACK requesting dropped frames. List=[%d-%d], requested=%d, List.Max=%d, List.Count=%d. RTT is probably too high.", - ((const trtp_rtp_packet_t*)TSK_LIST_FIRST_DATA(video->avpf.packets))->header->seq_num, - ((const trtp_rtp_packet_t*)TSK_LIST_LAST_DATA(video->avpf.packets))->header->seq_num, - pid, - (int)video->avpf.max, - (int)video->avpf.count); - // FIR not really requested but needed - /*_tdav_session_video_remote_requested_idr(video, ((const trtp_rtcp_report_fb_t*)rtpfb)->ssrc_media); - tsk_list_clear_items(video->avpf.packets); - video->avpf.count = 0;*/ - } // if(last_item) - }// foreach(pkt) - tsk_list_unlock(video->avpf.packets); - }// if(BLP is set) - }// foreach(BIT in BLP) - }// foreach(nack) - }// if(nack-blp and nack-pid are set) - break; - }// case + while((rtpfb = (const trtp_rtcp_report_rtpfb_t*)trtp_rtcp_packet_get_at(packet, trtp_rtcp_packet_type_rtpfb, i++))) { + switch(rtpfb->fci_type) { + default: + break; + case trtp_rtcp_rtpfb_fci_type_nack: { + if(rtpfb->nack.blp && rtpfb->nack.pid) { + tsk_size_t i; + int32_t j; + uint16_t pid, blp; + uint32_t r = 0; // the number of recoverable packets (lost but recovered using a NACK requests) + uint32_t u = 0; // the number of unrecoverable packets (lost but not recovered using NACK requests) + const tsk_list_item_t* item; + const trtp_rtp_packet_t* pkt_rtp; + for(i = 0; i < rtpfb->nack.count; ++i) { + static const int32_t __Pow2[16] = { 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000 }; + int32_t blp_count; + blp = rtpfb->nack.blp[i]; + blp_count = blp ? 16 : 0; + + for(j = -1/*Packet ID (PID)*/; j < blp_count; ++j) { + if(j == -1 || (blp & __Pow2[j])) { + pid = (rtpfb->nack.pid[i] + (j + 1)); + tsk_list_lock(video->avpf.packets); + tsk_list_foreach(item, video->avpf.packets) { + if(!(pkt_rtp = item->data)) { + continue; + } + + // Very Important: the seq_nums are not consecutive because of wrapping. + // For example, '65533, 65534, 65535, 0, 1' is a valid sequences which means we have to check all packets (probaly need somthing smarter) + if(pkt_rtp->header->seq_num == pid) { + ++r; + TSK_DEBUG_INFO("NACK Found, pid=%d, blp=%u, r=%u", pid, blp, r); + trtp_manager_send_rtp_packet(base->rtp_manager, pkt_rtp, tsk_true); + break; + } + if(item == video->avpf.packets->tail) { + // should never be called unless the tail is too small + int32_t old_max = (int32_t)video->avpf.max; + int32_t len_drop = (pkt_rtp->header->seq_num - pid); + ++u; + video->avpf.max = TSK_CLAMP((int32_t)tmedia_defaults_get_avpf_tail_min(), (old_max + len_drop), (int32_t)tmedia_defaults_get_avpf_tail_max()); + TSK_DEBUG_INFO("**NACK requesting dropped frames. List=[%d-%d], requested=%d, List.Max=%d, List.Count=%d, u=%u. RTT is probably too high.", + ((const trtp_rtp_packet_t*)TSK_LIST_FIRST_DATA(video->avpf.packets))->header->seq_num, + ((const trtp_rtp_packet_t*)TSK_LIST_LAST_DATA(video->avpf.packets))->header->seq_num, + pid, + (int)video->avpf.max, + (int)video->avpf.count, + (unsigned)u); + // FIR not really requested but needed + /*_tdav_session_video_remote_requested_idr(video, ((const trtp_rtcp_report_fb_t*)rtpfb)->ssrc_media); + tsk_list_clear_items(video->avpf.packets); + video->avpf.count = 0;*/ + } // if(last_item) + }// foreach(pkt) + tsk_list_unlock(video->avpf.packets); + }// if(BLP is set) + }// foreach(BIT in BLP) + }// foreach(nack) + if (base->congestion_ctrl_enabled) { + // Compute q1 + if (r || u) { + float q1 = 1.f - (((r * 0.2f) + (u * 0.8f)) / (r + u)); + tsk_mutex_lock(video->h_mutex_qos); + session->qos_metrics.q1 = (session->qos_metrics.q1 + q1) / (video->q1_n++ ? 2.f : 1.f); + tsk_mutex_unlock(video->h_mutex_qos); + TSK_DEBUG_INFO("RTCP-NACK: r=%u, u=%u, q1=%f", r, u, q1); + } + } + }// if(nack-blp and nack-pid are set) + break; + }// case }// switch }// while(rtcp-pkt) - + return ret; } static int _tdav_session_video_set_defaults(tdav_session_video_t* self) { + tmedia_session_t* session = (tmedia_session_t*)self; if (!self) { TSK_DEBUG_ERROR("Invalid parameter"); return -1; @@ -762,16 +730,29 @@ static int _tdav_session_video_set_defaults(tdav_session_video_t* self) self->jb_enabled = tmedia_defaults_get_videojb_enabled(); self->zero_artifacts = tmedia_defaults_get_video_zeroartifacts_enabled(); self->avpf.max = tmedia_defaults_get_avpf_tail_min(); - self->encoder.pkt_loss_level = tdav_session_video_pkt_loss_level_low; - self->encoder.pkt_loss_prob_bad = 0; // honor first report - self->encoder.pkt_loss_prob_good = TDAV_SESSION_VIDEO_PKT_LOSS_PROB_GOOD; self->encoder.last_frame_time = 0; - + // Quality metrics + session->qos_metrics.q1 = 0.f, self->q1_n = 0; + session->qos_metrics.q2 = 0.f, self->q2_n = 0; + session->qos_metrics.q3 = 0.f, self->q3_n = 0; + session->qos_metrics.q4 = 0.f, self->q4_n = 0; + session->qos_metrics.qvag = 1.f; + session->qos_metrics.bw_up_est_kbps = 0; + session->qos_metrics.bw_down_est_kbps = 0; + session->qos_metrics.last_update_time = 0; + session->qos_metrics.video_out_width = 0; + session->qos_metrics.video_out_height = 0; + session->qos_metrics.video_in_width = 0; + session->qos_metrics.video_in_height = 0; + session->qos_metrics.video_in_avg_fps = tmedia_defaults_get_video_fps(), self->in_avg_fps_n = 1; + session->qos_metrics.video_dec_avg_time = 0, self->dec_avg_time_n = 0 ; + session->qos_metrics.video_enc_avg_time = 0, self->enc_avg_time_n = 0; + // reset rotation info (MUST for reINVITE when mobile device in portrait[90 degrees]) self->encoder.rotation = 0; - + TSK_DEBUG_INFO("Video 'zero-artifacts' option = %s", self->zero_artifacts ? "yes" : "no"); - + return 0; } @@ -781,61 +762,61 @@ static int _tdav_session_video_jb_cb(const tdav_video_jb_cb_data_xt* data) tdav_session_video_t* video = (tdav_session_video_t*)data->usr_data; tdav_session_av_t* base = (tdav_session_av_t*)data->usr_data; tmedia_session_t* session = (tmedia_session_t*)data->usr_data; - - switch(data->type){ - default: break; - case tdav_video_jb_cb_data_type_rtp: - { - return _tdav_session_video_decode(video, data->rtp.pkt); - } - case tdav_video_jb_cb_data_type_tmfr: - { - base->time_last_frame_loss_report = tsk_time_now(); + + switch (data->type) { + default: + break; + case tdav_video_jb_cb_data_type_rtp: { + return _tdav_session_video_decode(video, data->rtp.pkt); + } + case tdav_video_jb_cb_data_type_tmfr: { + base->time_last_frame_loss_report = tsk_time_now(); + _tdav_session_video_local_request_idr(session, "TMFR", data->ssrc); + } + case tdav_video_jb_cb_data_type_fl: { + base->time_last_frame_loss_report = tsk_time_now(); + if(data->fl.count > TDAV_SESSION_VIDEO_PKT_LOSS_MAX_COUNT_TO_REQUEST_FIR) { _tdav_session_video_local_request_idr(session, "TMFR", data->ssrc); } - case tdav_video_jb_cb_data_type_fl: - { - base->time_last_frame_loss_report = tsk_time_now(); - if(data->fl.count > TDAV_SESSION_VIDEO_PKT_LOSS_MAX_COUNT_TO_REQUEST_FIR){ - _tdav_session_video_local_request_idr(session, "TMFR", data->ssrc); - } - else { - if (base->avpf_mode_neg || base->is_fb_nack_neg) { // AVPF? - // Send RTCP-NACK - tsk_size_t i, j, k; - uint16_t seq_nums[16]; - for(i = 0; i < data->fl.count; i+=16){ - for(j = 0, k = i; j < 16 && k < data->fl.count; ++j, ++k){ - seq_nums[j] = (uint16_t)(data->fl.seq_num + i + j); - TSK_DEBUG_INFO("Request re-send(%u)", seq_nums[j]); - } - trtp_manager_signal_pkt_loss(base->rtp_manager, data->ssrc, seq_nums, j); + else { + if (base->avpf_mode_neg || base->is_fb_nack_neg) { // AVPF? + // Send RTCP-NACK + tsk_size_t i, j, k; + uint16_t seq_nums[16]; + for (i = 0; i < data->fl.count; i+=16) { + for(j = 0, k = i; j < 16 && k < data->fl.count; ++j, ++k) { + seq_nums[j] = (uint16_t)(data->fl.seq_num + i + j); + TSK_DEBUG_INFO("Request re-send(%u)", seq_nums[j]); } + trtp_manager_signal_pkt_loss(base->rtp_manager, data->ssrc, seq_nums, j); } } - - break; } - case tdav_video_jb_cb_data_type_fps_changed: - { - if(base->congestion_ctrl_enabled){ - video->fps_changed = tsk_true; - if(video->decoder.codec){ - TSK_DEBUG_INFO("Congestion control enabled and fps updated from %u to %u", data->fps.old, data->fps.new); - TMEDIA_CODEC_VIDEO(video->decoder.codec)->in.fps = data->fps.new; - } + + break; + } + case tdav_video_jb_cb_data_type_fps_changed: { + if (base->congestion_ctrl_enabled) { + video->fps_changed = tsk_true; + if (video->decoder.codec) { + TSK_DEBUG_INFO("Congestion control enabled and fps updated from %u to %u", data->fps.old, data->fps.new); + TMEDIA_CODEC_VIDEO(video->decoder.codec)->in.fps = data->fps.new; } - break; + tsk_mutex_lock(video->h_mutex_qos); + session->qos_metrics.video_in_avg_fps = (session->qos_metrics.video_in_avg_fps + data->fps.new) / (video->in_avg_fps_n++ ? 2 : 1); + tsk_mutex_unlock(video->h_mutex_qos); } + break; } - + } + return 0; } int _tdav_session_video_open_decoder(tdav_session_video_t* self, uint8_t payload_type) { int ret = 0; - + if ((self->decoder.codec_payload_type != payload_type) || !self->decoder.codec) { tsk_istr_t format; TSK_OBJECT_SAFE_FREE(self->decoder.codec); @@ -849,14 +830,14 @@ int _tdav_session_video_open_decoder(tdav_session_video_t* self, uint8_t payload self->decoder.codec_decoded_frames_count = 0; // because we switched the codecs } // Open codec if not already done - if (!TMEDIA_CODEC(self->decoder.codec)->opened){ + if (!TMEDIA_CODEC(self->decoder.codec)->opened) { if ((ret = tmedia_codec_open(self->decoder.codec))) { TSK_DEBUG_ERROR("Failed to open [%s] codec", self->decoder.codec->plugin->desc); goto bail; } self->decoder.codec_decoded_frames_count = 0; // because first time to use } - + bail: return ret; } @@ -867,45 +848,49 @@ static int _tdav_session_video_decode(tdav_session_video_t* self, const trtp_rtp static const trtp_rtp_header_t* __rtp_header = tsk_null; static const tmedia_codec_id_t __codecs_supporting_zero_artifacts = (tmedia_codec_id_vp8 | tmedia_codec_id_h264_bp | tmedia_codec_id_h264_mp | tmedia_codec_id_h263); int ret = 0; - - if(!self || !packet || !packet->header){ + + if(!self || !packet || !packet->header) { TSK_DEBUG_ERROR("Invalid parameter"); return -1; } - + tsk_safeobj_lock(base); - + if (self->started && base->consumer && base->consumer->is_started) { tsk_size_t out_size, _size; const void* _buffer; tdav_session_video_t* video = (tdav_session_video_t*)base; - + tmedia_session_t* session = (tmedia_session_t*)base; + uint64_t time_start, time_duration; + // Find the codec to use to decode the RTP payload - if(!self->decoder.codec || self->decoder.codec_payload_type != packet->header->payload_type){ - if((ret = _tdav_session_video_open_decoder(self, packet->header->payload_type))){ + if (!self->decoder.codec || self->decoder.codec_payload_type != packet->header->payload_type) { + if ((ret = _tdav_session_video_open_decoder(self, packet->header->payload_type))) { goto bail; } } - + // check whether bypassing is enabled (e.g. rtcweb breaker ON and media coder OFF) - if(TMEDIA_SESSION(self)->bypass_decoding){ + if(TMEDIA_SESSION(self)->bypass_decoding) { // set codec id for internal use (useful to find codec with dynamic payload type) TRTP_RTP_HEADER(packet->header)->codec_id = self->decoder.codec->id; // consume the frame ret = tmedia_consumer_consume(base->consumer, (packet->payload.data ? packet->payload.data : packet->payload.data_const), packet->payload.size, packet->header); goto bail; } - + + time_start = tsk_time_now(); + // Check if stream is corrupted or not - if(video->decoder.last_seqnum && (video->decoder.last_seqnum + 1) != packet->header->seq_num){ + if(video->decoder.last_seqnum && (video->decoder.last_seqnum + 1) != packet->header->seq_num) { TSK_DEBUG_INFO("/!\\Video stream corrupted because of packet loss [%u - %u]. Pause rendering if 'zero_artifacts' (supported = %s, enabled = %s).", video->decoder.last_seqnum, packet->header->seq_num, (__codecs_supporting_zero_artifacts & self->decoder.codec->id) ? "yes" : "no", self->zero_artifacts ? "yes" : "no" - ); - if(!video->decoder.stream_corrupted){ // do not do the job twice - if(self->zero_artifacts && (__codecs_supporting_zero_artifacts & self->decoder.codec->id)){ + ); + if(!video->decoder.stream_corrupted) { // do not do the job twice + if(self->zero_artifacts && (__codecs_supporting_zero_artifacts & self->decoder.codec->id)) { // request IDR now and every time after 'TDAV_SESSION_VIDEO_AVPF_FIR_REQUEST_INTERVAL_MIN' ellapsed // 'zero-artifacts' not enabled then, we'll request IDR when decoding fails TSK_DEBUG_INFO("Sending FIR to request IDR..."); @@ -919,35 +904,43 @@ static int _tdav_session_video_decode(tdav_session_video_t* self, const trtp_rtp video->decoder.last_corrupted_timestamp = packet->header->timestamp; } video->decoder.last_seqnum = packet->header->seq_num; // update last seqnum - + // Decode data out_size = self->decoder.codec->plugin->decode( - self->decoder.codec, - (packet->payload.data ? packet->payload.data : packet->payload.data_const), packet->payload.size, - &self->decoder.buffer, &self->decoder.buffer_size, - packet->header - ); + self->decoder.codec, + (packet->payload.data ? packet->payload.data : packet->payload.data_const), packet->payload.size, + &self->decoder.buffer, &self->decoder.buffer_size, + packet->header + ); + + // report to the remote party the bandwidth usage and jitter buffer congestion info + // this must be done here to make sure it won't be skipped by decoding issues or any other failure + ret = _tdav_session_video_report_bw_usage_and_jcng(self); + + // inc() frame count + ++self->decoder.codec_decoded_frames_count; + // check - if(!out_size || !self->decoder.buffer){ + if (!out_size || !self->decoder.buffer) { goto bail; } // check if stream is corrupted // the above decoding process is required in order to reset stream corruption status when IDR frame is decoded - if(self->zero_artifacts && self->decoder.stream_corrupted && (__codecs_supporting_zero_artifacts & self->decoder.codec->id)){ + if (self->zero_artifacts && self->decoder.stream_corrupted && (__codecs_supporting_zero_artifacts & self->decoder.codec->id)) { TSK_DEBUG_INFO("Do not render video frame because stream is corrupted and 'zero-artifacts' is enabled. Last seqnum=%u", video->decoder.last_seqnum); - if(video->decoder.stream_corrupted && (tsk_time_now() - video->decoder.stream_corrupted_since) > TDAV_SESSION_VIDEO_AVPF_FIR_REQUEST_INTERVAL_MIN){ + if (video->decoder.stream_corrupted && (tsk_time_now() - video->decoder.stream_corrupted_since) > TDAV_SESSION_VIDEO_AVPF_FIR_REQUEST_INTERVAL_MIN) { TSK_DEBUG_INFO("Sending FIR to request IDR because frame corrupted since %llu...", video->decoder.stream_corrupted_since); _tdav_session_video_local_request_idr(TMEDIA_SESSION(video), "ZERO_ART_CORRUPTED", packet->header->ssrc); } goto bail; } - + // important: do not override the display size (used by the end-user) unless requested - if(base->consumer->video.display.auto_resize){ + if(base->consumer->video.display.auto_resize) { base->consumer->video.display.width = TMEDIA_CODEC_VIDEO(self->decoder.codec)->in.width;//decoded width base->consumer->video.display.height = TMEDIA_CODEC_VIDEO(self->decoder.codec)->in.height;//decoded height } - + // Convert decoded data to the consumer chroma and size #define CONSUMER_NEED_DECODER (base->consumer->decoder.codec_id == tmedia_codec_id_none) // Otherwise, the consumer requires encoded frames #define CONSUMER_IN_N_DISPLAY_MISMATCH (!base->consumer->video.display.auto_resize && (base->consumer->video.in.width != base->consumer->video.display.width || base->consumer->video.in.height != base->consumer->video.display.height)) @@ -955,112 +948,64 @@ static int _tdav_session_video_decode(tdav_session_video_t* self, const trtp_rtp #define CONSUMER_DISPLAY_N_CONVERTER_MISMATCH ( (self->conv.fromYUV420 && self->conv.fromYUV420->dstWidth != base->consumer->video.display.width) || (self->conv.fromYUV420 && self->conv.fromYUV420->dstHeight != base->consumer->video.display.height) ) #define CONSUMER_CHROMA_MISMATCH (base->consumer->video.display.chroma != TMEDIA_CODEC_VIDEO(self->decoder.codec)->in.chroma) #define DECODED_NEED_FLIP (TMEDIA_CODEC_VIDEO(self->decoder.codec)->in.flip) - - if(CONSUMER_NEED_DECODER && (CONSUMER_CHROMA_MISMATCH || CONSUMER_DISPLAY_N_CODEC_MISMATCH || CONSUMER_IN_N_DISPLAY_MISMATCH || CONSUMER_DISPLAY_N_CONVERTER_MISMATCH || DECODED_NEED_FLIP)){ - + + if(CONSUMER_NEED_DECODER && (CONSUMER_CHROMA_MISMATCH || CONSUMER_DISPLAY_N_CODEC_MISMATCH || CONSUMER_IN_N_DISPLAY_MISMATCH || CONSUMER_DISPLAY_N_CONVERTER_MISMATCH || DECODED_NEED_FLIP)) { + // Create video converter if not already done - if(!self->conv.fromYUV420 || CONSUMER_DISPLAY_N_CONVERTER_MISMATCH){ + if(!self->conv.fromYUV420 || CONSUMER_DISPLAY_N_CONVERTER_MISMATCH) { TSK_OBJECT_SAFE_FREE(self->conv.fromYUV420); - + // create converter if(!(self->conv.fromYUV420 = tmedia_converter_video_create(TMEDIA_CODEC_VIDEO(self->decoder.codec)->in.width, TMEDIA_CODEC_VIDEO(self->decoder.codec)->in.height, TMEDIA_CODEC_VIDEO(self->decoder.codec)->in.chroma, base->consumer->video.display.width, base->consumer->video.display.height, - base->consumer->video.display.chroma))){ + base->consumer->video.display.chroma))) { TSK_DEBUG_ERROR("Failed to create video converter"); ret = -3; goto bail; } } } - + // update consumer size using the codec decoded values // must be done here to avoid fooling "CONSUMER_IN_N_DISPLAY_MISMATCH" unless "auto_resize" option is enabled base->consumer->video.in.width = TMEDIA_CODEC_VIDEO(self->decoder.codec)->in.width;//decoded width base->consumer->video.in.height = TMEDIA_CODEC_VIDEO(self->decoder.codec)->in.height;//decoded height - - if(self->conv.fromYUV420){ + + if(self->conv.fromYUV420) { // update one-shot parameters tmedia_converter_video_set_flip(self->conv.fromYUV420, TMEDIA_CODEC_VIDEO(self->decoder.codec)->in.flip); // convert data to the consumer's chroma out_size = tmedia_converter_video_process(self->conv.fromYUV420, self->decoder.buffer, self->decoder.buffer_size, &self->decoder.conv_buffer, &self->decoder.conv_buffer_size); - if(!out_size || !self->decoder.conv_buffer){ + if(!out_size || !self->decoder.conv_buffer) { TSK_DEBUG_ERROR("Failed to convert YUV420 buffer to consumer's chroma"); ret = -4; goto bail; } - + _buffer = self->decoder.conv_buffer; _size = out_size; } - else{ + else { _buffer = self->decoder.buffer; _size = out_size; } - - // congetion control - // send RTCP-REMB if: - // - congestion control is enabled and - // - fps changed or - // - first frame or - // - approximately every 1 seconds (1 = 1 * 1) - if (base->congestion_ctrl_enabled && base->rtp_manager && (self->fps_changed || self->decoder.codec_decoded_frames_count == 0 || ((self->decoder.codec_decoded_frames_count % (TMEDIA_CODEC_VIDEO(self->decoder.codec)->in.fps * 1)) == 0))){ - int32_t bandwidth_max_upload_kbps = base->bandwidth_max_upload_kbps; - int32_t bandwidth_max_download_kbps = base->bandwidth_max_download_kbps; // user-defined (guard), INT_MAX if not defined - // bandwidth already computed in start() but the decoded video size was not correct and based on the SDP negotiation - bandwidth_max_download_kbps = TSK_MIN( - tmedia_get_video_bandwidth_kbps_2(TMEDIA_CODEC_VIDEO(self->decoder.codec)->in.width, TMEDIA_CODEC_VIDEO(self->decoder.codec)->in.height, TMEDIA_CODEC_VIDEO(self->decoder.codec)->in.fps), - bandwidth_max_download_kbps); - if (self->encoder.codec) { - bandwidth_max_upload_kbps = TSK_MIN( - tmedia_get_video_bandwidth_kbps_2(TMEDIA_CODEC_VIDEO(self->encoder.codec)->out.width, TMEDIA_CODEC_VIDEO(self->encoder.codec)->out.height, TMEDIA_CODEC_VIDEO(self->encoder.codec)->out.fps), - bandwidth_max_upload_kbps); - } - -#if TDAV_GOOG_REMB_FULL_SUPPORT - { - tsk_bool_t remb_ok = tsk_false; - int32_t remb_download_kbps = 0; - uint64_t now = 0; - uint64_t bytes_count_in; - static uint64_t* bytes_count_out_ptr_null = tsk_null; - if ((ret = trtp_manager_get_bytes_count(base->rtp_manager, &bytes_count_in, bytes_count_out_ptr_null)) == 0) { - uint64_t duration; - now = tsk_time_now(); - duration = (now - base->bytes_in.count_last_time); - remb_ok = (base->bytes_in.count_last_time != 0 && duration > 0); - if (remb_ok) { - remb_download_kbps = (int32_t)((((bytes_count_in - base->bytes_in.count) * 8 * 1000) / 1024) / duration); - TSK_DEBUG_INFO("remb_download_kbps=%d", remb_download_kbps); - } - base->bytes_in.count_last_time = now; - base->bytes_in.count = bytes_count_in; - } - if (remb_ok) { - // if "remb_ok" is true then "now" has a valid value - if ((now - base->time_last_frame_loss_report) > TDAV_SESSION_VIDEO_PKT_LOSS_NO_REPORT_BEFORE_INCREASING_BW) { - TSK_DEBUG_INFO("No pakt loss since %d millis ... adding 5%% to the estimated max bandwidth", TDAV_SESSION_VIDEO_PKT_LOSS_NO_REPORT_BEFORE_INCREASING_BW); - remb_download_kbps += (remb_download_kbps / 100) * 5; // add 5% to the estimated bandwidth - } - // CLAMP is used to make sure we will not report more than what the user defined as max values even if the estimated values are higher - bandwidth_max_download_kbps = TSK_CLAMP(0, remb_download_kbps, bandwidth_max_download_kbps); - } - } -#endif /* TDAV_GOOG_REMB_FULL_SUPPORT */ - - self->fps_changed = tsk_false; // reset - TSK_DEBUG_INFO("video with congestion control enabled: max_bw_up(unused)=%d kpbs, max_bw_down=%d kpbs", bandwidth_max_upload_kbps, bandwidth_max_download_kbps); - ret = trtp_manager_set_app_bandwidth_max(base->rtp_manager, bandwidth_max_upload_kbps/* unused */, bandwidth_max_download_kbps); + + time_duration = tsk_time_now() - time_start; + if (base->congestion_ctrl_enabled) { + tsk_mutex_lock(video->h_mutex_qos); + session->qos_metrics.video_dec_avg_time = (unsigned)((session->qos_metrics.video_dec_avg_time + time_duration) / (video->dec_avg_time_n++ ? 2 : 1)); + tsk_mutex_unlock(video->h_mutex_qos); } - // inc() frame count and consume decoded video - ++self->decoder.codec_decoded_frames_count; + + // consume decoded video ret = tmedia_consumer_consume(base->consumer, _buffer, _size, __rtp_header); } else if (!base->consumer || !base->consumer->is_started) { TSK_DEBUG_INFO("Consumer not started (is_null=%d)", !base->consumer); } - + bail: tsk_safeobj_unlock(base); - + return ret; } @@ -1071,36 +1016,36 @@ static int tdav_session_video_set(tmedia_session_t* self, const tmedia_param_t* int ret = 0; tdav_session_video_t* video; tdav_session_av_t* base; - - if(!self){ + + if(!self) { TSK_DEBUG_ERROR("Invalid parameter"); return -1; } - + // try with the base class to see if this option is supported or not if (tdav_session_av_set(TDAV_SESSION_AV(self), param) == tsk_true) { return 0; } - + video = (tdav_session_video_t*)self; base = (tdav_session_av_t*)self; - - if(param->plugin_type == tmedia_ppt_codec){ + + if(param->plugin_type == tmedia_ppt_codec) { tsk_mutex_lock(video->encoder.h_mutex); ret = tmedia_codec_set((tmedia_codec_t*)video->encoder.codec, param); tsk_mutex_unlock(video->encoder.h_mutex); } - else if(param->plugin_type == tmedia_ppt_consumer){ - if(!base->consumer){ + else if(param->plugin_type == tmedia_ppt_consumer) { + if(!base->consumer) { TSK_DEBUG_ERROR("No consumer associated to this session"); return -1; } - if(param->value_type == tmedia_pvt_int32){ - if(tsk_striequals(param->key, "flip")){ + if(param->value_type == tmedia_pvt_int32) { + if(tsk_striequals(param->key, "flip")) { tsk_list_item_t* item; tsk_bool_t flip = (tsk_bool_t)TSK_TO_INT32((uint8_t*)param->value); tmedia_codecs_L_t *codecs = tsk_object_ref(self->codecs); - tsk_list_foreach(item, codecs){ + tsk_list_foreach(item, codecs) { TMEDIA_CODEC_VIDEO(item->data)->in.flip = flip; } tsk_object_unref(codecs); @@ -1108,17 +1053,17 @@ static int tdav_session_video_set(tmedia_session_t* self, const tmedia_param_t* } ret = tmedia_consumer_set(base->consumer, param); } - else if(param->plugin_type == tmedia_ppt_producer){ - if(!base->producer){ + else if(param->plugin_type == tmedia_ppt_producer) { + if(!base->producer) { TSK_DEBUG_ERROR("No producer associated to this session"); return -1; } - if(param->value_type == tmedia_pvt_int32){ - if(tsk_striequals(param->key, "flip")){ + if(param->value_type == tmedia_pvt_int32) { + if(tsk_striequals(param->key, "flip")) { tsk_list_item_t* item; tsk_bool_t flip = (tsk_bool_t)TSK_TO_INT32((uint8_t*)param->value); tmedia_codecs_L_t *codecs = tsk_object_ref(self->codecs); - tsk_list_foreach(item, codecs){ + tsk_list_foreach(item, codecs) { TMEDIA_CODEC_VIDEO(item->data)->out.flip = flip; } tsk_object_unref(codecs); @@ -1126,20 +1071,20 @@ static int tdav_session_video_set(tmedia_session_t* self, const tmedia_param_t* } ret = tmedia_producer_set(base->producer, param); } - else{ - if (param->value_type == tmedia_pvt_int32){ - if (tsk_striequals(param->key, "bandwidth-level")){ + else { + if (param->value_type == tmedia_pvt_int32) { + if (tsk_striequals(param->key, "bandwidth-level")) { tsk_list_item_t* item; self->bl = (tmedia_bandwidth_level_t)TSK_TO_INT32((uint8_t*)param->value); self->codecs = tsk_object_ref(self->codecs); - tsk_list_foreach(item, self->codecs){ + tsk_list_foreach(item, self->codecs) { ((tmedia_codec_t*)item->data)->bl = self->bl; } tsk_object_unref(self->codecs); } } } - + return ret; } @@ -1149,7 +1094,7 @@ static int tdav_session_video_get(tmedia_session_t* self, tmedia_param_t* param) TSK_DEBUG_ERROR("Invalid parameter"); return -1; } - + // try with the base class to see if this option is supported or not if (tdav_session_av_get(TDAV_SESSION_AV(self), param) == tsk_true) { return 0; @@ -1164,7 +1109,7 @@ static int tdav_session_video_get(tmedia_session_t* self, tmedia_param_t* param) } } } - + TSK_DEBUG_WARN("This session doesn't support get(%s)", param->key); return -2; } @@ -1174,17 +1119,17 @@ static int tdav_session_video_prepare(tmedia_session_t* self) tdav_session_av_t* base = (tdav_session_av_t*)(self); tdav_session_video_t* video = (tdav_session_video_t*)self; int ret; - - if((ret = tdav_session_av_prepare(base))){ + + if((ret = tdav_session_av_prepare(base))) { TSK_DEBUG_ERROR("tdav_session_av_prepare(video) failed"); return ret; } - - if(base->rtp_manager){ + + if(base->rtp_manager) { ret = trtp_manager_set_rtp_callback(base->rtp_manager, tdav_session_video_rtp_cb, base); ret = trtp_manager_set_rtcp_callback(base->rtp_manager, tdav_session_video_rtcp_cb, base); } - + return ret; } @@ -1194,20 +1139,20 @@ static int tdav_session_video_start(tmedia_session_t* self) tdav_session_video_t* video; const tmedia_codec_t* codec; tdav_session_av_t* base; - + if (!self) { TSK_DEBUG_ERROR("Invalid parameter"); return -1; } - + video = (tdav_session_video_t*)self; base = (tdav_session_av_t*)self; - + if (video->started) { TSK_DEBUG_INFO("Video session already started"); return 0; } - + // ENCODER codec if (!(codec = tdav_session_av_get_best_neg_codec(base))) { TSK_DEBUG_ERROR("No codec matched"); @@ -1222,26 +1167,32 @@ static int tdav_session_video_start(tmedia_session_t* self) return ret; } if (!TMEDIA_CODEC(video->encoder.codec)->opened) { - if((ret = tmedia_codec_open(video->encoder.codec))){ + if((ret = tmedia_codec_open(video->encoder.codec))) { tsk_mutex_unlock(video->encoder.h_mutex); TSK_DEBUG_ERROR("Failed to open [%s] codec", video->encoder.codec->plugin->desc); return ret; } } tsk_mutex_unlock(video->encoder.h_mutex); - + if (video->jb) { if ((ret = tdav_video_jb_start(video->jb))) { TSK_DEBUG_ERROR("Failed to start jitter buffer"); return ret; } } - + if ((ret = tdav_session_av_start(base, video->encoder.codec))) { TSK_DEBUG_ERROR("tdav_session_av_start(video) failed"); return ret; } video->started = tsk_true; + + // start timer manager (must be after setting "started" to true) + if (tsk_timer_mgr_global_start() == 0) { + video->timer.id_qos = tsk_timer_mgr_global_schedule(TDAV_SESSION_VIDEO_QOS_COMPUTE_INTERVAL, _tdav_session_video_timer_cb, video); + } + return ret; } @@ -1250,18 +1201,25 @@ static int tdav_session_video_stop(tmedia_session_t* self) int ret; tdav_session_video_t* video; tdav_session_av_t* base; - + TSK_DEBUG_INFO("tdav_session_video_stop"); - + video = (tdav_session_video_t*)self; base = (tdav_session_av_t*)self; - + + // unschedule qos timer + if (video->timer.mgr) { + tsk_timer_mgr_global_cancel(video->timer.id_qos); + video->timer.id_qos = TSK_INVALID_TIMER_ID; + // must not stop global timer manager as it's used by other functions + } + // must be here to make sure no other thread will lock the encoder once we have done it tsk_mutex_lock(video->encoder.h_mutex); // encoder thread will check "started" var right after the lock is passed video->started = tsk_false; tsk_mutex_unlock(video->encoder.h_mutex); // at this step we're sure that encode() will no longer be called which means we can safely close the codec - + if (video->jb) { ret = tdav_video_jb_stop(video->jb); } @@ -1269,7 +1227,7 @@ static int tdav_session_video_stop(tmedia_session_t* self) tsk_list_lock(video->avpf.packets); tsk_list_clear_items(video->avpf.packets); tsk_list_unlock(video->avpf.packets); - + // tdav_session_av_stop() : stop producer and consumer, close encoder and all other codecs, stop rtpManager... // no need to lock the encoder to avoid using a closed codec (see above) // no need to lock the decoder as the rtpManager will be stop before closing the codec @@ -1279,11 +1237,11 @@ static int tdav_session_video_stop(tmedia_session_t* self) TSK_OBJECT_SAFE_FREE(video->encoder.codec); tsk_mutex_unlock(video->encoder.h_mutex); TSK_OBJECT_SAFE_FREE(video->decoder.codec); - + // reset default values to make sure next start will be called with right defaults // do not call this function in start to avoid overriding values defined between prepare() and start() _tdav_session_video_set_defaults(video); - + return ret; } @@ -1297,17 +1255,17 @@ static const tsdp_header_M_t* tdav_session_video_get_lo(tmedia_session_t* self) tsk_bool_t updated = tsk_false; const tsdp_header_M_t* ret; tdav_session_av_t* base = TDAV_SESSION_AV(self); - - if(!(ret = tdav_session_av_get_lo(base, &updated))){ + + if(!(ret = tdav_session_av_get_lo(base, &updated))) { TSK_DEBUG_ERROR("tdav_session_av_get_lo(video) failed"); return tsk_null; } - - if(updated){ + + if(updated) { // set callbacks _tdav_session_video_set_callbacks(self); } - + return ret; } @@ -1316,28 +1274,30 @@ static int tdav_session_video_set_ro(tmedia_session_t* self, const tsdp_header_M int ret; tsk_bool_t updated = tsk_false; tdav_session_av_t* base = TDAV_SESSION_AV(self); - - if((ret = tdav_session_av_set_ro(base, m, &updated))){ + + if((ret = tdav_session_av_set_ro(base, m, &updated))) { TSK_DEBUG_ERROR("tdav_session_av_set_ro(video) failed"); return ret; } - + // Check if "RTCP-NACK" and "RTC-FIR" are supported { const tmedia_codec_t* codec; - base->is_fb_fir_neg = base->is_fb_nack_neg = base->is_fb_googremb_neg = tsk_false; + base->is_fb_fir_neg = base->is_fb_nack_neg = base->is_fb_googremb_neg = base->is_fb_doubsjcng_neg = tsk_false; if ((codec = tdav_session_av_get_best_neg_codec(base))) { // a=rtcp-fb:* ccm fir // a=rtcp-fb:* nack // a=rtcp-fb:* goog-remb - char attr_fir[256], attr_nack[256], attr_goog_remb[256]; + // a=rtcp-fb:* doubs-jcng + char attr_fir[256], attr_nack[256], attr_goog_remb[256], attr_doubs_jcng[256]; int index = 0; const tsdp_header_A_t* A; - + sprintf(attr_fir, "%s ccm fir", codec->neg_format); sprintf(attr_nack, "%s nack", codec->neg_format); sprintf(attr_goog_remb, "%s goog-remb", codec->neg_format); - + sprintf(attr_doubs_jcng, "%s doubs-jcng", codec->neg_format); + while ((A = tsdp_header_M_findA_at(m, "rtcp-fb", index++))) { if (!base->is_fb_fir_neg) { base->is_fb_fir_neg = (tsk_striequals(A->value, "* ccm fir") || tsk_striequals(A->value, attr_fir)); @@ -1348,15 +1308,18 @@ static int tdav_session_video_set_ro(tmedia_session_t* self, const tsdp_header_M if (!base->is_fb_googremb_neg) { base->is_fb_googremb_neg = (tsk_striequals(A->value, "* goog-remb") || tsk_striequals(A->value, attr_goog_remb)); } - } + if (!base->is_fb_doubsjcng_neg) { + base->is_fb_doubsjcng_neg = (tsk_striequals(A->value, "* doubs-jcng") || tsk_striequals(A->value, attr_doubs_jcng)); + } + } } } - + if (updated) { // set callbacks ret = _tdav_session_video_set_callbacks(self); } - + return ret; } @@ -1365,20 +1328,20 @@ static int tdav_session_video_rtcp_set_onevent_cbfn(tmedia_session_t* self, cons { tdav_session_video_t* video; tdav_session_av_t* base; - - if(!self){ + + if(!self) { TSK_DEBUG_ERROR("Invalid parameter"); return -1; } - + video = (tdav_session_video_t*)self; base = (tdav_session_av_t*)self; - + tsk_safeobj_lock(base); video->cb_rtcpevent.context = context; video->cb_rtcpevent.func = func; tsk_safeobj_unlock(base); - + return 0; } @@ -1388,31 +1351,30 @@ static int tdav_session_video_rtcp_send_event(tmedia_session_t* self, tmedia_rtc tdav_session_video_t* video; tdav_session_av_t* base; int ret = -1; - - if(!self){ + + if(!self) { TSK_DEBUG_ERROR("Invalid parameter"); return -1; } - + video = (tdav_session_video_t*)self; base = (tdav_session_av_t*)self; - + tsk_safeobj_lock(base); - switch(event_type){ - case tmedia_rtcp_event_type_fir: - { - if(base->rtp_manager && base->rtp_manager->is_started){ - if(!ssrc_media){ // when called from C++/Java/C# bindings "ssrc_media" is a default parameter with value=0 - ssrc_media = base->rtp_manager->rtp.ssrc.remote; - } - TSK_DEBUG_INFO("Send FIR(%u)", ssrc_media); - _tdav_session_video_local_request_idr(self, "CALLBACK", ssrc_media); + switch(event_type) { + case tmedia_rtcp_event_type_fir: { + if(base->rtp_manager && base->rtp_manager->is_started) { + if(!ssrc_media) { // when called from C++/Java/C# bindings "ssrc_media" is a default parameter with value=0 + ssrc_media = base->rtp_manager->rtp.ssrc.remote; } - break; + TSK_DEBUG_INFO("Send FIR(%u)", ssrc_media); + _tdav_session_video_local_request_idr(self, "CALLBACK", ssrc_media); } + break; + } } tsk_safeobj_unlock(base); - + return ret; } @@ -1422,39 +1384,179 @@ static int tdav_session_video_rtcp_recv_event(tmedia_session_t* self, tmedia_rtc tdav_session_video_t* video; tdav_session_av_t* base; int ret = -1; - - if (!self){ + + if (!self) { TSK_DEBUG_ERROR("Invalid parameter"); return -1; } - + video = (tdav_session_video_t*)self; base = (tdav_session_av_t*)self; - + tsk_safeobj_lock(base); - switch(event_type){ - case tmedia_rtcp_event_type_fir: - { - _tdav_session_video_remote_requested_idr(video, ssrc_media); - ret = 0; - break; - } + switch(event_type) { + case tmedia_rtcp_event_type_fir: { + _tdav_session_video_remote_requested_idr(video, ssrc_media); + ret = 0; + break; + } } tsk_safeobj_unlock(base); - + + return ret; +} + +static int _tdav_session_video_timer_cb(const void* arg, tsk_timer_id_t timer_id) +{ + /*const*/ tdav_session_video_t* video = (/*const*/ tdav_session_video_t*)tsk_object_ref(TSK_OBJECT(arg)); + tdav_session_av_t* base = (tdav_session_av_t*)video; + tmedia_session_t* session = (tmedia_session_t*)video; + if (video->timer.id_qos == timer_id) { + if (base->congestion_ctrl_enabled) { + tmedia_codec_video_t* codec = tsk_object_ref(TSK_OBJECT(video->encoder.codec)); + if (codec && video->started) { + float q1, q2, q3, q4, q5, qavg, c; + uint64_t bw_est_kbps; + // Compute average QoS + tsk_mutex_lock(video->h_mutex_qos); + q1 = video->q1_n ? session->qos_metrics.q1 : 1.f; + q2 = video->q2_n ? session->qos_metrics.q2 : 1.f; + q3 = video->q3_n ? session->qos_metrics.q3 : 1.f; + q4 = video->q4_n ? session->qos_metrics.q4 : 1.f; + q5 = video->q5_n ? session->qos_metrics.q5 : 1.f; + + // update bw info + if (_tdav_session_video_get_bw_usage_est(video, &bw_est_kbps, /*in=*/tsk_true, /*reset*/tsk_true) == 0 && bw_est_kbps != 0) { + session->qos_metrics.bw_down_est_kbps = (unsigned)bw_est_kbps; + } + if (_tdav_session_video_get_bw_usage_est(video, &bw_est_kbps, /*in=*/tsk_false, /*reset*/tsk_true) == 0 && bw_est_kbps != 0) { + session->qos_metrics.bw_up_est_kbps = (unsigned)bw_est_kbps; + } + + // update video size + session->qos_metrics.video_out_width = codec->out.width; + session->qos_metrics.video_out_height = codec->out.height; + session->qos_metrics.video_in_width = codec->in.width; + session->qos_metrics.video_in_height = codec->in.height; + // reset n + video->q1_n = video->q2_n = video->q3_n = video->q4_n = video->q5_n = 0; + session->qos_metrics.q1 = session->qos_metrics.q2 = session->qos_metrics.q3 = session->qos_metrics.q4 = session->qos_metrics.q5 = 0.f; + // continue averaging + video->in_avg_fps_n = video->in_avg_fps_n ? 1 : 0; + video->dec_avg_time_n = video->dec_avg_time_n ? 1 : 0; + video->enc_avg_time_n = video->enc_avg_time_n ? 1 : 0; + + // reset time + session->qos_metrics.last_update_time = tsk_time_now(); + tsk_mutex_unlock(video->h_mutex_qos); + +#if 0 + q1 /= 10.f; + q2 /= 10.f; + q3 /= 10.f; + q4 /= 10.f; + q5 /= 10.f; +#endif + + qavg = q1 * 0.1f + q2 * 0.4f + q3 * 0.1f + q4 * 0.1f + q5 * 0.3f; + c = /*fabs*/(qavg - session->qos_metrics.qvag); + c = c < 0.f ? -c : +c; + TSK_DEBUG_INFO("_tdav_session_video_timer_cb: q1=%f, q2=%f, q3=%f, q4=%f, q5=%f, qavg=%f, c=%f congestion_ctrl_enabled=true", q1, q2, q3, q4, q5, qavg, c); + + if (c > 0.1f) { // quality change > or < 10% + // Update the upload bandwidth + int32_t bw_up_new_kbps, bw_up_base_kbps = base->bandwidth_max_upload_kbps; // user-defined maximum + bw_up_base_kbps = TSK_MIN(tmedia_get_video_bandwidth_kbps_2(codec->out.width, codec->out.height, codec->out.fps), bw_up_base_kbps); + bw_up_new_kbps = (int32_t)(bw_up_base_kbps * qavg); + TSK_DEBUG_INFO("Video quality change(%d%%) > 10%%, changing bw_up from base=%dkbps to new=%dkbps", (int)(c*100), bw_up_base_kbps, bw_up_new_kbps); + _tdav_session_video_bw_kbps(video, bw_up_new_kbps); + session->qos_metrics.qvag = qavg; + } + //!\ update qavg only if condition "c" is true + } + tsk_object_unref(TSK_OBJECT(codec)); + } + else { + TSK_DEBUG_INFO("_tdav_session_video_timer_cb: congestion_ctrl_enabled=false"); + } + + if (video->started) { + video->timer.id_qos = tsk_timer_mgr_global_schedule(TDAV_SESSION_VIDEO_QOS_COMPUTE_INTERVAL, _tdav_session_video_timer_cb, video); + } + } + tsk_object_unref(TSK_OBJECT(video)); + return 0; +} + +static int _tdav_session_video_get_bw_usage_est(tdav_session_video_t* self, uint64_t* bw_kbps, tsk_bool_t in, tsk_bool_t reset) +{ + int ret; + + tdav_session_av_t* base = (tdav_session_av_t*)self; + uint64_t bw_bytes = 0; + uint64_t* bytes_in = in ? &bw_bytes : tsk_null; + uint64_t* bytes_out = in ? tsk_null : &bw_bytes; + uint64_t* count_last_time = in ? &base->bytes_in.count_last_time : &base->bytes_out.count_last_time; + uint64_t* count = in ? &base->bytes_in.count : &base->bytes_out.count; + + if ((ret = trtp_manager_get_bytes_count(base->rtp_manager, bytes_in, bytes_out)) == 0) { + uint64_t duration, bytes_count_now; + bytes_count_now = tsk_time_now(); + duration = (bytes_count_now - *count_last_time); + if (*count_last_time != 0 && duration > 0) { + *bw_kbps = ((((bw_bytes - *count) * 8 * 1000) / 1024) / duration); + } + else { + ret = -2; + } + if (reset) { + *count_last_time = bytes_count_now; + *count = bw_bytes; + } + } + + return ret; +} + +static int _tdav_session_video_report_bw_usage_and_jcng(tdav_session_video_t* self) +{ + tdav_session_av_t* base = (tdav_session_av_t*)self; + tmedia_session_t* session = (tmedia_session_t*)self; + int ret = 0; + // congetion control + // send RTCP-REMB if: + // - congestion control is enabled and + // - fps changed or + // - first frame + if (base->congestion_ctrl_enabled && base->rtp_manager && session->qos_metrics.bw_down_est_kbps != 0) { +# define TDAV_SESSION_VIDEO_QOS_COMPUTE_INTERVAL_HALF (TDAV_SESSION_VIDEO_QOS_COMPUTE_INTERVAL >> 1) + tsk_bool_t update_info = (self->fps_changed || self->decoder.codec_decoded_frames_count == 0 || session->qos_metrics.last_update_time == 0 || ((tsk_time_now() - session->qos_metrics.last_update_time) > TDAV_SESSION_VIDEO_QOS_COMPUTE_INTERVAL_HALF)); + if (update_info) { + float jcng_q = 1.f; + if (self->jb && self->jb_enabled) { + float q5 = 1.f; + if ((ret = tdav_video_jb_get_qcong(self->jb, &q5)) == 0) { + jcng_q = q5; + } + } + self->fps_changed = tsk_false; // reset + TSK_DEBUG_INFO("video with congestion control enabled: est_bw_down=%llukbps, est_jcng=%f", session->qos_metrics.bw_down_est_kbps, jcng_q); + ret = trtp_manager_set_app_bw_and_jcng(base->rtp_manager, INT_MAX/* unused */, (int32_t)session->qos_metrics.bw_down_est_kbps, jcng_q); + } + } return ret; } static int _tdav_session_video_set_callbacks(tmedia_session_t* self) { - if(self){ + if(self) { tsk_list_item_t* item; - tsk_list_foreach(item, TMEDIA_SESSION(self)->neg_codecs){ + tsk_list_foreach(item, TMEDIA_SESSION(self)->neg_codecs) { // set codec callbacks tmedia_codec_video_set_enc_callback(TMEDIA_CODEC_VIDEO(item->data), tdav_session_video_raw_cb, self); tmedia_codec_video_set_dec_callback(TMEDIA_CODEC_VIDEO(item->data), tdav_session_video_decode_cb, self); // set RED callback: redundant data to decode and send to the consumer - if(TMEDIA_CODEC(item->data)->plugin == tdav_codec_red_plugin_def_t){ + if(TMEDIA_CODEC(item->data)->plugin == tdav_codec_red_plugin_def_t) { tdav_codec_red_set_callback((struct tdav_codec_red_s *)(item->data), tdav_session_video_rtp_cb, self); } } @@ -1470,13 +1572,13 @@ static int _tdav_session_video_init(tdav_session_video_t *p_self, tmedia_type_t TSK_DEBUG_ERROR("Invalid parameter"); return -1; } - + /* init() base */ if ((ret = tdav_session_av_init(p_base, e_media_type)) != 0) { TSK_DEBUG_ERROR("tdav_session_av_init(video) failed"); return ret; } - + /* init() self */ _tdav_session_video_set_defaults(p_self); if (!p_self->encoder.h_mutex && !(p_self->encoder.h_mutex = tsk_mutex_create())) { @@ -1494,12 +1596,23 @@ static int _tdav_session_video_init(tdav_session_video_t *p_self, tmedia_type_t } tdav_video_jb_set_callback(p_self->jb, _tdav_session_video_jb_cb, p_self); } - + + /* producer's callbacks */ if (p_base->producer) { tmedia_producer_set_enc_callback(p_base->producer, tdav_session_video_producer_enc_cb, p_self); tmedia_producer_set_raw_callback(p_base->producer, tdav_session_video_raw_cb, p_self); } - + + if (!p_self->h_mutex_qos && !(p_self->h_mutex_qos = tsk_mutex_create())) { + TSK_DEBUG_ERROR("Failed to create qos mutex"); + return -5; + } + + /* timer manager */ + if(!p_self->timer.mgr) { + p_self->timer.mgr = tsk_timer_mgr_global_ref(); + } + return 0; } @@ -1511,7 +1624,7 @@ static int _tdav_session_video_init(tdav_session_video_t *p_self, tmedia_type_t static tsk_object_t* tdav_session_video_ctor(tsk_object_t * self, va_list * app) { tdav_session_video_t *video = self; - if(video){ + if(video) { if (_tdav_session_video_init(video, tmedia_video)) { return tsk_null; } @@ -1520,71 +1633,78 @@ static tsk_object_t* tdav_session_video_ctor(tsk_object_t * self, va_list * app) } /* destructor */ static tsk_object_t* tdav_session_video_dtor(tsk_object_t * self) -{ +{ tdav_session_video_t *video = self; TSK_DEBUG_INFO("*** tdav_session_video_t destroyed ***"); - if(video){ + if(video) { tdav_session_video_stop((tmedia_session_t*)video); // deinit self (rtp manager should be destroyed after the producer) TSK_OBJECT_SAFE_FREE(video->conv.toYUV420); TSK_OBJECT_SAFE_FREE(video->conv.fromYUV420); - + TSK_FREE(video->encoder.buffer); TSK_FREE(video->encoder.conv_buffer); TSK_FREE(video->decoder.buffer); TSK_FREE(video->decoder.conv_buffer); - + TSK_OBJECT_SAFE_FREE(video->encoder.codec); TSK_OBJECT_SAFE_FREE(video->decoder.codec); - + TSK_OBJECT_SAFE_FREE(video->avpf.packets); - + TSK_OBJECT_SAFE_FREE(video->jb); - - if(video->encoder.h_mutex){ + + /* timer manager */ + if (video->timer.mgr) { + tsk_timer_mgr_global_unref(&video->timer.mgr); + } + + if(video->encoder.h_mutex) { tsk_mutex_destroy(&video->encoder.h_mutex); } - + + if (video->h_mutex_qos) { + tsk_mutex_destroy(&video->h_mutex_qos); + } + /* deinit() base */ tdav_session_av_deinit(TDAV_SESSION_AV(video)); - + TSK_DEBUG_INFO("*** Video session destroyed ***"); } - + return self; } /* object definition */ -static const tsk_object_def_t tdav_session_video_def_s = -{ +static const tsk_object_def_t tdav_session_video_def_s = { sizeof(tdav_session_video_t), - tdav_session_video_ctor, + tdav_session_video_ctor, tdav_session_video_dtor, - tmedia_session_cmp, + tmedia_session_cmp, }; /* plugin definition*/ -static const tmedia_session_plugin_def_t tdav_session_video_plugin_def_s = -{ +static const tmedia_session_plugin_def_t tdav_session_video_plugin_def_s = { &tdav_session_video_def_s, - + tmedia_video, "video", - + tdav_session_video_set, tdav_session_video_get, tdav_session_video_prepare, tdav_session_video_start, tdav_session_video_pause, tdav_session_video_stop, - + /* Audio part */ { tsk_null }, - + tdav_session_video_get_lo, tdav_session_video_set_ro, - + /* T.140 */ { tsk_null }, - + /* Rtcp */ { tdav_session_video_rtcp_set_onevent_cbfn, @@ -1601,7 +1721,7 @@ const tmedia_session_plugin_def_t *tdav_session_video_plugin_def_t = &tdav_sessi static tsk_object_t* tdav_session_bfcpvideo_ctor(tsk_object_t * self, va_list * app) { tdav_session_video_t *video = self; - if(video){ + if(video) { if (_tdav_session_video_init(video, tmedia_bfcp_video)) { return tsk_null; } @@ -1609,36 +1729,34 @@ static tsk_object_t* tdav_session_bfcpvideo_ctor(tsk_object_t * self, va_list * return self; } /* object definition */ -static const tsk_object_def_t tdav_session_bfcpvideo_def_s = -{ +static const tsk_object_def_t tdav_session_bfcpvideo_def_s = { sizeof(tdav_session_video_t), - tdav_session_bfcpvideo_ctor, + tdav_session_bfcpvideo_ctor, tdav_session_video_dtor, - tmedia_session_cmp, + tmedia_session_cmp, }; -static const tmedia_session_plugin_def_t tdav_session_bfcpvideo_plugin_def_s = -{ +static const tmedia_session_plugin_def_t tdav_session_bfcpvideo_plugin_def_s = { &tdav_session_bfcpvideo_def_s, - + tmedia_bfcp_video, "video", - + tdav_session_video_set, tdav_session_video_get, tdav_session_video_prepare, tdav_session_video_start, tdav_session_video_pause, tdav_session_video_stop, - + /* Audio part */ { tsk_null }, - + tdav_session_video_get_lo, tdav_session_video_set_ro, - + /* T.140 */ { tsk_null }, - + /* Rtcp */ { tdav_session_video_rtcp_set_onevent_cbfn, |