rtpdec.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. /*
  2. * RTP input format
  3. * Copyright (c) 2002 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/mathematics.h"
  22. #include "libavutil/avstring.h"
  23. #include "libavutil/time.h"
  24. #include "libavcodec/get_bits.h"
  25. #include "avformat.h"
  26. #include "mpegts.h"
  27. #include "url.h"
  28. #include "network.h"
  29. #include "rtpdec.h"
  30. #include "rtpdec_formats.h"
  31. //#define DEBUG
  32. /* TODO: - add RTCP statistics reporting (should be optional).
  33. - add support for h263/mpeg4 packetized output : IDEA: send a
  34. buffer to 'rtp_write_packet' contains all the packets for ONE
  35. frame. Each packet should have a four byte header containing
  36. the length in big endian format (same trick as
  37. 'ffio_open_dyn_packet_buf')
  38. */
  39. static RTPDynamicProtocolHandler realmedia_mp3_dynamic_handler = {
  40. .enc_name = "X-MP3-draft-00",
  41. .codec_type = AVMEDIA_TYPE_AUDIO,
  42. .codec_id = AV_CODEC_ID_MP3ADU,
  43. };
  44. static RTPDynamicProtocolHandler speex_dynamic_handler = {
  45. .enc_name = "speex",
  46. .codec_type = AVMEDIA_TYPE_AUDIO,
  47. .codec_id = AV_CODEC_ID_SPEEX,
  48. };
  49. /* statistics functions */
  50. static RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
  51. void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
  52. {
  53. handler->next= RTPFirstDynamicPayloadHandler;
  54. RTPFirstDynamicPayloadHandler= handler;
  55. }
  56. void av_register_rtp_dynamic_payload_handlers(void)
  57. {
  58. ff_register_dynamic_payload_handler(&ff_mp4v_es_dynamic_handler);
  59. ff_register_dynamic_payload_handler(&ff_mpeg4_generic_dynamic_handler);
  60. ff_register_dynamic_payload_handler(&ff_amr_nb_dynamic_handler);
  61. ff_register_dynamic_payload_handler(&ff_amr_wb_dynamic_handler);
  62. ff_register_dynamic_payload_handler(&ff_h263_1998_dynamic_handler);
  63. ff_register_dynamic_payload_handler(&ff_h263_2000_dynamic_handler);
  64. ff_register_dynamic_payload_handler(&ff_h263_rfc2190_dynamic_handler);
  65. ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
  66. ff_register_dynamic_payload_handler(&ff_ilbc_dynamic_handler);
  67. ff_register_dynamic_payload_handler(&ff_jpeg_dynamic_handler);
  68. ff_register_dynamic_payload_handler(&ff_vorbis_dynamic_handler);
  69. ff_register_dynamic_payload_handler(&ff_theora_dynamic_handler);
  70. ff_register_dynamic_payload_handler(&ff_qdm2_dynamic_handler);
  71. ff_register_dynamic_payload_handler(&ff_svq3_dynamic_handler);
  72. ff_register_dynamic_payload_handler(&ff_mp4a_latm_dynamic_handler);
  73. ff_register_dynamic_payload_handler(&ff_vp8_dynamic_handler);
  74. ff_register_dynamic_payload_handler(&ff_qcelp_dynamic_handler);
  75. ff_register_dynamic_payload_handler(&realmedia_mp3_dynamic_handler);
  76. ff_register_dynamic_payload_handler(&speex_dynamic_handler);
  77. ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfv_handler);
  78. ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfa_handler);
  79. ff_register_dynamic_payload_handler(&ff_qt_rtp_aud_handler);
  80. ff_register_dynamic_payload_handler(&ff_qt_rtp_vid_handler);
  81. ff_register_dynamic_payload_handler(&ff_quicktime_rtp_aud_handler);
  82. ff_register_dynamic_payload_handler(&ff_quicktime_rtp_vid_handler);
  83. ff_register_dynamic_payload_handler(&ff_g726_16_dynamic_handler);
  84. ff_register_dynamic_payload_handler(&ff_g726_24_dynamic_handler);
  85. ff_register_dynamic_payload_handler(&ff_g726_32_dynamic_handler);
  86. ff_register_dynamic_payload_handler(&ff_g726_40_dynamic_handler);
  87. }
  88. RTPDynamicProtocolHandler *ff_rtp_handler_find_by_name(const char *name,
  89. enum AVMediaType codec_type)
  90. {
  91. RTPDynamicProtocolHandler *handler;
  92. for (handler = RTPFirstDynamicPayloadHandler;
  93. handler; handler = handler->next)
  94. if (!av_strcasecmp(name, handler->enc_name) &&
  95. codec_type == handler->codec_type)
  96. return handler;
  97. return NULL;
  98. }
  99. RTPDynamicProtocolHandler *ff_rtp_handler_find_by_id(int id,
  100. enum AVMediaType codec_type)
  101. {
  102. RTPDynamicProtocolHandler *handler;
  103. for (handler = RTPFirstDynamicPayloadHandler;
  104. handler; handler = handler->next)
  105. if (handler->static_payload_id && handler->static_payload_id == id &&
  106. codec_type == handler->codec_type)
  107. return handler;
  108. return NULL;
  109. }
  110. static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
  111. {
  112. int payload_len;
  113. while (len >= 4) {
  114. payload_len = FFMIN(len, (AV_RB16(buf + 2) + 1) * 4);
  115. switch (buf[1]) {
  116. case RTCP_SR:
  117. if (payload_len < 20) {
  118. av_log(NULL, AV_LOG_ERROR, "Invalid length for RTCP SR packet\n");
  119. return AVERROR_INVALIDDATA;
  120. }
  121. s->last_rtcp_ntp_time = AV_RB64(buf + 8);
  122. s->last_rtcp_timestamp = AV_RB32(buf + 16);
  123. if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
  124. s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
  125. if (!s->base_timestamp)
  126. s->base_timestamp = s->last_rtcp_timestamp;
  127. s->rtcp_ts_offset = s->last_rtcp_timestamp - s->base_timestamp;
  128. }
  129. break;
  130. case RTCP_BYE:
  131. return -RTCP_BYE;
  132. }
  133. buf += payload_len;
  134. len -= payload_len;
  135. }
  136. return -1;
  137. }
  138. #define RTP_SEQ_MOD (1<<16)
  139. /**
  140. * called on parse open packet
  141. */
  142. static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence) // called on parse open packet.
  143. {
  144. memset(s, 0, sizeof(RTPStatistics));
  145. s->max_seq= base_sequence;
  146. s->probation= 1;
  147. }
  148. /**
  149. * called whenever there is a large jump in sequence numbers, or when they get out of probation...
  150. */
  151. static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
  152. {
  153. s->max_seq= seq;
  154. s->cycles= 0;
  155. s->base_seq= seq -1;
  156. s->bad_seq= RTP_SEQ_MOD + 1;
  157. s->received= 0;
  158. s->expected_prior= 0;
  159. s->received_prior= 0;
  160. s->jitter= 0;
  161. s->transit= 0;
  162. }
  163. /**
  164. * returns 1 if we should handle this packet.
  165. */
  166. static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
  167. {
  168. uint16_t udelta= seq - s->max_seq;
  169. const int MAX_DROPOUT= 3000;
  170. const int MAX_MISORDER = 100;
  171. const int MIN_SEQUENTIAL = 2;
  172. /* source not valid until MIN_SEQUENTIAL packets with sequence seq. numbers have been received */
  173. if(s->probation)
  174. {
  175. if(seq==s->max_seq + 1) {
  176. s->probation--;
  177. s->max_seq= seq;
  178. if(s->probation==0) {
  179. rtp_init_sequence(s, seq);
  180. s->received++;
  181. return 1;
  182. }
  183. } else {
  184. s->probation= MIN_SEQUENTIAL - 1;
  185. s->max_seq = seq;
  186. }
  187. } else if (udelta < MAX_DROPOUT) {
  188. // in order, with permissible gap
  189. if(seq < s->max_seq) {
  190. //sequence number wrapped; count antother 64k cycles
  191. s->cycles += RTP_SEQ_MOD;
  192. }
  193. s->max_seq= seq;
  194. } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
  195. // sequence made a large jump...
  196. if(seq==s->bad_seq) {
  197. // two sequential packets-- assume that the other side restarted without telling us; just resync.
  198. rtp_init_sequence(s, seq);
  199. } else {
  200. s->bad_seq= (seq + 1) & (RTP_SEQ_MOD-1);
  201. return 0;
  202. }
  203. } else {
  204. // duplicate or reordered packet...
  205. }
  206. s->received++;
  207. return 1;
  208. }
  209. int ff_rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
  210. {
  211. AVIOContext *pb;
  212. uint8_t *buf;
  213. int len;
  214. int rtcp_bytes;
  215. RTPStatistics *stats= &s->statistics;
  216. uint32_t lost;
  217. uint32_t extended_max;
  218. uint32_t expected_interval;
  219. uint32_t received_interval;
  220. uint32_t lost_interval;
  221. uint32_t expected;
  222. uint32_t fraction;
  223. uint64_t ntp_time= s->last_rtcp_ntp_time; // TODO: Get local ntp time?
  224. if (!s->rtp_ctx || (count < 1))
  225. return -1;
  226. /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
  227. /* XXX: mpeg pts hardcoded. RTCP send every 0.5 seconds */
  228. s->octet_count += count;
  229. rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
  230. RTCP_TX_RATIO_DEN;
  231. rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
  232. if (rtcp_bytes < 28)
  233. return -1;
  234. s->last_octet_count = s->octet_count;
  235. if (avio_open_dyn_buf(&pb) < 0)
  236. return -1;
  237. // Receiver Report
  238. avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
  239. avio_w8(pb, RTCP_RR);
  240. avio_wb16(pb, 7); /* length in words - 1 */
  241. // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
  242. avio_wb32(pb, s->ssrc + 1);
  243. avio_wb32(pb, s->ssrc); // server SSRC
  244. // some placeholders we should really fill...
  245. // RFC 1889/p64
  246. extended_max= stats->cycles + stats->max_seq;
  247. expected= extended_max - stats->base_seq + 1;
  248. lost= expected - stats->received;
  249. lost= FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
  250. expected_interval= expected - stats->expected_prior;
  251. stats->expected_prior= expected;
  252. received_interval= stats->received - stats->received_prior;
  253. stats->received_prior= stats->received;
  254. lost_interval= expected_interval - received_interval;
  255. if (expected_interval==0 || lost_interval<=0) fraction= 0;
  256. else fraction = (lost_interval<<8)/expected_interval;
  257. fraction= (fraction<<24) | lost;
  258. avio_wb32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
  259. avio_wb32(pb, extended_max); /* max sequence received */
  260. avio_wb32(pb, stats->jitter>>4); /* jitter */
  261. if(s->last_rtcp_ntp_time==AV_NOPTS_VALUE)
  262. {
  263. avio_wb32(pb, 0); /* last SR timestamp */
  264. avio_wb32(pb, 0); /* delay since last SR */
  265. } else {
  266. uint32_t middle_32_bits= s->last_rtcp_ntp_time>>16; // this is valid, right? do we need to handle 64 bit values special?
  267. uint32_t delay_since_last= ntp_time - s->last_rtcp_ntp_time;
  268. avio_wb32(pb, middle_32_bits); /* last SR timestamp */
  269. avio_wb32(pb, delay_since_last); /* delay since last SR */
  270. }
  271. // CNAME
  272. avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
  273. avio_w8(pb, RTCP_SDES);
  274. len = strlen(s->hostname);
  275. avio_wb16(pb, (6 + len + 3) / 4); /* length in words - 1 */
  276. avio_wb32(pb, s->ssrc + 1);
  277. avio_w8(pb, 0x01);
  278. avio_w8(pb, len);
  279. avio_write(pb, s->hostname, len);
  280. // padding
  281. for (len = (6 + len) % 4; len % 4; len++) {
  282. avio_w8(pb, 0);
  283. }
  284. avio_flush(pb);
  285. len = avio_close_dyn_buf(pb, &buf);
  286. if ((len > 0) && buf) {
  287. int av_unused result;
  288. av_dlog(s->ic, "sending %d bytes of RR\n", len);
  289. result= ffurl_write(s->rtp_ctx, buf, len);
  290. av_dlog(s->ic, "result from ffurl_write: %d\n", result);
  291. av_free(buf);
  292. }
  293. return 0;
  294. }
  295. void ff_rtp_send_punch_packets(URLContext* rtp_handle)
  296. {
  297. AVIOContext *pb;
  298. uint8_t *buf;
  299. int len;
  300. /* Send a small RTP packet */
  301. if (avio_open_dyn_buf(&pb) < 0)
  302. return;
  303. avio_w8(pb, (RTP_VERSION << 6));
  304. avio_w8(pb, 0); /* Payload type */
  305. avio_wb16(pb, 0); /* Seq */
  306. avio_wb32(pb, 0); /* Timestamp */
  307. avio_wb32(pb, 0); /* SSRC */
  308. avio_flush(pb);
  309. len = avio_close_dyn_buf(pb, &buf);
  310. if ((len > 0) && buf)
  311. ffurl_write(rtp_handle, buf, len);
  312. av_free(buf);
  313. /* Send a minimal RTCP RR */
  314. if (avio_open_dyn_buf(&pb) < 0)
  315. return;
  316. avio_w8(pb, (RTP_VERSION << 6));
  317. avio_w8(pb, RTCP_RR); /* receiver report */
  318. avio_wb16(pb, 1); /* length in words - 1 */
  319. avio_wb32(pb, 0); /* our own SSRC */
  320. avio_flush(pb);
  321. len = avio_close_dyn_buf(pb, &buf);
  322. if ((len > 0) && buf)
  323. ffurl_write(rtp_handle, buf, len);
  324. av_free(buf);
  325. }
  326. /**
  327. * open a new RTP parse context for stream 'st'. 'st' can be NULL for
  328. * MPEG2TS streams to indicate that they should be demuxed inside the
  329. * rtp demux (otherwise AV_CODEC_ID_MPEG2TS packets are returned)
  330. */
  331. RTPDemuxContext *ff_rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, int queue_size)
  332. {
  333. RTPDemuxContext *s;
  334. s = av_mallocz(sizeof(RTPDemuxContext));
  335. if (!s)
  336. return NULL;
  337. s->payload_type = payload_type;
  338. s->last_rtcp_ntp_time = AV_NOPTS_VALUE;
  339. s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
  340. s->ic = s1;
  341. s->st = st;
  342. s->queue_size = queue_size;
  343. rtp_init_statistics(&s->statistics, 0); // do we know the initial sequence from sdp?
  344. if (!strcmp(ff_rtp_enc_name(payload_type), "MP2T")) {
  345. s->ts = ff_mpegts_parse_open(s->ic);
  346. if (s->ts == NULL) {
  347. av_free(s);
  348. return NULL;
  349. }
  350. } else if (st) {
  351. switch(st->codec->codec_id) {
  352. case AV_CODEC_ID_MPEG1VIDEO:
  353. case AV_CODEC_ID_MPEG2VIDEO:
  354. case AV_CODEC_ID_MP2:
  355. case AV_CODEC_ID_MP3:
  356. case AV_CODEC_ID_MPEG4:
  357. case AV_CODEC_ID_H263:
  358. case AV_CODEC_ID_H264:
  359. st->need_parsing = AVSTREAM_PARSE_FULL;
  360. break;
  361. case AV_CODEC_ID_VORBIS:
  362. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  363. break;
  364. case AV_CODEC_ID_ADPCM_G722:
  365. /* According to RFC 3551, the stream clock rate is 8000
  366. * even if the sample rate is 16000. */
  367. if (st->codec->sample_rate == 8000)
  368. st->codec->sample_rate = 16000;
  369. break;
  370. default:
  371. break;
  372. }
  373. }
  374. // needed to send back RTCP RR in RTSP sessions
  375. s->rtp_ctx = rtpc;
  376. gethostname(s->hostname, sizeof(s->hostname));
  377. return s;
  378. }
  379. void
  380. ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
  381. RTPDynamicProtocolHandler *handler)
  382. {
  383. s->dynamic_protocol_context = ctx;
  384. s->parse_packet = handler->parse_packet;
  385. }
  386. /**
  387. * This was the second switch in rtp_parse packet. Normalizes time, if required, sets stream_index, etc.
  388. */
  389. static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
  390. {
  391. if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE)
  392. return; /* Timestamp already set by depacketizer */
  393. if (timestamp == RTP_NOTS_VALUE)
  394. return;
  395. if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && s->ic->nb_streams > 1) {
  396. int64_t addend;
  397. int delta_timestamp;
  398. /* compute pts from timestamp with received ntp_time */
  399. delta_timestamp = timestamp - s->last_rtcp_timestamp;
  400. /* convert to the PTS timebase */
  401. addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time, s->st->time_base.den, (uint64_t)s->st->time_base.num << 32);
  402. pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
  403. delta_timestamp;
  404. return;
  405. }
  406. if (!s->base_timestamp)
  407. s->base_timestamp = timestamp;
  408. /* assume that the difference is INT32_MIN < x < INT32_MAX, but allow the first timestamp to exceed INT32_MAX */
  409. if (!s->timestamp)
  410. s->unwrapped_timestamp += timestamp;
  411. else
  412. s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
  413. s->timestamp = timestamp;
  414. pkt->pts = s->unwrapped_timestamp + s->range_start_offset - s->base_timestamp;
  415. }
  416. static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
  417. const uint8_t *buf, int len)
  418. {
  419. unsigned int ssrc, h;
  420. int payload_type, seq, ret, flags = 0;
  421. int ext;
  422. AVStream *st;
  423. uint32_t timestamp;
  424. int rv= 0;
  425. ext = buf[0] & 0x10;
  426. payload_type = buf[1] & 0x7f;
  427. if (buf[1] & 0x80)
  428. flags |= RTP_FLAG_MARKER;
  429. seq = AV_RB16(buf + 2);
  430. timestamp = AV_RB32(buf + 4);
  431. ssrc = AV_RB32(buf + 8);
  432. /* store the ssrc in the RTPDemuxContext */
  433. s->ssrc = ssrc;
  434. /* NOTE: we can handle only one payload type */
  435. if (s->payload_type != payload_type)
  436. return -1;
  437. st = s->st;
  438. // only do something with this if all the rtp checks pass...
  439. if(!rtp_valid_packet_in_sequence(&s->statistics, seq))
  440. {
  441. av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
  442. payload_type, seq, ((s->seq + 1) & 0xffff));
  443. return -1;
  444. }
  445. if (buf[0] & 0x20) {
  446. int padding = buf[len - 1];
  447. if (len >= 12 + padding)
  448. len -= padding;
  449. }
  450. s->seq = seq;
  451. len -= 12;
  452. buf += 12;
  453. /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
  454. if (ext) {
  455. if (len < 4)
  456. return -1;
  457. /* calculate the header extension length (stored as number
  458. * of 32-bit words) */
  459. ext = (AV_RB16(buf + 2) + 1) << 2;
  460. if (len < ext)
  461. return -1;
  462. // skip past RTP header extension
  463. len -= ext;
  464. buf += ext;
  465. }
  466. if (!st) {
  467. /* specific MPEG2TS demux support */
  468. ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
  469. /* The only error that can be returned from ff_mpegts_parse_packet
  470. * is "no more data to return from the provided buffer", so return
  471. * AVERROR(EAGAIN) for all errors */
  472. if (ret < 0)
  473. return AVERROR(EAGAIN);
  474. if (ret < len) {
  475. s->read_buf_size = len - ret;
  476. memcpy(s->buf, buf + ret, s->read_buf_size);
  477. s->read_buf_index = 0;
  478. return 1;
  479. }
  480. return 0;
  481. } else if (s->parse_packet) {
  482. rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
  483. s->st, pkt, &timestamp, buf, len, flags);
  484. } else {
  485. // at this point, the RTP header has been stripped; This is ASSUMING that there is only 1 CSRC, which in't wise.
  486. switch(st->codec->codec_id) {
  487. case AV_CODEC_ID_MP2:
  488. case AV_CODEC_ID_MP3:
  489. /* better than nothing: skip mpeg audio RTP header */
  490. if (len <= 4)
  491. return -1;
  492. h = AV_RB32(buf);
  493. len -= 4;
  494. buf += 4;
  495. av_new_packet(pkt, len);
  496. memcpy(pkt->data, buf, len);
  497. break;
  498. case AV_CODEC_ID_MPEG1VIDEO:
  499. case AV_CODEC_ID_MPEG2VIDEO:
  500. /* better than nothing: skip mpeg video RTP header */
  501. if (len <= 4)
  502. return -1;
  503. h = AV_RB32(buf);
  504. buf += 4;
  505. len -= 4;
  506. if (h & (1 << 26)) {
  507. /* mpeg2 */
  508. if (len <= 4)
  509. return -1;
  510. buf += 4;
  511. len -= 4;
  512. }
  513. av_new_packet(pkt, len);
  514. memcpy(pkt->data, buf, len);
  515. break;
  516. default:
  517. av_new_packet(pkt, len);
  518. memcpy(pkt->data, buf, len);
  519. break;
  520. }
  521. pkt->stream_index = st->index;
  522. }
  523. // now perform timestamp things....
  524. finalize_packet(s, pkt, timestamp);
  525. return rv;
  526. }
  527. void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
  528. {
  529. while (s->queue) {
  530. RTPPacket *next = s->queue->next;
  531. av_free(s->queue->buf);
  532. av_free(s->queue);
  533. s->queue = next;
  534. }
  535. s->seq = 0;
  536. s->queue_len = 0;
  537. s->prev_ret = 0;
  538. }
  539. static void enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
  540. {
  541. uint16_t seq = AV_RB16(buf + 2);
  542. RTPPacket *cur = s->queue, *prev = NULL, *packet;
  543. /* Find the correct place in the queue to insert the packet */
  544. while (cur) {
  545. int16_t diff = seq - cur->seq;
  546. if (diff < 0)
  547. break;
  548. prev = cur;
  549. cur = cur->next;
  550. }
  551. packet = av_mallocz(sizeof(*packet));
  552. if (!packet)
  553. return;
  554. packet->recvtime = av_gettime();
  555. packet->seq = seq;
  556. packet->len = len;
  557. packet->buf = buf;
  558. packet->next = cur;
  559. if (prev)
  560. prev->next = packet;
  561. else
  562. s->queue = packet;
  563. s->queue_len++;
  564. }
  565. static int has_next_packet(RTPDemuxContext *s)
  566. {
  567. return s->queue && s->queue->seq == (uint16_t) (s->seq + 1);
  568. }
  569. int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
  570. {
  571. return s->queue ? s->queue->recvtime : 0;
  572. }
  573. static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
  574. {
  575. int rv;
  576. RTPPacket *next;
  577. if (s->queue_len <= 0)
  578. return -1;
  579. if (!has_next_packet(s))
  580. av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
  581. "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
  582. /* Parse the first packet in the queue, and dequeue it */
  583. rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
  584. next = s->queue->next;
  585. av_free(s->queue->buf);
  586. av_free(s->queue);
  587. s->queue = next;
  588. s->queue_len--;
  589. return rv;
  590. }
  591. static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
  592. uint8_t **bufptr, int len)
  593. {
  594. uint8_t* buf = bufptr ? *bufptr : NULL;
  595. int ret, flags = 0;
  596. uint32_t timestamp;
  597. int rv= 0;
  598. if (!buf) {
  599. /* If parsing of the previous packet actually returned 0 or an error,
  600. * there's nothing more to be parsed from that packet, but we may have
  601. * indicated that we can return the next enqueued packet. */
  602. if (s->prev_ret <= 0)
  603. return rtp_parse_queued_packet(s, pkt);
  604. /* return the next packets, if any */
  605. if(s->st && s->parse_packet) {
  606. /* timestamp should be overwritten by parse_packet, if not,
  607. * the packet is left with pts == AV_NOPTS_VALUE */
  608. timestamp = RTP_NOTS_VALUE;
  609. rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
  610. s->st, pkt, &timestamp, NULL, 0, flags);
  611. finalize_packet(s, pkt, timestamp);
  612. return rv;
  613. } else {
  614. // TODO: Move to a dynamic packet handler (like above)
  615. if (s->read_buf_index >= s->read_buf_size)
  616. return AVERROR(EAGAIN);
  617. ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
  618. s->read_buf_size - s->read_buf_index);
  619. if (ret < 0)
  620. return AVERROR(EAGAIN);
  621. s->read_buf_index += ret;
  622. if (s->read_buf_index < s->read_buf_size)
  623. return 1;
  624. else
  625. return 0;
  626. }
  627. }
  628. if (len < 12)
  629. return -1;
  630. if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
  631. return -1;
  632. if (RTP_PT_IS_RTCP(buf[1])) {
  633. return rtcp_parse_packet(s, buf, len);
  634. }
  635. if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
  636. /* First packet, or no reordering */
  637. return rtp_parse_packet_internal(s, pkt, buf, len);
  638. } else {
  639. uint16_t seq = AV_RB16(buf + 2);
  640. int16_t diff = seq - s->seq;
  641. if (diff < 0) {
  642. /* Packet older than the previously emitted one, drop */
  643. av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
  644. "RTP: dropping old packet received too late\n");
  645. return -1;
  646. } else if (diff <= 1) {
  647. /* Correct packet */
  648. rv = rtp_parse_packet_internal(s, pkt, buf, len);
  649. return rv;
  650. } else {
  651. /* Still missing some packet, enqueue this one. */
  652. enqueue_packet(s, buf, len);
  653. *bufptr = NULL;
  654. /* Return the first enqueued packet if the queue is full,
  655. * even if we're missing something */
  656. if (s->queue_len >= s->queue_size)
  657. return rtp_parse_queued_packet(s, pkt);
  658. return -1;
  659. }
  660. }
  661. }
  662. /**
  663. * Parse an RTP or RTCP packet directly sent as a buffer.
  664. * @param s RTP parse context.
  665. * @param pkt returned packet
  666. * @param bufptr pointer to the input buffer or NULL to read the next packets
  667. * @param len buffer len
  668. * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
  669. * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
  670. */
  671. int ff_rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
  672. uint8_t **bufptr, int len)
  673. {
  674. int rv = rtp_parse_one_packet(s, pkt, bufptr, len);
  675. s->prev_ret = rv;
  676. while (rv == AVERROR(EAGAIN) && has_next_packet(s))
  677. rv = rtp_parse_queued_packet(s, pkt);
  678. return rv ? rv : has_next_packet(s);
  679. }
  680. void ff_rtp_parse_close(RTPDemuxContext *s)
  681. {
  682. ff_rtp_reset_packet_queue(s);
  683. if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
  684. ff_mpegts_parse_close(s->ts);
  685. }
  686. av_free(s);
  687. }
  688. int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
  689. int (*parse_fmtp)(AVStream *stream,
  690. PayloadContext *data,
  691. char *attr, char *value))
  692. {
  693. char attr[256];
  694. char *value;
  695. int res;
  696. int value_size = strlen(p) + 1;
  697. if (!(value = av_malloc(value_size))) {
  698. av_log(stream, AV_LOG_ERROR, "Failed to allocate data for FMTP.\n");
  699. return AVERROR(ENOMEM);
  700. }
  701. // remove protocol identifier
  702. while (*p && *p == ' ') p++; // strip spaces
  703. while (*p && *p != ' ') p++; // eat protocol identifier
  704. while (*p && *p == ' ') p++; // strip trailing spaces
  705. while (ff_rtsp_next_attr_and_value(&p,
  706. attr, sizeof(attr),
  707. value, value_size)) {
  708. res = parse_fmtp(stream, data, attr, value);
  709. if (res < 0 && res != AVERROR_PATCHWELCOME) {
  710. av_free(value);
  711. return res;
  712. }
  713. }
  714. av_free(value);
  715. return 0;
  716. }