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.

819 lines
27KB

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