You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

795 lines
25KB

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