videortp.c 73 KB

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