videortp.c 70 KB

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