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.

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