videortp.c 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318
  1. #include "precompile.h"
  2. #include "videortp.h"
  3. #include "videocommon.h"
  4. #include "bs.h"
  5. #ifdef RVC_OS_WIN
  6. #define WIN32_LEAN_AND_MEAN
  7. #include <windows.h>
  8. #else
  9. #include <semaphore.h>
  10. #endif // RVC_OS_WIN
  11. #include <assert.h>
  12. #include <malloc.h>
  13. #include <stdint.h>
  14. #include "list.h"
  15. #include "rtp.h"
  16. #include "rtpsession.h"
  17. #include "memutil.h"
  18. #include "../rvcmediacommon/rvc_media_common.h"
  19. #include "x264.h"
  20. #include "video_common/ffmpeg_api_adapter.h"
  21. #include "video_coding/video_encoder_api.h"
  22. #include "video_coding/video_decoder.h"
  23. #include "video_coding/base/video_coding_clock.h"
  24. #include "video_coding/base/video_coding_log.h"
  25. #include "congestion_control/sim_transport/sim_external.h"
  26. #include "adaptive_jitter_buffer/video_jbuff_api.h"
  27. #include "adaptive_jitter_buffer/video_jbuff_log.h"
  28. #include "rtp_header_extension/rtp_header_extension_api.h"
  29. #include "h264_packetizer/h264_packetizer.h"
  30. #include "video_statics/video_stats.h"
  31. #include "video_common/videodebugfile.h"
  32. //接收缓冲区要大于MAX_MTU_SIZE,还要存储rtp头、udp头等
  33. #define MAX_RECV_BUFFER_SIZE 1500
  34. #define MAX_PLAYLOAD_SIZE 1400
  35. #define MAX_ASSEMBLE_EXTRA_SIZE 128
  36. #define FRAME_WIN_SIZE 20
  37. #define RTP_SEQ_GT(x, y, n) ((x > y && x-y<=n) || (y+n<n && x<=y+n))
  38. #define RTP_MAX_JUMP 128
  39. #define DIR_TX 1
  40. #define DIR_RX 2
  41. #define DIR_NONE 0
  42. #define DIR_BOTH 3
  43. #define VIDEO_CLOCK 90000
  44. #define PEER_UPDATE_INTERVAL 1500 // ms
  45. #define FIRST_KEY_FRAME_SIZE 40
  46. //DEBUG log开关
  47. #define DEBUG_TX 0
  48. #define DEBUG_ENCODER 0
  49. #define DEBUG_RX 0
  50. #define DEBUG_DECODER 0
  51. #define DEBUG_CC 0
  52. typedef unsigned char bool_t;
  53. typedef struct rtpframe_part_t {
  54. struct list_head entry;
  55. char buf[MAX_RECV_BUFFER_SIZE];
  56. int offset;
  57. int actual_len;
  58. int mb_in_slice;
  59. unsigned short seq;
  60. unsigned short mark : 1;
  61. unsigned short psc : 1;
  62. }rtpframe_part_t;
  63. typedef struct rtpframe_t {
  64. unsigned int used;
  65. unsigned int key;
  66. unsigned int ts;
  67. int id;
  68. int cur_max_mb;
  69. struct list_head part_list;
  70. }rtpframe_t;
  71. struct videortp_t
  72. {
  73. videortp_config_t config;
  74. rtp_session_t *rtp_sess;
  75. LONG force_key_frames;
  76. DWORD last_peer_update_tick;
  77. /******************************接收端*/
  78. VideoDecoder *decoder;
  79. rtpframe_part_t *sps;
  80. rtpframe_part_t *pps;
  81. /*接收缓冲*/
  82. struct list_head free_part_list;
  83. rtpframe_t frame_win[FRAME_WIN_SIZE];
  84. unsigned int frame_win_start;
  85. int frame_win_ptr;
  86. unsigned int frame_duration;
  87. unsigned int prev_dec_ts;
  88. unsigned short prev_dec_seq;
  89. uint64_t prev_dec_ms;
  90. //抖动缓冲
  91. VideoJBufferApi* jbuffer;
  92. //拥塞控制
  93. int send_cc_feedback;
  94. #ifdef _WIN32
  95. HANDLE recv_thread;
  96. HANDLE evt;
  97. #else
  98. pthread_t recv_threadid;
  99. sem_t sem_evt;
  100. #endif
  101. /******************************发送端 */
  102. VideoEncoderApi *encoder;
  103. x264_t* enc_params;
  104. //发送打包
  105. unsigned delta_ts;
  106. int64_t rtp_start_ms;
  107. RtpHeaderExtensionApi *rtp_header_extension;
  108. //拥塞控制
  109. int remote_support_cc;
  110. int recv_cc_feedback;
  111. int64_t recv_cc_feedback_ms;
  112. uint64_t framenum;
  113. //h264_packetizer
  114. h264_packetizer *h264_packetizer;
  115. //...
  116. };
  117. typedef struct _MSPicture {
  118. int w, h;
  119. uint8_t *planes[4]; // we usually use 3 planes, 4th is for compatibility
  120. int strides[4]; // with ffmpeg's swscale.h
  121. }MSPicture;
  122. //static void __Dbg(videortp_t *rtp, const char *fmt, ...)
  123. //{
  124. // int n;
  125. // va_list arg;
  126. // va_start(arg, fmt);
  127. // if (rtp->config.dbg) {
  128. // (*rtp->config.dbg)(rtp->config.user_data, fmt, arg);
  129. // } else {
  130. // n = _vscprintf(fmt, arg);
  131. // if (n > 0) {
  132. // char *buf = (char*)_alloca((size_t)(n+3));
  133. // vsprintf(buf, fmt, arg);
  134. // strcat(buf, "\r\n");
  135. // OutputDebugStringA((LPCSTR)buf);
  136. // printf(buf);
  137. // }
  138. // }
  139. // va_end(arg);
  140. //}
  141. //#define Dbg(__fmt__, ...) __Dbg(vrtp, __fmt__, __VA_ARGS__)
  142. static void get_start_config_bitrate(videortp_config_t *config, int *max_bitrate, int *target_bitrate, int *min_bitrate){
  143. *max_bitrate = config->bit_rate; //bps
  144. *min_bitrate = 50*1000 > config->bit_rate ? config->bit_rate : 50*1000; //bps
  145. *target_bitrate = *max_bitrate; //bps
  146. *target_bitrate = (*target_bitrate < *min_bitrate) ? *min_bitrate : *target_bitrate; //bps
  147. }
  148. static int get_mtu(int config_mtu){
  149. int mtu = config_mtu > MAX_PLAYLOAD_SIZE ? MAX_PLAYLOAD_SIZE : config_mtu;
  150. return mtu;
  151. }
  152. //interval 单位为ms
  153. static unsigned convert_to_rtp_timestamp_increment(int64_t interval) {
  154. // 时间戳增量
  155. unsigned timestampIncrement = (VIDEO_CLOCK/1000*interval);
  156. return timestampIncrement;
  157. }
  158. static void yuv_buffers_combine_to_one(const video_frame *vframe, unsigned char *buffer)
  159. {
  160. int i =0, j =0, k =0;
  161. for(i = 0; i < vframe->height; i++)
  162. {
  163. memcpy((void *)(buffer+vframe->width*i),
  164. (const void *)(vframe->data[0]+vframe->linesize[0]*i),
  165. (size_t)(vframe->width));
  166. }
  167. for(j = 0; j < vframe->height/2; j++)
  168. {
  169. memcpy((void *)(buffer+vframe->width*i+vframe->width/2*j),
  170. (const void *)(vframe->data[1]+vframe->linesize[1]*j),
  171. (size_t)(vframe->width/2));
  172. }
  173. for(k =0; k < vframe->height/2; k++)
  174. {
  175. memcpy((void *)(buffer+vframe->width*i+vframe->width/2*j+vframe->width/2*k),
  176. (const void *)(vframe->data[2]+vframe->linesize[2]*k),
  177. (size_t)(vframe->width/2));
  178. }
  179. }
  180. static rtpframe_part_t *rtpframe_part_create(videortp_t *vrtp)
  181. {
  182. rtpframe_part_t *part;
  183. if (!list_empty((const struct list_head *)(&vrtp->free_part_list))) {
  184. part = list_first_entry(&vrtp->free_part_list, rtpframe_part_t, entry);
  185. list_del((struct list_head *)(&part->entry));
  186. } else {
  187. part = MALLOC_T(rtpframe_part_t);
  188. }
  189. return part;
  190. }
  191. static void rtpframe_part_destroy(videortp_t *vrtp, rtpframe_part_t *part)
  192. {
  193. list_add((struct list_head *)(&part->entry), (struct list_head *)(&vrtp->free_part_list));
  194. }
  195. rtpframe_part_t *rtpframe_part_dupb(rtpframe_part_t *mp){
  196. rtpframe_part_t *part = MALLOC_T(rtpframe_part_t);
  197. if (part){
  198. part->entry = mp->entry;
  199. memcpy((void *)(part->buf), (const void *)(mp->buf), strlen((const char *)(mp->buf)));
  200. part->offset = mp->offset;
  201. part->actual_len = mp->actual_len;
  202. part->mb_in_slice = mp->mb_in_slice;
  203. part->seq = mp->seq;
  204. part->mark = mp->mark;
  205. part->psc = mp->psc;
  206. }
  207. return part;
  208. }
  209. static void rtpframe_clear(videortp_t *vrtp, rtpframe_t *frame)
  210. {
  211. if (frame->used) {
  212. list_splice_init((struct list_head *)(&frame->part_list), (struct list_head *)(&vrtp->free_part_list));
  213. frame->used = 0;
  214. }
  215. }
  216. static unsigned short rtpframe_get_last_seq(rtpframe_t *frame)
  217. {
  218. if (!list_empty((const struct list_head *)(&frame->part_list))) {
  219. rtpframe_part_t *part = list_last_entry(&frame->part_list, rtpframe_part_t, entry);
  220. return part->seq;
  221. } else {
  222. assert(0);
  223. return 0;
  224. }
  225. }
  226. static unsigned short rtpframe_get_first_seq(rtpframe_t *frame)
  227. {
  228. if (!list_empty((const struct list_head *)(&frame->part_list))) {
  229. rtpframe_part_t *part = list_first_entry(&frame->part_list, rtpframe_part_t, entry);
  230. return part->seq;
  231. } else {
  232. assert(0);
  233. return 0;
  234. }
  235. }
  236. static int rtpframe_is_empty(rtpframe_t *frame)
  237. {
  238. if (list_empty((const struct list_head *)(&frame->part_list))) {
  239. return 1;
  240. }
  241. return 0;
  242. }
  243. static __inline void receiver_notify_peer_fast_update(videortp_t *vrtp)
  244. {
  245. DWORD dwNow = GetTickCount();
  246. if (dwNow - vrtp->last_peer_update_tick >= PEER_UPDATE_INTERVAL) {
  247. Dbg("%I64d receiver_notify_peer_fast_update!", TimeInMilliseconds());
  248. rtp_session_send_rtcp_h261_fir(vrtp->rtp_sess);
  249. vrtp->last_peer_update_tick = dwNow;
  250. }
  251. }
  252. static __inline void receiver_notify_peer_fast_update_now(videortp_t *vrtp)
  253. {
  254. DWORD dwNow = GetTickCount();
  255. Dbg("%I64d receiver_notify_peer_fast_update_now!", TimeInMilliseconds());
  256. rtp_session_send_rtcp_h261_fir(vrtp->rtp_sess);
  257. vrtp->last_peer_update_tick = dwNow;
  258. }
  259. static __inline void receiver_force_key_frame(videortp_t *vrtp)
  260. {
  261. Dbg("%I64d receiver_force_key_frame!", TimeInMilliseconds());
  262. InterlockedCompareExchange(&vrtp->force_key_frames, 1, 0);
  263. }
  264. static void receiver_clear_window(videortp_t *vrtp)
  265. {
  266. int i;
  267. for (i = 0; i < FRAME_WIN_SIZE; ++i) {
  268. rtpframe_t *frame = &vrtp->frame_win[i];
  269. rtpframe_clear(vrtp, frame);
  270. }
  271. vrtp->frame_duration = 0;
  272. }
  273. int receiver_msgdsize(const rtpframe_part_t *mp)
  274. {
  275. int msgsize = 0;
  276. {
  277. msgsize += (int) mp->actual_len;
  278. }
  279. return msgsize;
  280. }
  281. int video_coding_on_log(void *userdata, int level, const char* file, int line, const char* fmt, va_list vl){
  282. videortp_t *vrtp = (videortp_t *)userdata;
  283. int n;
  284. n = _vscprintf(fmt, vl);
  285. if ((DEBUG_ENCODER || DEBUG_DECODER) && n > 0 && vrtp && level >= VIDEO_CODING_DEBUG_INFO) {
  286. char *buf = (char*)_alloca((size_t)(n+3));
  287. vsprintf(buf, fmt, vl);
  288. Dbg("%s.", buf);
  289. }
  290. }
  291. static int decoder_process(videortp_t *vrtp, uint8_t *input_buf, int input_len){
  292. int64_t before_decode_ms;
  293. int64_t after_decode_ms;
  294. int64_t before_render_ms;
  295. int64_t after_render_ms;
  296. //decode
  297. while (input_len > 0) {
  298. video_frame *decodered_frame;
  299. int key_frame = 0;
  300. video_debug_write_play_file(AUDIO_DEC_IN, input_buf, input_len);
  301. if(DEBUG_DECODER){
  302. Dbg("%s:%d: receiver_do_decode before decode data_len:%d.", __FILE__, __LINE__, input_len);
  303. }
  304. before_decode_ms = TimeInMilliseconds();
  305. decodered_frame = video_decoder_process(vrtp->decoder, input_buf, input_len, &input_len, &key_frame);
  306. if(DEBUG_DECODER){
  307. Dbg("%s:%d: receiver_do_decode after decode data_len:%d.", __FILE__, __LINE__, input_len);
  308. }
  309. after_decode_ms = TimeInMilliseconds();
  310. if (decodered_frame == NULL){
  311. Dbg("receiver_do_decode decode failed.");
  312. video_stats_receiver_on_decoded_frame(after_decode_ms, after_decode_ms - before_decode_ms, 0);
  313. return 0;
  314. }
  315. vrtp->prev_dec_ms = after_decode_ms;
  316. video_stats_receiver_on_decoded_frame(after_decode_ms, after_decode_ms - before_decode_ms, key_frame);
  317. //debug render file
  318. if (vrtp->config.rx_height)
  319. {
  320. if (VIDEO_FORMAT_RGB24 != decodered_frame->format)
  321. {
  322. unsigned char *video_debug_buf;
  323. int length = vrtp->config.rx_height*vrtp->config.rx_width*3/2;
  324. video_debug_buf = (unsigned char *)malloc(length);
  325. yuv_buffers_combine_to_one(decodered_frame, video_debug_buf);
  326. video_debug_write_play_file(VIDEO_RENDER_IN, video_debug_buf, length);
  327. free(video_debug_buf);
  328. }
  329. }
  330. //notify render
  331. before_render_ms = TimeInMilliseconds();
  332. if(vrtp->config.on_rx_frame){
  333. vrtp->config.on_rx_frame(decodered_frame, vrtp->config.user_data);
  334. }else {
  335. //render is null, we need delete self.
  336. video_frame_delete(decodered_frame);
  337. }
  338. after_render_ms = TimeInMilliseconds();
  339. video_stats_receiver_on_rendered_frame(after_render_ms, after_render_ms - before_render_ms);
  340. }
  341. return input_len == 0;
  342. }
  343. void decoder_create(videortp_t *vrtp, const videortp_config_t *config){
  344. VideoCodingLogCallBack log_func;
  345. DecoderConfig decoder_config;
  346. decoder_config.color_space = VIDEO_FORMAT_RGB24;
  347. decoder_config.decode_id = CODEC_ID_H264;
  348. decoder_config.width = config->rx_width;
  349. decoder_config.height = config->rx_height;
  350. log_func.log_fn = &video_coding_on_log;
  351. log_func.userdata = vrtp;
  352. vrtp->decoder = video_decoder_open(&decoder_config, &log_func);
  353. Dbg("decoder_create color_space: %d decode_id: %d width: %d height: %d.",
  354. decoder_config.color_space, decoder_config.decode_id, decoder_config.width, decoder_config.height);
  355. }
  356. void decoder_destroy(videortp_t *vrtp){
  357. if (vrtp->decoder != NULL) {
  358. video_decoder_close(vrtp->decoder);
  359. }
  360. Dbg("decoder_destroy.");
  361. }
  362. #if 0
  363. #endif
  364. /******************************standard_h264接收处理 start***************************/
  365. static void receiver_standard_h264_update_sps(videortp_t *d, rtpframe_part_t *sps){
  366. if (d->sps){
  367. free((void *)(d->sps));
  368. }
  369. d->sps = rtpframe_part_dupb(sps);
  370. }
  371. static void receiver_standard_h264_update_pps(videortp_t *d, rtpframe_part_t *pps){
  372. if (d->pps){
  373. free((void *)(d->pps));
  374. }
  375. if (pps){
  376. d->pps=rtpframe_part_dupb(pps);
  377. }
  378. else{
  379. d->pps=NULL;
  380. }
  381. }
  382. static bool_t receiver_standard_h264_check_sps_pps_change(videortp_t *d, rtpframe_part_t *sps, rtpframe_part_t *pps){
  383. bool_t ret1=FALSE,ret2=FALSE;
  384. if (d->sps){
  385. if (sps){
  386. ret1=(receiver_msgdsize(sps)!=receiver_msgdsize(d->sps)) ||
  387. (memcmp((const void *)(d->sps->buf),(const void *)(sps->buf),(size_t)receiver_msgdsize(sps))!=0);
  388. if (ret1) {
  389. receiver_standard_h264_update_sps(d,sps);
  390. receiver_standard_h264_update_pps(d,NULL);
  391. }
  392. }
  393. }else if (sps) {
  394. receiver_standard_h264_update_sps(d,sps);
  395. }
  396. if (d->pps){
  397. if (pps){
  398. ret2=(receiver_msgdsize(pps)!=receiver_msgdsize(d->pps)) ||
  399. (memcmp((const void *)(d->pps->buf), (const void *)(pps->buf), (size_t)receiver_msgdsize(pps))!=0);
  400. if (ret2) {
  401. receiver_standard_h264_update_pps(d,pps);
  402. }
  403. }
  404. }else if (pps) {
  405. receiver_standard_h264_update_pps(d,pps);
  406. }
  407. return ret1 || ret2;
  408. }
  409. static int receiver_standard_h264_add_startcode(videortp_t *vrtp, rtpframe_t *frame,
  410. uint8_t *output_buf, bool_t *new_sps_pps)
  411. {
  412. rtpframe_part_t *pos = NULL;
  413. uint8_t *dst = NULL;
  414. bool_t start_picture=TRUE;
  415. int output_len = 0;
  416. dst = output_buf;
  417. list_for_each_entry(pos, &frame->part_list, rtpframe_part_t, entry)
  418. {
  419. x264_hdr *hdr = (x264_hdr*)&pos->buf[pos->offset];
  420. unsigned char* src = (unsigned char*)&pos->buf[pos->offset];
  421. uint8_t nalu_type = hdr->id;
  422. if (nalu_type==NAL_SPS){
  423. *new_sps_pps=receiver_standard_h264_check_sps_pps_change(vrtp,pos,NULL) || *new_sps_pps;
  424. }
  425. if (nalu_type==NAL_PPS){
  426. *new_sps_pps=receiver_standard_h264_check_sps_pps_change(vrtp,NULL,pos) || *new_sps_pps;
  427. }
  428. if (start_picture || nalu_type==NAL_SPS || nalu_type==NAL_PPS ){
  429. *dst++=0;
  430. start_picture=FALSE;
  431. }
  432. *dst++ = 0;
  433. *dst++ = 0;
  434. *dst++ = 1;
  435. *dst++=*src++;
  436. while(src < (unsigned char*)&(pos->buf[pos->offset]) + pos->actual_len - 3){
  437. if (src[0]==0 && src[1]==0 && src[2]<3){
  438. *dst++=0;
  439. *dst++=0;
  440. *dst++=3;
  441. src+=2;
  442. }
  443. *dst++=*src++;
  444. }
  445. *dst++=*src++;
  446. *dst++=*src++;
  447. *dst++=*src++;
  448. }
  449. output_len = dst - output_buf;
  450. return output_len;
  451. }
  452. static int receiver_standard_h264_add_encoded_buffer_startcode(videortp_t *vrtp, EncodedImage *encoded_image,
  453. uint8_t *output_buf)
  454. {
  455. uint8_t *dst = NULL;
  456. bool_t start_picture=TRUE;
  457. int output_len = 0;
  458. int i = 0;
  459. dst = output_buf;
  460. for (i = 0; i < encoded_image->fragmentation_header_.fragmentationVectorSize; i++)
  461. {
  462. x264_hdr *hdr = (x264_hdr*)&encoded_image->encoded_data_[encoded_image->fragmentation_header_.fragmentationOffset[i]];
  463. unsigned char* src = (unsigned char*)&encoded_image->encoded_data_[encoded_image->fragmentation_header_.fragmentationOffset[i]];
  464. uint8_t nalu_type = hdr->id;
  465. if (start_picture || nalu_type==NAL_SPS || nalu_type==NAL_PPS){
  466. *dst++=0;
  467. start_picture=FALSE;
  468. }
  469. *dst++ = 0;
  470. *dst++ = 0;
  471. *dst++ = 1;
  472. *dst++=*src++;
  473. while(src < (unsigned char*)&encoded_image->encoded_data_[encoded_image->fragmentation_header_.fragmentationOffset[i]] +
  474. encoded_image->fragmentation_header_.fragmentationLength[i] - 3){
  475. if (src[0]==0 && src[1]==0 && src[2]<3){
  476. *dst++=0;
  477. *dst++=0;
  478. *dst++=3;
  479. src+=2;
  480. }
  481. *dst++=*src++;
  482. }
  483. *dst++=*src++;
  484. *dst++=*src++;
  485. *dst++=*src++;
  486. }
  487. output_len = dst - output_buf;
  488. return output_len;
  489. }
  490. static int receiver_standard_h264_calculate_mb_in_slice(char* psrc, size_t ulen)
  491. {
  492. int ret = -1;
  493. bs_t bs_data;
  494. if (NULL == psrc || 0 == ulen){
  495. return ret;
  496. }
  497. bs_init(&bs_data, psrc, ulen);
  498. ret = bs_read_ue(&bs_data);
  499. return ret;
  500. }
  501. static int receiver_standard_h264_append_rtpframe_part(videortp_t *rtp, rtpframe_t *frame,
  502. unsigned ts, unsigned key, rtpframe_part_t *new_part)
  503. {
  504. if (frame->used && frame->ts != ts)
  505. {
  506. rtpframe_clear(rtp, frame);
  507. }
  508. if (frame->used == 0){
  509. frame->ts = ts;
  510. frame->key = key;
  511. frame->cur_max_mb = 0;
  512. }
  513. if (frame->cur_max_mb <= new_part->mb_in_slice)
  514. {
  515. frame->cur_max_mb = new_part->mb_in_slice;
  516. list_add_tail(&new_part->entry, &frame->part_list);
  517. frame->used++;
  518. }
  519. else
  520. {
  521. rtpframe_part_t *pos;
  522. unsigned short temp_seq;
  523. list_for_each_entry(pos, &frame->part_list, rtpframe_part_t, entry)
  524. {
  525. if (pos->mb_in_slice > new_part->mb_in_slice)
  526. {
  527. break;
  528. }
  529. }
  530. temp_seq = new_part->seq;
  531. new_part->seq = pos->seq;
  532. pos->seq = temp_seq;
  533. __list_add(&new_part->entry, pos->entry.prev, &pos->entry);
  534. frame->used++;
  535. }
  536. return 1;
  537. }
  538. //ts不同, 一帧结束,返回此帧
  539. static int receiver_standard_h264_find_frame(videortp_t *rtp, rtpframe_part_t* part_data,
  540. unsigned mark, unsigned ts, unsigned key)
  541. {
  542. int i = rtp->frame_win_start;
  543. if (rtp->frame_win[i].ts == ts)
  544. {
  545. receiver_standard_h264_append_rtpframe_part(rtp, &rtp->frame_win[i], ts, key, part_data);
  546. return -1;
  547. }
  548. else{
  549. int index = (rtp->frame_win_start + 1)%FRAME_WIN_SIZE;
  550. rtpframe_t *frame = &rtp->frame_win[i];
  551. receiver_standard_h264_append_rtpframe_part(rtp, &rtp->frame_win[index], ts, key, part_data);
  552. rtp->frame_win_start = index;
  553. return i;
  554. }
  555. }
  556. static int receiver_standard_h264_on_jbuffer_request_key_frame(void *userdata){
  557. videortp_t *vrtp = (videortp_t *)userdata;
  558. if (vrtp) {
  559. receiver_notify_peer_fast_update_now((vrtp));
  560. }
  561. }
  562. static int receiver_h264_on_receive_encoded_image(EncodedImage *encoded_image,
  563. unsigned int timestamp, unsigned short first_seq, unsigned short last_seq, void *userdata){
  564. videortp_t *vrtp = (videortp_t *)userdata;
  565. if (vrtp) {
  566. uint8_t *input_buf = NULL;
  567. int input_len = 0;
  568. int i = 0;
  569. int decoded;
  570. if(DEBUG_RX){
  571. Dbg("%s:%d: receiver_h264_on_receive_encoded_image timestamp:%u first_seq:%u last_seq:%u key: %d len: %d.", __FILE__, __LINE__,
  572. timestamp, first_seq, last_seq, encoded_image->key_frame, encoded_image->size_);
  573. Dbg("%s:%d: receiver_h264_on_receive_encoded_image fragmentationSize: %d.", __FILE__, __LINE__,
  574. encoded_image->fragmentation_header_.fragmentationVectorSize);
  575. for (i = 0;i < encoded_image->fragmentation_header_.fragmentationVectorSize;++i){
  576. Dbg("%s:%d: receiver_h264_on_receive_encoded_image index: %d fragmentationLength: %d fragmentationOffset: %d.", __FILE__, __LINE__,
  577. i, encoded_image->fragmentation_header_.fragmentationLength[i], encoded_image->fragmentation_header_.fragmentationOffset[i]);
  578. }
  579. }
  580. if (encoded_image->key_frame || vrtp->prev_dec_seq+1 == first_seq) {
  581. input_len = encoded_image->size_ + MAX_ASSEMBLE_EXTRA_SIZE;
  582. input_buf = (uint8_t*)_alloca(input_len);
  583. memset(input_buf, 0, input_len);
  584. //00->003,同时加上startcode
  585. if (encoded_image->pt_ == REC_COMMON_VIDEO_PT){
  586. memcpy(input_buf, encoded_image->encoded_data_, encoded_image->size_);
  587. input_len = encoded_image->size_;
  588. } else {
  589. if (vrtp->h264_packetizer){
  590. int status;
  591. unsigned int whole_len = 0;
  592. for (i=0; i<encoded_image->fragmentation_header_.fragmentationVectorSize; ++i) {
  593. if (whole_len + encoded_image->fragmentation_header_.fragmentationLength[i] > input_len) {
  594. return 0;
  595. }
  596. status = h264_unpacketize( vrtp->h264_packetizer,
  597. &encoded_image->encoded_data_[encoded_image->fragmentation_header_.fragmentationOffset[i]],
  598. encoded_image->fragmentation_header_.fragmentationLength[i],
  599. input_buf,
  600. input_len,
  601. &whole_len);
  602. if (status != 0) {
  603. continue;
  604. }
  605. }
  606. input_len = whole_len;
  607. }else {
  608. input_len = receiver_standard_h264_add_encoded_buffer_startcode(vrtp, encoded_image, input_buf);
  609. }
  610. }
  611. if(DEBUG_RX){
  612. Dbg("%s:%d: receiver_h264_on_receive_encoded_image encoded_size:%d frame_len:%d now:%I64d.", __FILE__, __LINE__,
  613. encoded_image->size_, input_len, TimeInMilliseconds());
  614. }
  615. //decode
  616. decoded = decoder_process(vrtp, input_buf, input_len);
  617. if (decoded) {
  618. vrtp->prev_dec_seq = last_seq;
  619. vrtp->prev_dec_ts = timestamp;
  620. } else {
  621. Dbg("receiver_h264_on_receive_encoded_image decode_frame failed!");
  622. }
  623. }
  624. }
  625. return 0;
  626. }
  627. static int receiver_standard_h264_decode(videortp_t *vrtp, rtpframe_t *frame)
  628. {
  629. if (frame->used) {
  630. rtpframe_part_t *pos = NULL;
  631. int got_picture = 0;
  632. uint8_t *input_buf = NULL;
  633. int input_len = 0;
  634. input_buf = (uint8_t*)_alloca(frame->used * MAX_RECV_BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
  635. memset(input_buf, 0, frame->used * MAX_RECV_BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
  636. //00->003,同时加上startcode
  637. {
  638. bool_t need_reinit=FALSE;
  639. input_len = receiver_standard_h264_add_startcode(vrtp, frame, input_buf, &need_reinit);
  640. }
  641. if(DEBUG_RX){
  642. Dbg("%s:%d: receiver_standard_h264_decode frame_used:%d frame_len:%d now:%I64d.", __FILE__, __LINE__, frame->used, input_len, TimeInMilliseconds());
  643. }
  644. //decode
  645. return decoder_process(vrtp, input_buf, input_len);
  646. }
  647. return 0;
  648. }
  649. rtpframe_t *receiver_standard_h264_assemble(videortp_t *vrtp,
  650. rtpframe_part_t *part_data, int len,
  651. unsigned short seq, unsigned mark, unsigned ts){
  652. int ret = -1;
  653. int iret = -1;
  654. rtpframe_t *frame = NULL;
  655. int key = 0;
  656. x264_hdr *hdr = (x264_hdr*)&part_data->buf[0];
  657. uint8_t nalu_type = hdr->id;
  658. if(NAL_SPS == nalu_type || NAL_PPS == nalu_type){
  659. part_data->mb_in_slice = 0;
  660. key = 1;
  661. }else{
  662. part_data->mb_in_slice = receiver_standard_h264_calculate_mb_in_slice(&part_data->buf[1], part_data->actual_len - 1);
  663. }
  664. if (NAL_SLICE_IDR == nalu_type){
  665. key = 1;
  666. }
  667. part_data->actual_len = len;
  668. part_data->offset = 0;
  669. part_data->mark = mark;
  670. part_data->seq = seq;
  671. if(DEBUG_RX){
  672. Dbg("%s:%d: receiver_standard_h264_assemble actual_len:%d seq:%d key:%d.", __FILE__, __LINE__, len, seq, key);
  673. }
  674. iret = receiver_standard_h264_find_frame(vrtp, part_data, mark, ts, key);
  675. if (iret != -1) {
  676. return &vrtp->frame_win[iret];
  677. }
  678. return NULL;
  679. }
  680. static int receiver_process_standard_h264_packet(
  681. videortp_t *vrtp, rtpframe_part_t *part_data, int len,
  682. unsigned short seq, unsigned mark, unsigned ts, unsigned pt)
  683. {
  684. #if 1
  685. VideoJBufferPacketInfo packet_info = {0};
  686. x264_hdr *hdr = (x264_hdr*)&part_data->buf[part_data->offset];
  687. uint8_t nalu_type = NAL_UNKNOWN;
  688. int actual_len = part_data->actual_len;
  689. int offset = part_data->offset;
  690. packet_info.length = actual_len;
  691. packet_info.packet_type = NORMAL_PACKET_IN_FRAME;
  692. if(mark){
  693. packet_info.packet_type = LAST_PACKET_IN_FRAME;
  694. }
  695. packet_info.seq = seq;
  696. packet_info.timestamp = ts;
  697. nalu_type = hdr->id;
  698. if (vrtp->h264_packetizer) {
  699. h264_unpacketize_get_original_nal_type(vrtp->h264_packetizer, &part_data->buf[offset], actual_len, &nalu_type);
  700. }
  701. if(NAL_SPS == nalu_type || NAL_PPS == nalu_type || NAL_SLICE_IDR == nalu_type){
  702. packet_info.is_key = 1;
  703. }
  704. packet_info.pt = pt;
  705. if(DEBUG_RX){
  706. Dbg("%s:%d: receiver_process_standard_h264_packet len:%d seq:%d mark:%d ts:%d nalu_type:%u offset:%d actual_len:%d.", __FILE__, __LINE__,
  707. len, seq, mark, ts, nalu_type, offset, actual_len);
  708. }
  709. video_jbuffer_api_receive_packet(vrtp->jbuffer, &part_data->buf[offset], &packet_info);
  710. rtpframe_part_destroy(vrtp, part_data);
  711. #else
  712. rtpframe_t *frame = NULL;
  713. frame = receiver_standard_h264_assemble(vrtp, part_data, len, seq, mark, ts);
  714. if (frame != NULL) {
  715. int decoded = 0;
  716. //取出的frame可能为空(在第一次收数据时),需要先判空
  717. if (!rtpframe_is_empty(frame)
  718. && (frame->key || vrtp->prev_dec_seq+1 == rtpframe_get_first_seq(frame))){
  719. decoded = receiver_standard_h264_decode(vrtp, frame);
  720. if (decoded) {
  721. //Dbg("decode_frame ok!");
  722. if (vrtp->frame_duration==0 && vrtp->prev_dec_seq+1 == rtpframe_get_first_seq(frame)) {
  723. vrtp->frame_duration = frame->ts - vrtp->prev_dec_ts;
  724. Dbg("decode frame duration: %d", vrtp->frame_duration);
  725. }
  726. vrtp->prev_dec_seq = rtpframe_get_last_seq(frame);
  727. vrtp->prev_dec_ts = frame->ts;
  728. } else {
  729. Dbg("decode_frame failed!");
  730. }
  731. }
  732. rtpframe_clear(vrtp, frame);
  733. }
  734. #endif
  735. return 0;
  736. }
  737. /******************************standard_h264接收处理 end***************************/
  738. #if 0
  739. #endif
  740. /******************************custom_h264接收处理 start***************************/
  741. static int receiver_custom_h264_check_rtpframe_integrated(rtpframe_t *frame)
  742. {
  743. if (!list_empty((const struct list_head *)(&frame->part_list))) {
  744. rtpframe_part_t *first = list_first_entry(&frame->part_list, rtpframe_part_t, entry);
  745. rtpframe_part_t *last = list_last_entry(&frame->part_list, rtpframe_part_t, entry);
  746. if (first->psc && last->mark) {
  747. rtpframe_part_t *pos;
  748. unsigned short seq = first->seq;
  749. list_for_each_entry(pos, &frame->part_list, rtpframe_part_t, entry) {
  750. if (seq == pos->seq) {
  751. ++seq;
  752. } else {
  753. return 0;
  754. }
  755. }
  756. return 1;
  757. }
  758. }
  759. return 0;
  760. }
  761. static int receiver_custom_h264_check_rtpframe_partleft(rtpframe_t *frame)
  762. {
  763. if (!list_empty((const struct list_head *)(&frame->part_list))) {
  764. rtpframe_part_t *first = list_first_entry(&frame->part_list, rtpframe_part_t, entry);
  765. rtpframe_part_t *last = list_last_entry(&frame->part_list, rtpframe_part_t, entry);
  766. if (last->mark && (0 != first->psc)) {
  767. return 1;
  768. }
  769. }
  770. return 0;
  771. }
  772. //根据ts查找缓存rtpframe_t位置
  773. static rtpframe_t *receiver_custom_h264_find_rtpframe(videortp_t *rtp, unsigned ts)
  774. {
  775. if (rtp->frame_duration == 0) {
  776. return &rtp->frame_win[rtp->frame_win_ptr];
  777. } else {
  778. unsigned int frame_win_duration = rtp->frame_duration*FRAME_WIN_SIZE;
  779. if (RTP_SEQ_GT(ts, rtp->prev_dec_ts, frame_win_duration)) {
  780. unsigned int idx = (ts - rtp->prev_dec_ts) / rtp->frame_duration;
  781. idx = (rtp->frame_win_ptr + idx + FRAME_WIN_SIZE - 1) % FRAME_WIN_SIZE;
  782. return &rtp->frame_win[idx];
  783. }
  784. }
  785. return NULL;
  786. }
  787. static int receiver_custom_h264_append_rtpframe_part(videortp_t *rtp, rtpframe_t *frame, unsigned key, unsigned ts, rtpframe_part_t *new_part)
  788. {
  789. if (frame->used && frame->ts != ts) {
  790. rtpframe_clear(rtp, frame);
  791. }
  792. if (frame->used == 0) {
  793. frame->ts = ts;
  794. frame->key = key;
  795. } else {
  796. rtpframe_part_t *pos;
  797. if (frame->used >= 1 && !key) {
  798. OutputDebugStringA("a");
  799. }
  800. list_for_each_entry(pos, &frame->part_list, rtpframe_part_t, entry) {
  801. if (pos->seq == new_part->seq) {
  802. return 0;
  803. } else if (RTP_SEQ_GT(pos->seq, new_part->seq, RTP_MAX_JUMP)) {
  804. __list_add(&new_part->entry, pos->entry.prev, &pos->entry);
  805. frame->used++;
  806. return 1;
  807. } else if (RTP_SEQ_GT(new_part->seq, pos->seq, RTP_MAX_JUMP)) {
  808. continue;
  809. } else {
  810. return 0;
  811. }
  812. }
  813. }
  814. list_add_tail(&new_part->entry, &frame->part_list);
  815. frame->used++;
  816. return 1;
  817. }
  818. static int receiver_custom_h264_decode(videortp_t *vrtp, rtpframe_t *frame)
  819. {
  820. if (frame->used) {
  821. rtpframe_part_t *pos = NULL;
  822. int got_picture = 0;
  823. uint8_t *input_buf = NULL;
  824. int input_len = 0;
  825. input_buf = (uint8_t*)_alloca(frame->used * MAX_RECV_BUFFER_SIZE+FF_INPUT_BUFFER_PADDING_SIZE);
  826. list_for_each_entry(pos, &frame->part_list, rtpframe_part_t, entry) {
  827. memcpy(input_buf+input_len, &pos->buf[pos->offset], pos->actual_len);
  828. input_len += pos->actual_len;
  829. }
  830. memset(input_buf+input_len, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  831. if(DEBUG_RX){
  832. Dbg("%s:%d: receiver_custom_h264_decode frame_used:%d frame_len:%d now:%I64d.", __FILE__, __LINE__, frame->used, input_len, TimeInMilliseconds());
  833. }
  834. //decode
  835. return decoder_process(vrtp, input_buf, input_len);
  836. }
  837. return 0;
  838. }
  839. rtpframe_t *receiver_custom_h264_assemble(videortp_t *vrtp,
  840. rtpframe_part_t *part_data, int len,
  841. unsigned short seq, unsigned mark, unsigned ts){
  842. h26x_hdr *hdr = (h26x_hdr*)&part_data->buf[0];
  843. char *raw_data = (char*)(hdr + 1);
  844. rtpframe_t *frame = NULL;
  845. int actual_len = len - sizeof(h26x_hdr) + 2;
  846. int appended;
  847. int key = hdr->key;
  848. int sno = hdr->id;
  849. int end = hdr->end;
  850. if(DEBUG_RX){
  851. Dbg("%s:%d: receiver_custom_h264_assemble actual_len:%d seq:%d key:%d sno:%d end: %d.", __FILE__, __LINE__, actual_len, seq, !!key, sno, end);
  852. }
  853. part_data->actual_len = actual_len;
  854. part_data->offset = sizeof(h26x_hdr)-2;
  855. part_data->mark = mark;
  856. part_data->seq = seq;
  857. part_data->psc = (sno == 0);
  858. frame = receiver_custom_h264_find_rtpframe(vrtp, ts);
  859. if (!frame) {
  860. receiver_clear_window(vrtp);
  861. frame = &vrtp->frame_win[vrtp->frame_win_ptr];
  862. }
  863. appended = receiver_custom_h264_append_rtpframe_part(vrtp, frame, key, ts, part_data);
  864. if (!appended) {
  865. rtpframe_part_destroy(vrtp, part_data);
  866. } else if(receiver_custom_h264_check_rtpframe_integrated(frame)) {
  867. return frame;
  868. }
  869. return NULL;
  870. }
  871. static int receiver_process_custom_h264_packet(videortp_t *vrtp,
  872. rtpframe_part_t *part_data, int len,
  873. unsigned short seq, unsigned mark, unsigned ts, unsigned pt)
  874. {
  875. #if 1
  876. VideoJBufferPacketInfo packet_info = {0};
  877. h26x_hdr *hdr = (h26x_hdr*)&part_data->buf[part_data->offset];
  878. int actual_len = part_data->actual_len - sizeof(h26x_hdr) + 2;
  879. int key = hdr->key;
  880. int sno = hdr->id;
  881. int end = hdr->end;
  882. int offset = part_data->offset + sizeof(h26x_hdr)-2;
  883. packet_info.length = actual_len;
  884. packet_info.packet_type = NORMAL_PACKET_IN_FRAME;
  885. if (sno == 0){
  886. packet_info.packet_type = FIRST_PACKET_IN_FRAME;
  887. }
  888. if(end){
  889. packet_info.packet_type = LAST_PACKET_IN_FRAME;
  890. }
  891. packet_info.seq = seq;
  892. packet_info.timestamp = ts;
  893. packet_info.is_key = key;
  894. packet_info.pt = pt;
  895. if(DEBUG_RX){
  896. Dbg("%s:%d: receiver_process_custom_h264_packet len:%d seq:%d mark:%d ts:%d pt:%u key:%d sno:%d end:%d offset:%d actual_len:%d.", __FILE__, __LINE__,
  897. len, seq, mark, ts, pt, key, sno, end, offset, actual_len);
  898. }
  899. video_jbuffer_api_receive_packet(vrtp->jbuffer, &part_data->buf[offset], &packet_info);
  900. rtpframe_part_destroy(vrtp, part_data);
  901. #else
  902. rtpframe_t *frame = NULL;
  903. if(DEBUG_RX){
  904. Dbg("%s:%d: receiver_process_custom_h264_packet len:%d seq:%d mark:%d ts:%d.", __FILE__, __LINE__, len, seq, mark, ts);
  905. }
  906. frame = receiver_custom_h264_assemble(vrtp, part_data, len, seq, mark, ts);
  907. if (frame != NULL) {
  908. int decoded;
  909. do {
  910. decoded = 0;
  911. if (frame->key || vrtp->prev_dec_seq+1 == rtpframe_get_first_seq(frame)) {
  912. decoded = receiver_custom_h264_decode(vrtp, frame);
  913. if (decoded) {
  914. if (vrtp->frame_duration==0 && vrtp->prev_dec_seq+1 == rtpframe_get_first_seq(frame)) {
  915. vrtp->frame_duration = frame->ts - vrtp->prev_dec_ts;
  916. Dbg("%s:%d: receiver_process_custom_h264_packet decode frame duration: %d.", __FILE__, __LINE__, vrtp->frame_duration);
  917. }
  918. vrtp->prev_dec_seq = rtpframe_get_last_seq(frame);
  919. vrtp->prev_dec_ts = frame->ts;
  920. } else {
  921. Dbg("%s:%d: receiver_process_custom_h264_packet decode_frame failed!", __FILE__, __LINE__);
  922. }
  923. rtpframe_clear(vrtp, frame);
  924. vrtp->frame_win_ptr = (frame->id+1) % FRAME_WIN_SIZE;
  925. frame = &vrtp->frame_win[vrtp->frame_win_ptr];
  926. } else {
  927. if (!frame->key) {
  928. receiver_notify_peer_fast_update(vrtp);
  929. }
  930. }
  931. } while (decoded && frame->used && receiver_custom_h264_check_rtpframe_integrated(frame));
  932. }
  933. #endif
  934. return 0;
  935. }
  936. /******************************custom_h264接收处理 end***************************/
  937. #if 0
  938. #endif
  939. static void receiver_process_rtcp_packet(videortp_t *vrtp, unsigned rtcp_flags){
  940. if (rtcp_flags & RTP_SESSION_HAS_FIR){
  941. receiver_force_key_frame(vrtp);
  942. }
  943. if (rtcp_flags & RTP_SESSION_HAS_RTPFB_TMMBR) {
  944. rtcp_statistics rtcp_stats = {0};
  945. rtp_session_get_rtcp_stat(vrtp->rtp_sess, &rtcp_stats);
  946. sim_recv_bitrate_feedback(rtcp_stats.tmmbr_max_bitrate);
  947. vrtp->recv_cc_feedback_ms = TimeInMilliseconds();
  948. vrtp->recv_cc_feedback = TRUE;
  949. vrtp->remote_support_cc = TRUE;
  950. }
  951. if ((rtcp_flags & RTP_SESSION_HAS_RR) || (rtcp_flags & RTP_SESSION_HAS_SR)) {
  952. rtcp_statistics rtcp_stats = {0};
  953. rtp_session_get_rtcp_stat(vrtp->rtp_sess, &rtcp_stats);
  954. sim_update_rtt((uint32_t)(rtcp_stats.rtt*1000));
  955. sim_recv_fraction_loss_feedback(rtcp_stats.fraction_lost, rtcp_stats.report_block_last_number_of_packets);
  956. }
  957. }
  958. static unsigned int __stdcall recv_proc(void *arg)
  959. {
  960. videortp_t *vrtp = (videortp_t*)arg;
  961. int rtp_timeout_cnt = 0;
  962. int64_t pre_500_ms = TimeInMilliseconds();
  963. Dbg("recv_proc.");
  964. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  965. receiver_notify_peer_fast_update_now(vrtp);
  966. for (;;) {
  967. #ifdef _WIN32
  968. DWORD dwRet = WaitForSingleObject(vrtp->evt, 10);
  969. if (dwRet == WAIT_TIMEOUT)
  970. #else
  971. struct timespec ts;
  972. clock_gettime(CLOCK_REALTIME, &ts);
  973. ts.tv_nsec += 1000 * 1000 * 10;
  974. //sem_getvalue(&m_semt, &ivalue);
  975. if (-1 == sem_timedwait(&vrtp->sem_evt, &ts) && (ETIMEDOUT == errno))
  976. #endif
  977. {
  978. int n;
  979. {
  980. unsigned rtcp_flags = 0;
  981. int result = rtp_session_recv_rtcp(vrtp->rtp_sess, &rtcp_flags);
  982. if (result >= 0) {
  983. receiver_process_rtcp_packet(vrtp, rtcp_flags);
  984. }
  985. }
  986. do {
  987. unsigned short seq = 0;
  988. unsigned mark = 0;
  989. unsigned extension = 0;
  990. unsigned ts = 0;
  991. unsigned pt = 0;
  992. rtp_hdr hdr = {0};
  993. rtpframe_part_t *part_data = rtpframe_part_create(vrtp);
  994. rtp_session_t *rtp_sess = vrtp->rtp_sess;
  995. part_data->actual_len = 0;
  996. part_data->mark = 0;
  997. part_data->psc = 0;
  998. part_data->seq = 0;
  999. part_data->offset = 0;
  1000. part_data->mb_in_slice = -1;
  1001. n = rtp_session_recv_hook2(rtp_sess, &hdr, part_data->buf, sizeof(part_data->buf), vrtp->config.on_rx_udp, vrtp->config.user_data);
  1002. seq = ntohs(hdr.seq);
  1003. mark = hdr.m;
  1004. extension = hdr.x;
  1005. ts = ntohl(hdr.ts);
  1006. pt = hdr.pt;
  1007. #if 0 // for testing
  1008. #define PACKET_LOSS_RATIO 30
  1009. if (n > 0 && rand()%1000 >= PACKET_LOSS_RATIO) {
  1010. Dbg("rtp_session_recv_hook pt = %u, mark = %u, ts = %u, seq = %u, size = %d", pt, mark, ts, seq, n);
  1011. #else
  1012. if (n > 0) {
  1013. #endif
  1014. {
  1015. uint32_t send_time = 0;
  1016. if (vrtp->rtp_header_extension && extension){
  1017. int extension_length = 0;
  1018. rtp_header_extension_api_decode_absolute_send_time(vrtp->rtp_header_extension,
  1019. (uint8_t *)part_data->buf, n, &send_time, &extension_length);
  1020. part_data->actual_len = n - extension_length;
  1021. part_data->offset = extension_length;
  1022. if(DEBUG_RX){
  1023. Dbg("%s:%d: recv_proc rtp_header_extension send_time:%u length:%d actual_len:%d offset:%d.",
  1024. __FILE__, __LINE__, send_time, extension_length,
  1025. part_data->actual_len, part_data->offset);
  1026. }
  1027. }else {
  1028. part_data->actual_len = n;
  1029. part_data->offset = 0;
  1030. }
  1031. //huchen add for video cc
  1032. {
  1033. sim_segment_t seg = {0};
  1034. seg.transport_seq = seq;
  1035. //注意,cc中的ts是以真实时间毫秒为单位,rtp的时间戳是90000为1秒,这里需要转换
  1036. seg.timestamp = (send_time==0 ? (ts/(VIDEO_CLOCK/1000)) : send_time);
  1037. seg.data_size = n;
  1038. sim_recv_video(&seg);
  1039. }
  1040. }
  1041. video_stats_bandwidth_update_recv_rtp_bytes(n);
  1042. video_stats_receiver_on_incoming_packet(TimeInMilliseconds());
  1043. if (REC_COMMON_VIDEO_PT == pt){
  1044. receiver_process_custom_h264_packet(vrtp, part_data, n, seq, mark, ts, pt);
  1045. }else{
  1046. receiver_process_standard_h264_packet(vrtp, part_data, n, seq, mark, ts, pt);
  1047. }
  1048. rtp_timeout_cnt = 0;
  1049. } else {
  1050. rtpframe_part_destroy(vrtp, part_data);
  1051. }
  1052. } while (n > 0);
  1053. {
  1054. //1s没有解码到视频数据,请求I帧
  1055. int64_t now_ms = TimeInMilliseconds();
  1056. if (now_ms - vrtp->prev_dec_ms >= 1000){
  1057. Dbg("recv_proc now:%I64d > prev_dec_ms:%I64d 1s.", TimeInMilliseconds(), vrtp->prev_dec_ms);
  1058. receiver_notify_peer_fast_update_now(vrtp);
  1059. vrtp->prev_dec_ms = now_ms;
  1060. }
  1061. if (now_ms - pre_500_ms >= 500){
  1062. //发送流控信令,表明接收端支持拥塞控制,让发送端发送加上send time(rtp header extension)
  1063. if (vrtp->send_cc_feedback == FALSE){
  1064. int max_bitrate, target_bitrate, min_bitrate;
  1065. get_start_config_bitrate(&vrtp->config, &max_bitrate, &target_bitrate, &min_bitrate);
  1066. rtp_session_send_rtcp_fb_tmmbr(vrtp->rtp_sess, target_bitrate);
  1067. }
  1068. pre_500_ms = now_ms;
  1069. }
  1070. }
  1071. } else {
  1072. break;
  1073. }
  1074. }
  1075. return 0;
  1076. }
  1077. #if 0
  1078. #endif
  1079. /******************************custom_h264发送处理 start***************************/
  1080. static void sender_custom_h264_packetize_and_send(videortp_t *vrtp, int key, unsigned pt, const uint8_t *buf, int n)
  1081. {
  1082. const char *ptr = (const char*)buf;
  1083. int left = n;
  1084. unsigned delta_ts = vrtp->delta_ts;
  1085. int id = 0;
  1086. int mtu = get_mtu(vrtp->config.mtu);
  1087. mtu = mtu-20-8-12-sizeof(h26x_hdr)+2; // ip hdr: 20, udp hdr: 8, rtp hdr: 12
  1088. if(DEBUG_TX){
  1089. Dbg("%s:%d: sender_custom_h264_packetize_and_send key: %d len: %d delta_ts: %d now: %I64d.",
  1090. __FILE__, __LINE__, key, n, delta_ts, TimeInMilliseconds());
  1091. }
  1092. video_debug_write_record_file(VIDEO_ENC_OUT, buf, n);
  1093. while (left > 0) {
  1094. int rc;
  1095. char tx_buf[MAX_PLAYLOAD_SIZE];
  1096. h26x_hdr *hdr = (h26x_hdr*)&tx_buf[0];
  1097. unsigned rtcp_flag;
  1098. int tn = min(left, mtu);
  1099. unsigned mark = (tn == left);
  1100. hdr->key = !!key;
  1101. hdr->end = mark;
  1102. hdr->id = id++;
  1103. memcpy((void *)(&tx_buf[0]+sizeof(h26x_hdr)-2), (const void *)ptr, (size_t)tn);
  1104. if (DEBUG_TX) {
  1105. Dbg("end = %d, id = %d, tn = %d", hdr->end, hdr->id, tn);
  1106. }
  1107. rc = rtp_session_send_hook(vrtp->rtp_sess, &rtcp_flag, pt, mark, delta_ts, tx_buf, tn+sizeof(h26x_hdr)-2, vrtp->config.on_tx_udp, vrtp->config.user_data);
  1108. if (rc == 0) {
  1109. receiver_process_rtcp_packet(vrtp, rtcp_flag);
  1110. delta_ts = 0;
  1111. left -= tn;
  1112. ptr += tn;
  1113. } else {
  1114. break;
  1115. }
  1116. }
  1117. }
  1118. static void sender_custom_h264_send_fragment(videortp_t *vrtp, int index, int key_frame, unsigned mark, unsigned pt, uint8_t *fragment, int length)
  1119. {
  1120. char tx_buf[MAX_PLAYLOAD_SIZE] = {0};
  1121. video_debug_write_record_file(VIDEO_ENC_OUT, fragment, length);
  1122. video_stats_bandwidth_update_send_rtp_bytes(length);
  1123. video_stats_sender_on_sent_packet(TimeInMilliseconds());
  1124. if (MAX_PLAYLOAD_SIZE > length + sizeof(h26x_hdr)-2 + 32/*rtp_header_extension_length*/){
  1125. int rc;
  1126. unsigned rtcp_flag;
  1127. h26x_hdr *hdr;
  1128. int rtp_extension = 0;
  1129. char rtp_header_extension_buf[32] = {0};
  1130. int rtp_header_extension_length = 0;
  1131. unsigned int delta_ts = vrtp->delta_ts;
  1132. if(DEBUG_TX){
  1133. Dbg("%s:%d: sender_custom_h264_send_fragment mark: %d length: %d delta_ts: %d now: %I64d.",
  1134. __FILE__, __LINE__, mark, length, delta_ts, TimeInMilliseconds());
  1135. }
  1136. //rtp_header_extension
  1137. if (vrtp->rtp_header_extension && vrtp->remote_support_cc){
  1138. uint32_t interval_ms = TimeInMilliseconds() - vrtp->rtp_start_ms;
  1139. rtp_header_extension_api_encode_absolute_send_time(vrtp->rtp_header_extension,
  1140. interval_ms, (uint8_t *)rtp_header_extension_buf, &rtp_header_extension_length);
  1141. memcpy((void *)(&tx_buf[0]), (const void *)rtp_header_extension_buf, (size_t)rtp_header_extension_length);
  1142. rtp_extension = 1;
  1143. if(DEBUG_TX){
  1144. Dbg("%s:%d: sender_custom_h264_send_fragment rtp_header_extension interval_ms:%u length:%d.", __FILE__, __LINE__, interval_ms, rtp_header_extension_length);
  1145. }
  1146. }
  1147. //custom header
  1148. hdr = (h26x_hdr*)&tx_buf[rtp_header_extension_length];
  1149. hdr->key = !!key_frame;
  1150. hdr->end = mark;
  1151. hdr->id = index;
  1152. //playload
  1153. memcpy((void *)(&tx_buf[rtp_header_extension_length]+sizeof(h26x_hdr)-2), (const void *)fragment, (size_t)length);
  1154. { rtp_hdr rtp_hdr;
  1155. rtp_state *rtp_state;
  1156. rtp_state = rtp_session_get_rtp_state(vrtp->rtp_sess);
  1157. rtp_state_fill_rtp(rtp_state, &rtp_hdr, pt, mark, delta_ts);
  1158. rtp_hdr.x = rtp_extension;
  1159. rc = rtp_session_send_hook2(vrtp->rtp_sess, &rtcp_flag, &rtp_hdr,
  1160. tx_buf, length+sizeof(h26x_hdr)-2+rtp_header_extension_length,
  1161. vrtp->config.on_tx_udp, vrtp->config.user_data);
  1162. if (rc == 0) {
  1163. receiver_process_rtcp_packet(vrtp, rtcp_flag);
  1164. }
  1165. }
  1166. }
  1167. }
  1168. /******************************custom_h264发送处理 end***************************/
  1169. /******************************standard_h264发送处理 start***************************/
  1170. static int sender_standard_h264_send_packet(videortp_t *vrtp, unsigned mark, unsigned pt, const uint8_t *packet, int length)
  1171. {
  1172. char tx_buf[MAX_PLAYLOAD_SIZE] = {0};
  1173. if (MAX_PLAYLOAD_SIZE > length + 32/*rtp_header_extension_length*/){
  1174. int rc;
  1175. unsigned rtcp_flag;
  1176. int rtp_extension = 0;
  1177. char rtp_header_extension_buf[32] = {0};
  1178. int rtp_header_extension_length = 0;
  1179. unsigned int delta_ts = vrtp->delta_ts;
  1180. if(DEBUG_TX){
  1181. Dbg("%s:%d: sender_standard_h264_send_packet mark: %d length: %d delta_ts: %d now: %I64d.",
  1182. __FILE__, __LINE__, mark, length, delta_ts, TimeInMilliseconds());
  1183. }
  1184. //rtp_header_extension
  1185. if (vrtp->rtp_header_extension && vrtp->remote_support_cc){
  1186. uint32_t interval_ms = TimeInMilliseconds() - vrtp->rtp_start_ms;
  1187. rtp_header_extension_api_encode_absolute_send_time(vrtp->rtp_header_extension,
  1188. interval_ms, (uint8_t *)rtp_header_extension_buf, &rtp_header_extension_length);
  1189. memcpy(&tx_buf[0], rtp_header_extension_buf, rtp_header_extension_length);
  1190. rtp_extension = 1;
  1191. if(DEBUG_TX){
  1192. Dbg("%s:%d: sender_standard_h264_send_packet rtp_header_extension interval_ms:%u length:%d.", __FILE__, __LINE__, interval_ms, rtp_header_extension_length);
  1193. }
  1194. }
  1195. //playload
  1196. memcpy(&tx_buf[rtp_header_extension_length], packet, length);
  1197. {
  1198. rtp_hdr rtp_hdr;
  1199. rtp_state *rtp_state;
  1200. rtp_state = rtp_session_get_rtp_state(vrtp->rtp_sess);
  1201. rtp_state_fill_rtp(rtp_state, &rtp_hdr, pt, mark, delta_ts);
  1202. rtp_hdr.x = rtp_extension;
  1203. rc = rtp_session_send_hook2(vrtp->rtp_sess, &rtcp_flag, &rtp_hdr,
  1204. tx_buf, length + rtp_header_extension_length,
  1205. vrtp->config.on_tx_udp, vrtp->config.user_data);
  1206. if (rc == 0) {
  1207. receiver_process_rtcp_packet(vrtp, rtcp_flag);
  1208. }
  1209. }
  1210. }
  1211. return 0;
  1212. }
  1213. // unsigned short id : 5;
  1214. // unsigned short end : 2;
  1215. // unsigned short key : 1;
  1216. static int sender_standard_h264_send_nal(videortp_t *vrtp, unsigned mark, unsigned pt, uint8_t *nal_payload, int length)
  1217. {
  1218. video_debug_write_record_file(VIDEO_ENC_OUT, nal_payload, length);
  1219. video_stats_bandwidth_update_send_rtp_bytes(length);
  1220. video_stats_sender_on_sent_packet(TimeInMilliseconds());
  1221. if(vrtp->h264_packetizer){
  1222. const uint8_t *payload;
  1223. size_t payload_len;
  1224. int status;
  1225. unsigned tmp_mark;
  1226. //h264_packetize func change nal_payload, so we need copy it to tx_buf first, let nal_payload unchanged.
  1227. unsigned int processed = 0;
  1228. uint8_t *tx_buf = (uint8_t*)_alloca(length);
  1229. memcpy(tx_buf, nal_payload, length);
  1230. while(processed < length){
  1231. status = h264_packetize(vrtp->h264_packetizer, (uint8_t *)tx_buf, length, &processed, &payload, &payload_len);
  1232. if (status != 0) {
  1233. return status;
  1234. }
  1235. if(DEBUG_TX){
  1236. Dbg("%s:%d: sender_standard_h264_send_nal mark: %d processed: %u payload_len: %d.",
  1237. __FILE__, __LINE__, mark, processed, payload_len);
  1238. }
  1239. //input mark =1, means last nal, rtp mark = 1, we need last nal 's last packet.
  1240. if (mark && (processed >= length)){
  1241. tmp_mark = 1;
  1242. } else {
  1243. tmp_mark = 0;
  1244. }
  1245. sender_standard_h264_send_packet(vrtp, tmp_mark, pt, payload, payload_len);
  1246. }
  1247. } else {
  1248. int tn = length;
  1249. int start_code_length = 0;
  1250. //comment, remove nal start code
  1251. if (nal_payload && nal_payload[0] == 0 && nal_payload[1] == 0 && nal_payload[2] == 0 && nal_payload[3] == 1) {
  1252. start_code_length = 4;
  1253. if (length - start_code_length > 0) {
  1254. tn = length - start_code_length;
  1255. } else {
  1256. return -1;
  1257. }
  1258. }
  1259. else if (nal_payload && nal_payload[0] == 0 && nal_payload[1] == 0 && nal_payload[2] == 1) {
  1260. start_code_length = 3;
  1261. if (length - start_code_length > 0) {
  1262. tn = length - start_code_length;
  1263. } else {
  1264. return -1;
  1265. }
  1266. }
  1267. sender_standard_h264_send_packet(vrtp, mark, pt, nal_payload + start_code_length, tn);
  1268. }
  1269. return 0;
  1270. }
  1271. static void sender_standard_h264_packetize_x264_nals(videortp_t *vrtp, unsigned pt, x264_nal_t *xnals, int num_nals)
  1272. {
  1273. int i;
  1274. if(DEBUG_TX){
  1275. Dbg("%s:%d: sender_standard_h264_packetize_x264_nals num_nals: %d.", __FILE__, __LINE__, num_nals);
  1276. }
  1277. for (i = 0;i < num_nals;++i){
  1278. unsigned mark = 0;
  1279. x264_nal_t* nal = &xnals[i];
  1280. if (xnals[i].i_type == NAL_SPS) {
  1281. if (DEBUG_TX) {
  1282. Dbg("A SPS is being sent.");
  1283. }
  1284. }else if (xnals[i].i_type == NAL_PPS) {
  1285. if (DEBUG_TX) {
  1286. Dbg("A PPS is being sent.");
  1287. }
  1288. }else if (xnals[i].i_type == NAL_SLICE_IDR) {
  1289. if (DEBUG_TX) {
  1290. Dbg("A IDR is being sent.");
  1291. }
  1292. }
  1293. if (i == num_nals -1){
  1294. mark = 1;
  1295. if (DEBUG_TX) {
  1296. Dbg("A frame end.");
  1297. }
  1298. }
  1299. sender_standard_h264_send_nal(vrtp, mark , pt, nal->p_payload, nal->i_payload);
  1300. }
  1301. }
  1302. void sender_h264_packetize_nal(videortp_t *vrtp, int index, int total, int key_frame, unsigned pt, uint8_t *data, int data_size){
  1303. int i;
  1304. unsigned mark = 0;
  1305. if(DEBUG_TX){
  1306. Dbg("%s:%d: sender_h264_packetize_nal index: %d total: %d key_frame: %d data_size: %d.", __FILE__, __LINE__,
  1307. index, total, key_frame, data_size);
  1308. }
  1309. if (index == total -1){
  1310. mark = 1;
  1311. if(DEBUG_TX){
  1312. Dbg("A frame end.");
  1313. }
  1314. }
  1315. //pt=97 rtp ts = vrtp->delta_ts
  1316. //pt=101 rtp ts += vrtp->delta_ts
  1317. if (index == 0){
  1318. if (pt == REC_COMMON_VIDEO_PT){
  1319. vrtp->delta_ts = VIDEO_CLOCK * vrtp->config.fps_den / vrtp->config.fps_num;
  1320. } else {
  1321. vrtp->delta_ts += VIDEO_CLOCK * vrtp->config.fps_den / vrtp->config.fps_num;
  1322. }
  1323. }else {
  1324. if (pt == REC_COMMON_VIDEO_PT){
  1325. vrtp->delta_ts = 0;
  1326. } else {
  1327. //do nothing
  1328. }
  1329. }
  1330. if (pt == REC_COMMON_VIDEO_PT){
  1331. sender_custom_h264_send_fragment(vrtp, index, key_frame, mark, pt, data, data_size);
  1332. } else {
  1333. sender_standard_h264_send_nal(vrtp, mark, pt, data, data_size);
  1334. }
  1335. }
  1336. /******************************standard_h264发送处理 end***************************/
  1337. #if 0
  1338. #endif
  1339. /******************************congestion control处理 start***************************/
  1340. int congestion_control_on_log(void *userdata, int level, const char* file, int line, const char* fmt, va_list vl){
  1341. videortp_t *vrtp = (videortp_t *)userdata;
  1342. int n;
  1343. n = _vscprintf(fmt, vl);
  1344. if (DEBUG_CC && n > 0 && level >= 1 && vrtp) {
  1345. char *buf = (char*)_alloca((size_t)(n+3));
  1346. vsprintf(buf, fmt, vl);
  1347. Dbg("%s.", buf);
  1348. }
  1349. }
  1350. /* 发送端回调。运行在sim_heartbeat方法调用线程。sim_send_video->cc缓存,然后sim_heartbeat->pacing判断可以发送->回调 */
  1351. void congestion_control_sender_on_send_fragment(sim_segment_t* seg, void *userdata){
  1352. videortp_t *vrtp = (videortp_t *)userdata;
  1353. if(DEBUG_TX){
  1354. Dbg("%s:%d: congestion_control_sender_on_send_fragment.", __FILE__, __LINE__);
  1355. }
  1356. sender_h264_packetize_nal(vrtp, seg->index, seg->total, seg->key_frame, seg->payload_type, seg->data, seg->data_size);
  1357. }
  1358. /* 发送端回调。运行在sim_heartbeat方法调用线程。 sim_heartbeat->cc判断带宽估计是否变化->回调 */
  1359. /* 或者sim_recv_bitrate_feedback调用线程 . sim_recv_bitrate_feedback->cc判断带宽估计是否变化->回调 */
  1360. /*bw 估计码率,单位:kbps*/
  1361. void congestion_control_sender_on_change_bitrate(uint32_t bw, int lost, void *userdata){
  1362. videortp_t *vrtp = (videortp_t *)userdata;
  1363. if(DEBUG_CC){
  1364. Dbg("%s:%d: congestion_control_sender_on_change_bitrate bw: %d lost: %d.", __FILE__, __LINE__, bw, lost);
  1365. }
  1366. //回调时编码器可能未创建
  1367. if (vrtp->encoder) {
  1368. video_encoder_api_on_bitrate_updated(vrtp->encoder, bw*1000, lost, 0);
  1369. }
  1370. }
  1371. /* 接收端回调。运行在sim_heartbeat方法调用线程,sim_heartbeat->cc判断需要发送remb->回调 */
  1372. void congestion_control_receiver_on_send_bitrate_feedback(uint32_t estimate_bitrate, void *userdata){
  1373. videortp_t *vrtp = (videortp_t *)userdata;
  1374. if(DEBUG_CC){
  1375. Dbg("%s:%d: congestion_control_receiver_on_send_bitrate_feedback estimate_bitrate: %d.", __FILE__, __LINE__, estimate_bitrate);
  1376. }
  1377. video_stats_receiver_on_report_cc_bitrate(estimate_bitrate);
  1378. rtp_session_send_rtcp_fb_tmmbr(vrtp->rtp_sess, estimate_bitrate);
  1379. vrtp->send_cc_feedback = TRUE;
  1380. }
  1381. void congestion_control_create(videortp_t *vrtp, const videortp_config_t *config){
  1382. int max_bitrate, target_bitrate, min_bitrate;
  1383. get_start_config_bitrate(config, &max_bitrate, &target_bitrate, &min_bitrate);
  1384. {
  1385. sim_callback_t callback = {0};
  1386. callback.userdata = vrtp;
  1387. callback.log_cb = &congestion_control_on_log;
  1388. callback.send_fragment_cb = &congestion_control_sender_on_send_fragment;
  1389. callback.change_bitrate_cb = &congestion_control_sender_on_change_bitrate;
  1390. callback.send_bitrate_feedback_cb = &congestion_control_receiver_on_send_bitrate_feedback;
  1391. sim_init(gcc_transport, 0, min_bitrate, target_bitrate, max_bitrate, &callback);
  1392. }
  1393. Dbg("congestion_control_create min_bitrate: %d target_bitrate: %d max_bitrate: %d.", min_bitrate, target_bitrate, max_bitrate);
  1394. }
  1395. void congestion_control_destroy(videortp_t *vrtp){
  1396. sim_destroy();
  1397. Dbg("congestion_control_destroy.");
  1398. }
  1399. /******************************congestion control处理 end***************************/
  1400. #if 0
  1401. #endif
  1402. /******************************x264 encoder处理 start***************************/
  1403. #ifndef IDR_INTERVAL
  1404. #define IDR_INTERVAL 8
  1405. #endif
  1406. #ifndef NAL_TIMESTAP_ENC
  1407. #define NAL_TIMESTAP_ENC 3000
  1408. #endif
  1409. #ifndef SEND_WIDTH
  1410. #define SEND_WIDTH 320
  1411. #endif
  1412. #ifndef SEND_HEIGHT
  1413. #define SEND_HEIGHT 320
  1414. #endif
  1415. #ifndef SEND_FPS
  1416. #define SEND_FPS 15
  1417. #endif
  1418. #ifndef SEND_BITRATE
  1419. #define SEND_BITRATE 180*1000
  1420. #endif
  1421. #ifndef RC_MARGIN
  1422. #define RC_MARGIN 10000
  1423. #endif
  1424. #define DEFAULT_MAX_PAYLOAD_SIZE 1440
  1425. static int max_payload_size = DEFAULT_MAX_PAYLOAD_SIZE;
  1426. int x264_encoder_get_payload_max_size(){
  1427. return max_payload_size;
  1428. }
  1429. static void x264_encoder_set_linephone_param(x264_param_t* params)
  1430. {
  1431. float bitrate;
  1432. int csp = X264_CSP_I420;
  1433. int iframerate = REC_COMMON_VIDEO_FPS_NUM;
  1434. params->i_threads=1;
  1435. params->i_sync_lookahead=0;
  1436. params->i_width = SEND_WIDTH;
  1437. params->i_height = SEND_HEIGHT;
  1438. params->i_fps_num=(int)iframerate;
  1439. params->i_fps_den=1;
  1440. params->i_slice_max_size=x264_encoder_get_payload_max_size()-100; /*-100 security margin*/
  1441. params->i_level_idc=13;
  1442. bitrate=(float)SEND_BITRATE*0.92;
  1443. if (bitrate>RC_MARGIN)
  1444. bitrate-=RC_MARGIN;
  1445. #ifndef ANDROID
  1446. params->rc.i_rc_method = X264_RC_ABR;
  1447. params->rc.i_bitrate=(int)(bitrate/1000);
  1448. params->rc.f_rate_tolerance=0.1;
  1449. params->rc.i_vbv_max_bitrate=(int) ((bitrate+RC_MARGIN/2)/1000);
  1450. params->rc.i_vbv_buffer_size=params->rc.i_vbv_max_bitrate;
  1451. params->rc.f_vbv_buffer_init=0.5;
  1452. #else
  1453. params.rc.i_rc_method = X264_RC_CQP;
  1454. params.rc.i_bitrate=(int)(bitrate/1000);
  1455. #endif
  1456. params->rc.i_lookahead=0;
  1457. params->b_repeat_headers=1;
  1458. params->b_annexb=0;
  1459. //these parameters must be set so that our stream is baseline
  1460. params->analyse.b_transform_8x8 = 0;
  1461. params->b_cabac = 0;
  1462. params->i_cqm_preset = X264_CQM_FLAT;
  1463. params->i_bframe = 0;
  1464. params->analyse.i_weighted_pred = X264_WEIGHTP_NONE;
  1465. }
  1466. static void x264_encoder_set_param_t(x264_param_t* params)
  1467. {
  1468. float bitrate;
  1469. int csp = X264_CSP_I420;
  1470. int iframerate = REC_COMMON_VIDEO_FPS_NUM;
  1471. x264_param_default(params);
  1472. x264_param_default_preset(params, "slow" , "zerolatency" );
  1473. params->i_threads=1;
  1474. params->i_sync_lookahead=0;
  1475. params->i_width = SEND_WIDTH;
  1476. params->i_height = SEND_HEIGHT;
  1477. params->i_fps_num = iframerate;
  1478. params->i_fps_den = 1;
  1479. params->i_slice_max_size=x264_encoder_get_payload_max_size()-100; /*-100 security margin*/
  1480. bitrate=(float)SEND_BITRATE*0.92;
  1481. if (bitrate>RC_MARGIN){
  1482. bitrate-=RC_MARGIN;
  1483. }
  1484. // rc
  1485. params->rc.i_rc_method = X264_RC_ABR;
  1486. params->rc.i_bitrate = (int)bitrate/1000;
  1487. //must i_vbv_max_bitrate <= i_bitrate reconfig available
  1488. params->rc.i_vbv_max_bitrate = (int)((bitrate)/1000) ;
  1489. params->rc.i_vbv_buffer_size = (int)((bitrate*2)/1000) ;
  1490. params->rc.f_vbv_buffer_init=0.5;
  1491. params->rc.b_mb_tree=0;//
  1492. params->rc.f_rf_constant = 25;
  1493. params->rc.f_rf_constant_max = 45;
  1494. params->rc.f_rate_tolerance=0.1;
  1495. params->rc.b_stat_write = 1;
  1496. params->rc.i_lookahead=0;
  1497. params->i_keyint_max = iframerate * 2;
  1498. params->i_keyint_min = iframerate * 2;
  1499. params->b_repeat_headers = 1; //
  1500. params->b_annexb= 1;
  1501. params->b_cabac = 1;
  1502. params->i_cqm_preset = X264_CQM_FLAT;
  1503. params->i_bframe = 0;
  1504. params->analyse.i_weighted_pred = X264_WEIGHTP_NONE;
  1505. params->i_csp=csp;
  1506. params->i_level_idc = 30;
  1507. x264_param_apply_profile(params, x264_profile_names[0]);
  1508. params->i_log_level = X264_LOG_WARNING;
  1509. }
  1510. void x264_encoder_create(videortp_t *vrtp, const videortp_config_t *config){
  1511. x264_param_t params = {0};
  1512. x264_param_t params_print = {0};
  1513. x264_encoder_set_param_t(&params);
  1514. vrtp->enc_params = x264_encoder_open(&params);
  1515. x264_encoder_parameters(vrtp->enc_params, &params_print);
  1516. Dbg("x264_encoder_create bit_rate: %d kb/s, i_rc_method: %d ", params_print.rc.i_bitrate, params_print.rc.i_rc_method);
  1517. Dbg("x264_encoder_create i_vbv_max_bitrate: %d kb/s, i_vbv_buffer_size: %d ", params_print.rc.i_vbv_max_bitrate, params_print.rc.i_vbv_buffer_size);
  1518. Dbg("x264_encoder_create keyint_max: %d, i_keyint_min: %d ", params_print.i_keyint_max, params_print.i_keyint_min);
  1519. }
  1520. void x264_encoder_destroy(videortp_t *vrtp){
  1521. if (vrtp->enc_params){
  1522. x264_encoder_close(vrtp->enc_params);
  1523. }
  1524. Dbg("x264_encoder_destroy.");
  1525. }
  1526. /******************************x264 encoder处理 end***************************/
  1527. #if 0
  1528. #endif
  1529. /******************************ffmpeg encoder处理 start***************************/
  1530. void ffmpeg_encoder_on_encoder_encoded_image(const EncodedImage *encoded_image, void *userdata){
  1531. int i;
  1532. videortp_t *vrtp = (videortp_t *)userdata;
  1533. if (encoded_image != NULL && vrtp != NULL) {
  1534. if(DEBUG_TX){
  1535. Dbg("%s:%d: ffmpeg_encoder_on_encoder_encoded_image key: %d len: %d qp: %d, PT:%u.", __FILE__, __LINE__,
  1536. encoded_image->key_frame, encoded_image->size_, encoded_image->qp_, encoded_image->pt_);
  1537. Dbg("%s:%d: ffmpeg_encoder_on_encoder_encoded_image encode_start_ms: %I64d encode_finish_ms: %I64d fragmentationSize: %d.", __FILE__, __LINE__,
  1538. encoded_image->encode_start_ms, encoded_image->encode_finish_ms, encoded_image->fragmentation_header_.fragmentationVectorSize);
  1539. }
  1540. if(DEBUG_TX){
  1541. for (i = 0;i < encoded_image->fragmentation_header_.fragmentationVectorSize;++i){
  1542. Dbg("%s:%d: ffmpeg_encoder_on_encoder_encoded_image index: %d fragmentationLength: %d.", __FILE__, __LINE__,
  1543. i, encoded_image->fragmentation_header_.fragmentationLength[i]);
  1544. }
  1545. }
  1546. video_stats_sender_on_encoded_frame(encoded_image->encode_finish_ms,
  1547. encoded_image->encode_finish_ms - encoded_image->encode_start_ms, encoded_image->key_frame);
  1548. //采用cc控制发送
  1549. if(vrtp->remote_support_cc){
  1550. sim_send_video((EncodedImage *)encoded_image);
  1551. }
  1552. //不采用cc直接发送
  1553. else {
  1554. int use_fragment_send = 1;
  1555. //采用新分片发送
  1556. if (use_fragment_send){
  1557. for (i = 0;i < encoded_image->fragmentation_header_.fragmentationVectorSize;++i){
  1558. sender_h264_packetize_nal(vrtp, i,
  1559. encoded_image->fragmentation_header_.fragmentationVectorSize,
  1560. encoded_image->key_frame,
  1561. encoded_image->pt_,
  1562. &(encoded_image->encoded_data_[encoded_image->fragmentation_header_.fragmentationOffset[i]]),
  1563. encoded_image->fragmentation_header_.fragmentationLength[i]);
  1564. }
  1565. }
  1566. //采用旧分片发送
  1567. else {
  1568. if (encoded_image->pt_ == REC_COMMON_VIDEO_PT){
  1569. sender_custom_h264_packetize_and_send(vrtp, encoded_image->key_frame, encoded_image->pt_,
  1570. encoded_image->encoded_data_, encoded_image->size_);
  1571. } else {
  1572. for (i = 0;i < encoded_image->fragmentation_header_.fragmentationVectorSize;++i){
  1573. sender_h264_packetize_nal(vrtp, i,
  1574. encoded_image->fragmentation_header_.fragmentationVectorSize,
  1575. encoded_image->key_frame,
  1576. encoded_image->pt_,
  1577. &(encoded_image->encoded_data_[encoded_image->fragmentation_header_.fragmentationOffset[i]]),
  1578. encoded_image->fragmentation_header_.fragmentationLength[i]);
  1579. }
  1580. }
  1581. }
  1582. }
  1583. }
  1584. }
  1585. void ffmpeg_encoder_create(videortp_t *vrtp, const videortp_config_t *config){
  1586. int max_bitrate, target_bitrate, min_bitrate;
  1587. VideoEncoderObserver video_encoder_observer = {0};
  1588. VideoEncoderConfig encoder_config = {0};
  1589. VideoCodingLogCallBack log_func = {0};
  1590. get_start_config_bitrate(config, &max_bitrate, &target_bitrate, &min_bitrate);
  1591. video_encoder_observer.OnEncodedImage = &ffmpeg_encoder_on_encoder_encoded_image;
  1592. video_encoder_observer.userdata = vrtp;
  1593. log_func.log_fn = &video_coding_on_log;
  1594. log_func.userdata = vrtp;
  1595. vrtp->encoder = video_encoder_api_new(&video_encoder_observer, &log_func);
  1596. encoder_config.color_space = VIDEO_FORMAT_I420;
  1597. encoder_config.encode_id = CODEC_ID_H264;
  1598. encoder_config.width = config->tx_width;
  1599. encoder_config.height = config->tx_height;
  1600. encoder_config.max_bitrate = max_bitrate/1000; //kbps
  1601. encoder_config.target_bitrate = target_bitrate/1000; //kbps
  1602. encoder_config.min_bitrate = min_bitrate/1000; //kbps
  1603. encoder_config.max_framerate = config->fps_num;
  1604. encoder_config.target_framerate = config->fps_num;
  1605. encoder_config.min_framerate = config->fps_num > 3 ? 3 : config->fps_num;
  1606. encoder_config.key_frame_interval = config->fps_num * 2;
  1607. encoder_config.target_qp = 24;
  1608. encoder_config.max_qp = 37;
  1609. encoder_config.min_qp = 10;
  1610. video_encoder_api_configure_encoder(vrtp->encoder, &encoder_config, get_mtu(config->mtu) - 5/*padding*/ - ((sizeof(h26x_hdr)-2 + 32/*rtp_header_extension_length*/)));
  1611. Dbg("ffmpeg_encoder_create color_space: %d encode_id: %d width: %d height: %d.",
  1612. encoder_config.color_space, encoder_config.encode_id, encoder_config.width, encoder_config.height);
  1613. Dbg("ffmpeg_encoder_create max_bitrate: %d min_bitrate: %d target_bitrate: %d.",
  1614. max_bitrate, min_bitrate, target_bitrate);
  1615. Dbg("ffmpeg_encoder_create min_framerate: %d key_frame_interval: %d target_qp: %d.",
  1616. encoder_config.min_framerate, encoder_config.key_frame_interval, encoder_config.target_qp);
  1617. }
  1618. void ffmpeg_encoder_destory(videortp_t *vrtp){
  1619. if (vrtp->encoder != NULL) {
  1620. video_encoder_api_stop(vrtp->encoder);
  1621. video_encoder_api_destroy(vrtp->encoder);
  1622. }
  1623. Dbg("ffmpeg_encoder_destory.");
  1624. }
  1625. /******************************ffmpeg encoder处理 end***************************/
  1626. #if 0
  1627. #endif
  1628. /******************************jitter buffer处理 start***************************/
  1629. int jitter_buffer_on_log(void *userdata, int level, const char* file, int line, const char* fmt, va_list vl){
  1630. videortp_t *vrtp = (videortp_t *)userdata;
  1631. int n;
  1632. n = _vscprintf(fmt, vl);
  1633. if (DEBUG_RX && n > 0 && vrtp && level >= VIDEO_JBUFFER_DEBUG_TRACE) {
  1634. char *buf = (char*)_alloca((size_t)(n+3));
  1635. vsprintf(buf, fmt, vl);
  1636. Dbg("%s.", buf);
  1637. }
  1638. }
  1639. void jitter_buffer_create(videortp_t *vrtp, const videortp_config_t *config){
  1640. VideoJBufferObserver video_jbuffer_observer;
  1641. VideoJBufferLogCallBack log_func = {0};
  1642. video_jbuffer_observer.OnReceiveEncodedImage = &receiver_h264_on_receive_encoded_image;
  1643. video_jbuffer_observer.RequestKeyFrame = &receiver_standard_h264_on_jbuffer_request_key_frame;
  1644. video_jbuffer_observer.userdata = vrtp;
  1645. log_func.log_fn = &jitter_buffer_on_log;
  1646. log_func.userdata = vrtp;
  1647. vrtp->jbuffer = video_jbuffer_api_new(&video_jbuffer_observer, &log_func);
  1648. Dbg("jitter_buffer_create.");
  1649. }
  1650. void jitter_buffer_destory(videortp_t *vrtp){
  1651. if (vrtp->jbuffer != NULL) {
  1652. video_jbuffer_api_destroy(vrtp->jbuffer);
  1653. }
  1654. Dbg("jitter_buffer_destory.");
  1655. }
  1656. /******************************jitter buffer处理 end***************************/
  1657. static rtp_session_t *videortp_internal_create_rtp_session(const videortp_config_t *config)
  1658. {
  1659. rtp_session_t *rtp_sess;
  1660. struct in_addr addr;
  1661. int rc;
  1662. addr.s_addr = config->local_ip;
  1663. rc = rtp_session_create(inet_ntoa(addr), config->local_rtp_port, 2, &rtp_sess);
  1664. if (rc != 0)
  1665. return 0;
  1666. addr.s_addr = config->remote_ip;
  1667. rtp_session_reset(rtp_sess, config->dir, inet_ntoa(addr), config->remote_rtp_port, config->remote_rtp_port+1);
  1668. {
  1669. // set to a larger recv buffer, so that it will not overflow
  1670. int rtp_fd = -1/*INVALID_SOCKET*/;
  1671. int buf_size = 1<<20;
  1672. rtp_session_get_raw_fd(rtp_sess, &rtp_fd, NULL);
  1673. if (rtp_fd != -1/*INVALID_SOCKET*/) {
  1674. setsockopt(rtp_fd, SOL_SOCKET, SO_RCVBUF, (const char*)&buf_size, sizeof(buf_size));
  1675. setsockopt(rtp_fd, SOL_SOCKET, SO_SNDBUF, (const char*)&buf_size, sizeof(buf_size));
  1676. }
  1677. }
  1678. return rtp_sess;
  1679. }
  1680. int video_stats_on_log(void *userdata, int level, const char* file, int line, const char* fmt, va_list vl){
  1681. videortp_t *vrtp = (videortp_t *)userdata;
  1682. int n;
  1683. n = _vscprintf(fmt, vl);
  1684. if (n > 0 && vrtp) {
  1685. char *buf = (char*)_alloca((size_t)(n+3));
  1686. vsprintf(buf, fmt, vl);
  1687. Dbg("%s.", buf);
  1688. }
  1689. }
  1690. /******************************对外api start***************************/
  1691. int videortp_create(const videortp_config_t *config, videortp_t **p_rtp)
  1692. {
  1693. int i, rc;
  1694. videortp_t *vrtp = ZALLOC_T(videortp_t);
  1695. vrtp->prev_dec_ms = TimeInMilliseconds();
  1696. vrtp->recv_cc_feedback_ms = TimeInMilliseconds();
  1697. vrtp->send_cc_feedback = 0;
  1698. vrtp->recv_cc_feedback = 0;
  1699. vrtp->remote_support_cc = 0;
  1700. memcpy((void *)(&vrtp->config), (const void *)config, sizeof(videortp_config_t));
  1701. Dbg("videortp_create local_pt: %d local_ip: %d local_rtp_port: %d.", config->local_pt, config->local_ip, config->local_rtp_port);
  1702. Dbg("videortp_create remote_pt: %d remote_ip: %d remote_rtp_port: %d.", config->remote_pt, config->remote_ip, config->remote_rtp_port);
  1703. Dbg("videortp_create tx_width: %d tx_height: %d.", config->tx_width, config->tx_height);
  1704. Dbg("videortp_create rx_width: %d rx_height: %d.", config->rx_width, config->rx_height);
  1705. Dbg("videortp_create capture_width: %d capture_height: %d.", config->capture_width, config->capture_height);
  1706. Dbg("videortp_create fps_num: %d bit_rate: %d dir: %d.", config->fps_num, config->bit_rate, config->dir);
  1707. INIT_LIST_HEAD(&vrtp->free_part_list);
  1708. for (i = 0; i < FRAME_WIN_SIZE; ++i) {
  1709. rtpframe_t *frame = &vrtp->frame_win[i];
  1710. INIT_LIST_HEAD(&frame->part_list);
  1711. frame->id = i;
  1712. }
  1713. vrtp->delta_ts = VIDEO_CLOCK * config->fps_den / config->fps_num;
  1714. vrtp->rtp_sess = videortp_internal_create_rtp_session(config);
  1715. if (!vrtp->rtp_sess)
  1716. goto on_error;
  1717. {
  1718. VideoStatsLogCallBack log_func;
  1719. log_func.log_fn = &video_stats_on_log;
  1720. log_func.userdata = vrtp;
  1721. video_stats_init(&log_func);
  1722. }
  1723. jitter_buffer_create(vrtp, config);
  1724. vrtp->rtp_header_extension = rtp_header_extension_api_new();
  1725. if (config->dir & DIR_RX) {
  1726. decoder_create(vrtp, config);
  1727. video_debug_open_play_file();
  1728. }
  1729. if (config->dir & DIR_TX) {
  1730. ffmpeg_encoder_create(vrtp, config);
  1731. video_debug_open_record_file();
  1732. vrtp->framenum = 0;
  1733. }
  1734. congestion_control_create(vrtp, config);
  1735. {
  1736. h264_packetizer_cfg cfg;
  1737. cfg.mtu = get_mtu(config->mtu);
  1738. cfg.mode = H264_PACKETIZER_MODE_NON_INTERLEAVED;
  1739. cfg.unpack_nal_start = 3;
  1740. h264_packetizer_create(&cfg, &(vrtp->h264_packetizer));
  1741. }
  1742. *p_rtp = vrtp;
  1743. return 0;
  1744. on_error:
  1745. videortp_destroy(vrtp);
  1746. return -1;
  1747. }
  1748. void videortp_destroy(videortp_t *vrtp)
  1749. {
  1750. videortp_config_t *config;
  1751. if (!vrtp){
  1752. return;
  1753. }
  1754. config = &vrtp->config;
  1755. Dbg("videortp_destroy.");
  1756. receiver_clear_window(vrtp);
  1757. while (!list_empty(&vrtp->free_part_list)) {
  1758. rtpframe_part_t *part = list_first_entry(&vrtp->free_part_list, rtpframe_part_t, entry);
  1759. list_del(&part->entry);
  1760. free(part);
  1761. }
  1762. congestion_control_destroy(vrtp);
  1763. video_stats_uninit();
  1764. jitter_buffer_destory(vrtp);
  1765. rtp_header_extension_api_destroy(vrtp->rtp_header_extension);
  1766. h264_packetizer_destroy(vrtp->h264_packetizer);
  1767. rtp_session_destroy(vrtp->rtp_sess);
  1768. vrtp->rtp_sess = NULL;
  1769. if (config->dir & DIR_RX) {
  1770. decoder_destroy(vrtp);
  1771. video_debug_close_play_file();
  1772. }
  1773. if (config->dir & DIR_TX) {
  1774. ffmpeg_encoder_destory(vrtp);
  1775. video_debug_close_record_file();
  1776. }
  1777. free(vrtp);
  1778. }
  1779. int videortp_start(videortp_t *vrtp)
  1780. {
  1781. int rc;
  1782. ReceiverConfigStats receiver_config_stats;
  1783. SenderConfigStats sender_config_stats;
  1784. int64_t now = TimeInMilliseconds();
  1785. vrtp->rtp_start_ms = now;
  1786. video_jbuffer_api_start(vrtp->jbuffer);
  1787. if (vrtp->config.dir & DIR_RX) {
  1788. #ifdef _WIN32
  1789. vrtp->evt = CreateEventA(NULL, FALSE, FALSE, NULL);
  1790. vrtp->recv_thread = (HANDLE)_beginthreadex(NULL, 0, &recv_proc, vrtp, 0, NULL);
  1791. #else
  1792. sem_init(&vrtp->sem_evt, 0, 0);
  1793. int err = pthread_create(&vrtp->recv_threadid, NULL, recv_proc, vrtp);
  1794. if (0 == err) {
  1795. Dbg("create vrtp recv thread success, %lu.", vrtp->recv_threadid);
  1796. }
  1797. else {
  1798. Dbg("create vrtp recv thread failed.");
  1799. }
  1800. #endif
  1801. }
  1802. Dbg("videortp_start.");
  1803. receiver_config_stats.remote_pt = vrtp->config.remote_pt;
  1804. receiver_config_stats.local_ip = vrtp->config.local_ip;
  1805. receiver_config_stats.local_rtp_port = vrtp->config.local_rtp_port;
  1806. receiver_config_stats.rx_width = vrtp->config.rx_width;
  1807. receiver_config_stats.rx_height = vrtp->config.rx_height;
  1808. receiver_config_stats.bit_rate = vrtp->config.bit_rate;
  1809. video_stats_receiver_on_started(now, &receiver_config_stats);
  1810. sender_config_stats.local_pt = vrtp->config.local_pt;
  1811. sender_config_stats.remote_ip = vrtp->config.remote_ip;
  1812. sender_config_stats.remote_rtp_port = vrtp->config.remote_rtp_port;
  1813. sender_config_stats.mtu = vrtp->config.mtu;
  1814. sender_config_stats.tx_height = vrtp->config.tx_height;
  1815. sender_config_stats.tx_width = vrtp->config.tx_width;
  1816. sender_config_stats.capture_width = vrtp->config.capture_width;
  1817. sender_config_stats.capture_height = vrtp->config.capture_height;
  1818. sender_config_stats.fps_den = vrtp->config.fps_den;
  1819. sender_config_stats.fps_num = vrtp->config.fps_num;
  1820. sender_config_stats.fps_num = vrtp->config.fps_num;
  1821. sender_config_stats.bit_rate = vrtp->config.bit_rate;
  1822. video_stats_sender_on_started(now, &sender_config_stats);
  1823. return 0;
  1824. }
  1825. void videortp_stop(videortp_t* vrtp)
  1826. {
  1827. int64_t now = TimeInMilliseconds();
  1828. Dbg("start call videortp_stop.");
  1829. #ifdef _WIN32
  1830. if (vrtp->evt) {
  1831. SetEvent(vrtp->evt);
  1832. if (vrtp->recv_thread) {
  1833. WaitForSingleObject(vrtp->recv_thread, INFINITE);
  1834. CloseHandle(vrtp->recv_thread);
  1835. vrtp->recv_thread = NULL;
  1836. }
  1837. CloseHandle(vrtp->evt);
  1838. vrtp->evt = NULL;
  1839. }
  1840. #else
  1841. if (&vrtp->sem_evt) {
  1842. sem_post(&vrtp->sem_evt);
  1843. if (0 != vrtp->recv_threadid) {
  1844. pthread_join(vrtp->recv_threadid, NULL);
  1845. vrtp->recv_threadid = 0;
  1846. }
  1847. sem_destroy(&vrtp->sem_evt);
  1848. }
  1849. #endif
  1850. Dbg("stop rtp recv thread.");
  1851. video_stats_receiver_on_stopped(now);
  1852. video_stats_sender_on_stopped(now);
  1853. video_jbuffer_api_stop(vrtp->jbuffer);
  1854. Dbg("videortp_stop func end.");
  1855. }
  1856. int videortp_send_frame(videortp_t *vrtp, const video_frame *frame)
  1857. {
  1858. if (vrtp && (vrtp->config.dir & DIR_TX)) {
  1859. int64_t now;
  1860. if(DEBUG_TX){
  1861. Dbg("%s:%d: videortp_send_frame width: %d height: %d format: %d.", __FILE__, __LINE__, frame->width, frame->height, frame->format);
  1862. }
  1863. if (VIDEO_FORMAT_RGB24 != frame->format)
  1864. {
  1865. unsigned char *video_debug_buf;
  1866. int length = frame->width*frame->height*3/2;
  1867. video_debug_buf = (unsigned char *)malloc(length);
  1868. yuv_buffers_combine_to_one(frame, video_debug_buf);
  1869. video_debug_write_record_file(VIDEO_CAPTURE_OUT, video_debug_buf, length);
  1870. free(video_debug_buf);
  1871. }
  1872. if (vrtp->force_key_frames) {
  1873. video_encoder_api_send_key_frame(vrtp->encoder);
  1874. vrtp->force_key_frames = 0;
  1875. if(DEBUG_TX){
  1876. Dbg("%s:%d: videortp_send_frame force_key_frames.", __FILE__, __LINE__);
  1877. }
  1878. }
  1879. //在编码器中固定i帧间隔为2s,不再需要自己主动设置了
  1880. #if 0
  1881. else {
  1882. int start_key_interval = vrtp->config.fps_num / vrtp->config.fps_den / 2;
  1883. if (start_key_interval == 0)
  1884. start_key_interval = 1;
  1885. if (vrtp->framenum/start_key_interval <= FIRST_KEY_FRAME_SIZE) {
  1886. if (vrtp->framenum % start_key_interval == 0) {
  1887. video_encoder_api_send_key_frame(vrtp->encoder);
  1888. if(DEBUG_TX){
  1889. Dbg("%s:%d: videortp_send_frame framenum: %d force_key_frames.", __FILE__, __LINE__, vrtp->framenum);
  1890. }
  1891. }
  1892. }
  1893. }
  1894. #endif
  1895. video_encoder_api_on_frame(vrtp->encoder, vrtp->config.local_pt, frame);
  1896. vrtp->framenum++;
  1897. //从未收到cc_feedback估计带宽,远端不支持流量控制,将码率设为配置值
  1898. now = TimeInMilliseconds();
  1899. if ((vrtp->recv_cc_feedback == FALSE) && (now-vrtp->recv_cc_feedback_ms >= 10*1000)){
  1900. Dbg("videortp_send_frame, never receive cc feedback, remote don't support .");
  1901. sim_recv_bitrate_feedback(vrtp->config.bit_rate/*bps*/);
  1902. vrtp->recv_cc_feedback = TRUE;
  1903. }
  1904. } else {
  1905. return -1;
  1906. }
  1907. return 0;
  1908. }
  1909. int videortp_send_yuvframe(videortp_t *vrtp, const video_frame *vframe)
  1910. {
  1911. videortp_send_frame(vrtp, vframe);
  1912. return 0;
  1913. }
  1914. int videortp_reconfig_local_pt(videortp_t *vrtp, unsigned int local_pt){
  1915. Dbg("videortp_reconfig_local_pt:%u .", local_pt);
  1916. vrtp->config.local_pt = local_pt;
  1917. }
  1918. bool videortp_thread_valid(videortp_t* vrtp)
  1919. {
  1920. bool bret = true;
  1921. #ifdef _WIN32
  1922. bret = vrtp->recv_thread != NULL ? true : false;
  1923. #else
  1924. bret = vrtp->recv_threadid != 0 ? true : false;
  1925. #endif
  1926. return bret;
  1927. }
  1928. int videortp_force_key_frame(videortp_t *vrtp)
  1929. {
  1930. int iret = -1;
  1931. if (videortp_thread_valid(vrtp))
  1932. {
  1933. receiver_force_key_frame(vrtp);
  1934. iret = 0;
  1935. }
  1936. return iret;
  1937. }
  1938. /******************************对外api end***************************/