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.

997 lines
31KB

  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/intreadwrite.h"
  24. #include "libavutil/time.h"
  25. #include "libavcodec/bytestream.h"
  26. #include "avformat.h"
  27. #include "network.h"
  28. #include "srtp.h"
  29. #include "url.h"
  30. #include "rtpdec.h"
  31. #include "rtpdec_formats.h"
  32. #include "internal.h"
  33. #define MIN_FEEDBACK_INTERVAL 200000 /* 200 ms in us */
  34. static const RTPDynamicProtocolHandler l24_dynamic_handler = {
  35. .enc_name = "L24",
  36. .codec_type = AVMEDIA_TYPE_AUDIO,
  37. .codec_id = AV_CODEC_ID_PCM_S24BE,
  38. };
  39. static const RTPDynamicProtocolHandler gsm_dynamic_handler = {
  40. .enc_name = "GSM",
  41. .codec_type = AVMEDIA_TYPE_AUDIO,
  42. .codec_id = AV_CODEC_ID_GSM,
  43. };
  44. static const RTPDynamicProtocolHandler realmedia_mp3_dynamic_handler = {
  45. .enc_name = "X-MP3-draft-00",
  46. .codec_type = AVMEDIA_TYPE_AUDIO,
  47. .codec_id = AV_CODEC_ID_MP3ADU,
  48. };
  49. static const RTPDynamicProtocolHandler speex_dynamic_handler = {
  50. .enc_name = "speex",
  51. .codec_type = AVMEDIA_TYPE_AUDIO,
  52. .codec_id = AV_CODEC_ID_SPEEX,
  53. };
  54. static const RTPDynamicProtocolHandler opus_dynamic_handler = {
  55. .enc_name = "opus",
  56. .codec_type = AVMEDIA_TYPE_AUDIO,
  57. .codec_id = AV_CODEC_ID_OPUS,
  58. };
  59. static const RTPDynamicProtocolHandler t140_dynamic_handler = { /* RFC 4103 */
  60. .enc_name = "t140",
  61. .codec_type = AVMEDIA_TYPE_SUBTITLE,
  62. .codec_id = AV_CODEC_ID_TEXT,
  63. };
  64. extern const RTPDynamicProtocolHandler ff_rdt_video_handler;
  65. extern const RTPDynamicProtocolHandler ff_rdt_audio_handler;
  66. extern const RTPDynamicProtocolHandler ff_rdt_live_video_handler;
  67. extern const RTPDynamicProtocolHandler ff_rdt_live_audio_handler;
  68. static const RTPDynamicProtocolHandler *const rtp_dynamic_protocol_handler_list[] = {
  69. /* rtp */
  70. &ff_ac3_dynamic_handler,
  71. &ff_amr_nb_dynamic_handler,
  72. &ff_amr_wb_dynamic_handler,
  73. &ff_dv_dynamic_handler,
  74. &ff_g726_16_dynamic_handler,
  75. &ff_g726_24_dynamic_handler,
  76. &ff_g726_32_dynamic_handler,
  77. &ff_g726_40_dynamic_handler,
  78. &ff_g726le_16_dynamic_handler,
  79. &ff_g726le_24_dynamic_handler,
  80. &ff_g726le_32_dynamic_handler,
  81. &ff_g726le_40_dynamic_handler,
  82. &ff_h261_dynamic_handler,
  83. &ff_h263_1998_dynamic_handler,
  84. &ff_h263_2000_dynamic_handler,
  85. &ff_h263_rfc2190_dynamic_handler,
  86. &ff_h264_dynamic_handler,
  87. &ff_hevc_dynamic_handler,
  88. &ff_ilbc_dynamic_handler,
  89. &ff_jpeg_dynamic_handler,
  90. &ff_mp4a_latm_dynamic_handler,
  91. &ff_mp4v_es_dynamic_handler,
  92. &ff_mpeg_audio_dynamic_handler,
  93. &ff_mpeg_audio_robust_dynamic_handler,
  94. &ff_mpeg_video_dynamic_handler,
  95. &ff_mpeg4_generic_dynamic_handler,
  96. &ff_mpegts_dynamic_handler,
  97. &ff_ms_rtp_asf_pfa_handler,
  98. &ff_ms_rtp_asf_pfv_handler,
  99. &ff_qcelp_dynamic_handler,
  100. &ff_qdm2_dynamic_handler,
  101. &ff_qt_rtp_aud_handler,
  102. &ff_qt_rtp_vid_handler,
  103. &ff_quicktime_rtp_aud_handler,
  104. &ff_quicktime_rtp_vid_handler,
  105. &ff_rfc4175_rtp_handler,
  106. &ff_svq3_dynamic_handler,
  107. &ff_theora_dynamic_handler,
  108. &ff_vc2hq_dynamic_handler,
  109. &ff_vorbis_dynamic_handler,
  110. &ff_vp8_dynamic_handler,
  111. &ff_vp9_dynamic_handler,
  112. &gsm_dynamic_handler,
  113. &l24_dynamic_handler,
  114. &opus_dynamic_handler,
  115. &realmedia_mp3_dynamic_handler,
  116. &speex_dynamic_handler,
  117. &t140_dynamic_handler,
  118. /* rdt */
  119. &ff_rdt_video_handler,
  120. &ff_rdt_audio_handler,
  121. &ff_rdt_live_video_handler,
  122. &ff_rdt_live_audio_handler,
  123. NULL,
  124. };
  125. const RTPDynamicProtocolHandler *ff_rtp_handler_iterate(void **opaque)
  126. {
  127. uintptr_t i = (uintptr_t)*opaque;
  128. const RTPDynamicProtocolHandler *r = rtp_dynamic_protocol_handler_list[i];
  129. if (r)
  130. *opaque = (void*)(i + 1);
  131. return r;
  132. }
  133. const RTPDynamicProtocolHandler *ff_rtp_handler_find_by_name(const char *name,
  134. enum AVMediaType codec_type)
  135. {
  136. void *i = 0;
  137. const RTPDynamicProtocolHandler *handler;
  138. while (handler = ff_rtp_handler_iterate(&i)) {
  139. if (handler->enc_name &&
  140. !av_strcasecmp(name, handler->enc_name) &&
  141. codec_type == handler->codec_type)
  142. return handler;
  143. }
  144. return NULL;
  145. }
  146. const RTPDynamicProtocolHandler *ff_rtp_handler_find_by_id(int id,
  147. enum AVMediaType codec_type)
  148. {
  149. void *i = 0;
  150. const RTPDynamicProtocolHandler *handler;
  151. while (handler = ff_rtp_handler_iterate(&i)) {
  152. if (handler->static_payload_id && handler->static_payload_id == id &&
  153. codec_type == handler->codec_type)
  154. return handler;
  155. }
  156. return NULL;
  157. }
  158. static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf,
  159. int len)
  160. {
  161. int payload_len;
  162. while (len >= 4) {
  163. payload_len = FFMIN(len, (AV_RB16(buf + 2) + 1) * 4);
  164. switch (buf[1]) {
  165. case RTCP_SR:
  166. if (payload_len < 20) {
  167. av_log(s->ic, AV_LOG_ERROR, "Invalid RTCP SR packet length\n");
  168. return AVERROR_INVALIDDATA;
  169. }
  170. s->last_rtcp_reception_time = av_gettime_relative();
  171. s->last_rtcp_ntp_time = AV_RB64(buf + 8);
  172. s->last_rtcp_timestamp = AV_RB32(buf + 16);
  173. if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
  174. s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
  175. if (!s->base_timestamp)
  176. s->base_timestamp = s->last_rtcp_timestamp;
  177. s->rtcp_ts_offset = (int32_t)(s->last_rtcp_timestamp - s->base_timestamp);
  178. }
  179. break;
  180. case RTCP_BYE:
  181. return -RTCP_BYE;
  182. }
  183. buf += payload_len;
  184. len -= payload_len;
  185. }
  186. return -1;
  187. }
  188. #define RTP_SEQ_MOD (1 << 16)
  189. static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence)
  190. {
  191. memset(s, 0, sizeof(RTPStatistics));
  192. s->max_seq = base_sequence;
  193. s->probation = 1;
  194. }
  195. /*
  196. * Called whenever there is a large jump in sequence numbers,
  197. * or when they get out of probation...
  198. */
  199. static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
  200. {
  201. s->max_seq = seq;
  202. s->cycles = 0;
  203. s->base_seq = seq - 1;
  204. s->bad_seq = RTP_SEQ_MOD + 1;
  205. s->received = 0;
  206. s->expected_prior = 0;
  207. s->received_prior = 0;
  208. s->jitter = 0;
  209. s->transit = 0;
  210. }
  211. /* Returns 1 if we should handle this packet. */
  212. static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
  213. {
  214. uint16_t udelta = seq - s->max_seq;
  215. const int MAX_DROPOUT = 3000;
  216. const int MAX_MISORDER = 100;
  217. const int MIN_SEQUENTIAL = 2;
  218. /* source not valid until MIN_SEQUENTIAL packets with sequence
  219. * seq. numbers have been received */
  220. if (s->probation) {
  221. if (seq == s->max_seq + 1) {
  222. s->probation--;
  223. s->max_seq = seq;
  224. if (s->probation == 0) {
  225. rtp_init_sequence(s, seq);
  226. s->received++;
  227. return 1;
  228. }
  229. } else {
  230. s->probation = MIN_SEQUENTIAL - 1;
  231. s->max_seq = seq;
  232. }
  233. } else if (udelta < MAX_DROPOUT) {
  234. // in order, with permissible gap
  235. if (seq < s->max_seq) {
  236. // sequence number wrapped; count another 64k cycles
  237. s->cycles += RTP_SEQ_MOD;
  238. }
  239. s->max_seq = seq;
  240. } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
  241. // sequence made a large jump...
  242. if (seq == s->bad_seq) {
  243. /* two sequential packets -- assume that the other side
  244. * restarted without telling us; just resync. */
  245. rtp_init_sequence(s, seq);
  246. } else {
  247. s->bad_seq = (seq + 1) & (RTP_SEQ_MOD - 1);
  248. return 0;
  249. }
  250. } else {
  251. // duplicate or reordered packet...
  252. }
  253. s->received++;
  254. return 1;
  255. }
  256. static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp,
  257. uint32_t arrival_timestamp)
  258. {
  259. // Most of this is pretty straight from RFC 3550 appendix A.8
  260. uint32_t transit = arrival_timestamp - sent_timestamp;
  261. uint32_t prev_transit = s->transit;
  262. int32_t d = transit - prev_transit;
  263. // Doing the FFABS() call directly on the "transit - prev_transit"
  264. // expression doesn't work, since it's an unsigned expression. Doing the
  265. // transit calculation in unsigned is desired though, since it most
  266. // probably will need to wrap around.
  267. d = FFABS(d);
  268. s->transit = transit;
  269. if (!prev_transit)
  270. return;
  271. s->jitter += d - (int32_t) ((s->jitter + 8) >> 4);
  272. }
  273. int ff_rtp_check_and_send_back_rr(RTPDemuxContext *s, URLContext *fd,
  274. AVIOContext *avio, int count)
  275. {
  276. AVIOContext *pb;
  277. uint8_t *buf;
  278. int len;
  279. int rtcp_bytes;
  280. RTPStatistics *stats = &s->statistics;
  281. uint32_t lost;
  282. uint32_t extended_max;
  283. uint32_t expected_interval;
  284. uint32_t received_interval;
  285. int32_t lost_interval;
  286. uint32_t expected;
  287. uint32_t fraction;
  288. if ((!fd && !avio) || (count < 1))
  289. return -1;
  290. /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
  291. /* XXX: MPEG pts hardcoded. RTCP send every 0.5 seconds */
  292. s->octet_count += count;
  293. rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
  294. RTCP_TX_RATIO_DEN;
  295. rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
  296. if (rtcp_bytes < 28)
  297. return -1;
  298. s->last_octet_count = s->octet_count;
  299. if (!fd)
  300. pb = avio;
  301. else if (avio_open_dyn_buf(&pb) < 0)
  302. return -1;
  303. // Receiver Report
  304. avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
  305. avio_w8(pb, RTCP_RR);
  306. avio_wb16(pb, 7); /* length in words - 1 */
  307. // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
  308. avio_wb32(pb, s->ssrc + 1);
  309. avio_wb32(pb, s->ssrc); // server SSRC
  310. // some placeholders we should really fill...
  311. // RFC 1889/p64
  312. extended_max = stats->cycles + stats->max_seq;
  313. expected = extended_max - stats->base_seq;
  314. lost = expected - stats->received;
  315. lost = FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
  316. expected_interval = expected - stats->expected_prior;
  317. stats->expected_prior = expected;
  318. received_interval = stats->received - stats->received_prior;
  319. stats->received_prior = stats->received;
  320. lost_interval = expected_interval - received_interval;
  321. if (expected_interval == 0 || lost_interval <= 0)
  322. fraction = 0;
  323. else
  324. fraction = (lost_interval << 8) / expected_interval;
  325. fraction = (fraction << 24) | lost;
  326. avio_wb32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
  327. avio_wb32(pb, extended_max); /* max sequence received */
  328. avio_wb32(pb, stats->jitter >> 4); /* jitter */
  329. if (s->last_rtcp_ntp_time == AV_NOPTS_VALUE) {
  330. avio_wb32(pb, 0); /* last SR timestamp */
  331. avio_wb32(pb, 0); /* delay since last SR */
  332. } else {
  333. uint32_t middle_32_bits = s->last_rtcp_ntp_time >> 16; // this is valid, right? do we need to handle 64 bit values special?
  334. uint32_t delay_since_last = av_rescale(av_gettime_relative() - s->last_rtcp_reception_time,
  335. 65536, AV_TIME_BASE);
  336. avio_wb32(pb, middle_32_bits); /* last SR timestamp */
  337. avio_wb32(pb, delay_since_last); /* delay since last SR */
  338. }
  339. // CNAME
  340. avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
  341. avio_w8(pb, RTCP_SDES);
  342. len = strlen(s->hostname);
  343. avio_wb16(pb, (7 + len + 3) / 4); /* length in words - 1 */
  344. avio_wb32(pb, s->ssrc + 1);
  345. avio_w8(pb, 0x01);
  346. avio_w8(pb, len);
  347. avio_write(pb, s->hostname, len);
  348. avio_w8(pb, 0); /* END */
  349. // padding
  350. for (len = (7 + len) % 4; len % 4; len++)
  351. avio_w8(pb, 0);
  352. avio_flush(pb);
  353. if (!fd)
  354. return 0;
  355. len = avio_close_dyn_buf(pb, &buf);
  356. if ((len > 0) && buf) {
  357. int av_unused result;
  358. av_log(s->ic, AV_LOG_TRACE, "sending %d bytes of RR\n", len);
  359. result = ffurl_write(fd, buf, len);
  360. av_log(s->ic, AV_LOG_TRACE, "result from ffurl_write: %d\n", result);
  361. av_free(buf);
  362. }
  363. return 0;
  364. }
  365. void ff_rtp_send_punch_packets(URLContext *rtp_handle)
  366. {
  367. uint8_t buf[RTP_MIN_PACKET_LENGTH], *ptr = buf;
  368. /* Send a small RTP packet */
  369. bytestream_put_byte(&ptr, (RTP_VERSION << 6));
  370. bytestream_put_byte(&ptr, 0); /* Payload type */
  371. bytestream_put_be16(&ptr, 0); /* Seq */
  372. bytestream_put_be32(&ptr, 0); /* Timestamp */
  373. bytestream_put_be32(&ptr, 0); /* SSRC */
  374. ffurl_write(rtp_handle, buf, ptr - buf);
  375. /* Send a minimal RTCP RR */
  376. ptr = buf;
  377. bytestream_put_byte(&ptr, (RTP_VERSION << 6));
  378. bytestream_put_byte(&ptr, RTCP_RR); /* receiver report */
  379. bytestream_put_be16(&ptr, 1); /* length in words - 1 */
  380. bytestream_put_be32(&ptr, 0); /* our own SSRC */
  381. ffurl_write(rtp_handle, buf, ptr - buf);
  382. }
  383. static int find_missing_packets(RTPDemuxContext *s, uint16_t *first_missing,
  384. uint16_t *missing_mask)
  385. {
  386. int i;
  387. uint16_t next_seq = s->seq + 1;
  388. RTPPacket *pkt = s->queue;
  389. if (!pkt || pkt->seq == next_seq)
  390. return 0;
  391. *missing_mask = 0;
  392. for (i = 1; i <= 16; i++) {
  393. uint16_t missing_seq = next_seq + i;
  394. while (pkt) {
  395. int16_t diff = pkt->seq - missing_seq;
  396. if (diff >= 0)
  397. break;
  398. pkt = pkt->next;
  399. }
  400. if (!pkt)
  401. break;
  402. if (pkt->seq == missing_seq)
  403. continue;
  404. *missing_mask |= 1 << (i - 1);
  405. }
  406. *first_missing = next_seq;
  407. return 1;
  408. }
  409. int ff_rtp_send_rtcp_feedback(RTPDemuxContext *s, URLContext *fd,
  410. AVIOContext *avio)
  411. {
  412. int len, need_keyframe, missing_packets;
  413. AVIOContext *pb;
  414. uint8_t *buf;
  415. int64_t now;
  416. uint16_t first_missing = 0, missing_mask = 0;
  417. if (!fd && !avio)
  418. return -1;
  419. need_keyframe = s->handler && s->handler->need_keyframe &&
  420. s->handler->need_keyframe(s->dynamic_protocol_context);
  421. missing_packets = find_missing_packets(s, &first_missing, &missing_mask);
  422. if (!need_keyframe && !missing_packets)
  423. return 0;
  424. /* Send new feedback if enough time has elapsed since the last
  425. * feedback packet. */
  426. now = av_gettime_relative();
  427. if (s->last_feedback_time &&
  428. (now - s->last_feedback_time) < MIN_FEEDBACK_INTERVAL)
  429. return 0;
  430. s->last_feedback_time = now;
  431. if (!fd)
  432. pb = avio;
  433. else if (avio_open_dyn_buf(&pb) < 0)
  434. return -1;
  435. if (need_keyframe) {
  436. avio_w8(pb, (RTP_VERSION << 6) | 1); /* PLI */
  437. avio_w8(pb, RTCP_PSFB);
  438. avio_wb16(pb, 2); /* length in words - 1 */
  439. // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
  440. avio_wb32(pb, s->ssrc + 1);
  441. avio_wb32(pb, s->ssrc); // server SSRC
  442. }
  443. if (missing_packets) {
  444. avio_w8(pb, (RTP_VERSION << 6) | 1); /* NACK */
  445. avio_w8(pb, RTCP_RTPFB);
  446. avio_wb16(pb, 3); /* length in words - 1 */
  447. avio_wb32(pb, s->ssrc + 1);
  448. avio_wb32(pb, s->ssrc); // server SSRC
  449. avio_wb16(pb, first_missing);
  450. avio_wb16(pb, missing_mask);
  451. }
  452. avio_flush(pb);
  453. if (!fd)
  454. return 0;
  455. len = avio_close_dyn_buf(pb, &buf);
  456. if (len > 0 && buf) {
  457. ffurl_write(fd, buf, len);
  458. av_free(buf);
  459. }
  460. return 0;
  461. }
  462. static int opus_write_extradata(AVCodecParameters *codecpar)
  463. {
  464. uint8_t *bs;
  465. int ret;
  466. /* This function writes an extradata with a channel mapping family of 0.
  467. * This mapping family only supports mono and stereo layouts. And RFC7587
  468. * specifies that the number of channels in the SDP must be 2.
  469. */
  470. if (codecpar->channels > 2) {
  471. return AVERROR_INVALIDDATA;
  472. }
  473. ret = ff_alloc_extradata(codecpar, 19);
  474. if (ret < 0)
  475. return ret;
  476. bs = (uint8_t *)codecpar->extradata;
  477. /* Opus magic */
  478. bytestream_put_buffer(&bs, "OpusHead", 8);
  479. /* Version */
  480. bytestream_put_byte (&bs, 0x1);
  481. /* Channel count */
  482. bytestream_put_byte (&bs, codecpar->channels);
  483. /* Pre skip */
  484. bytestream_put_le16 (&bs, 0);
  485. /* Input sample rate */
  486. bytestream_put_le32 (&bs, 48000);
  487. /* Output gain */
  488. bytestream_put_le16 (&bs, 0x0);
  489. /* Mapping family */
  490. bytestream_put_byte (&bs, 0x0);
  491. return 0;
  492. }
  493. /**
  494. * open a new RTP parse context for stream 'st'. 'st' can be NULL for
  495. * MPEG-2 TS streams.
  496. */
  497. RTPDemuxContext *ff_rtp_parse_open(AVFormatContext *s1, AVStream *st,
  498. int payload_type, int queue_size)
  499. {
  500. RTPDemuxContext *s;
  501. int ret;
  502. s = av_mallocz(sizeof(RTPDemuxContext));
  503. if (!s)
  504. return NULL;
  505. s->payload_type = payload_type;
  506. s->last_rtcp_ntp_time = AV_NOPTS_VALUE;
  507. s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
  508. s->ic = s1;
  509. s->st = st;
  510. s->queue_size = queue_size;
  511. av_log(s->ic, AV_LOG_VERBOSE, "setting jitter buffer size to %d\n",
  512. s->queue_size);
  513. rtp_init_statistics(&s->statistics, 0);
  514. if (st) {
  515. switch (st->codecpar->codec_id) {
  516. case AV_CODEC_ID_ADPCM_G722:
  517. /* According to RFC 3551, the stream clock rate is 8000
  518. * even if the sample rate is 16000. */
  519. if (st->codecpar->sample_rate == 8000)
  520. st->codecpar->sample_rate = 16000;
  521. break;
  522. case AV_CODEC_ID_OPUS:
  523. ret = opus_write_extradata(st->codecpar);
  524. if (ret < 0) {
  525. av_log(s1, AV_LOG_ERROR,
  526. "Error creating opus extradata: %s\n",
  527. av_err2str(ret));
  528. av_free(s);
  529. return NULL;
  530. }
  531. break;
  532. default:
  533. break;
  534. }
  535. }
  536. // needed to send back RTCP RR in RTSP sessions
  537. gethostname(s->hostname, sizeof(s->hostname));
  538. return s;
  539. }
  540. void ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
  541. const RTPDynamicProtocolHandler *handler)
  542. {
  543. s->dynamic_protocol_context = ctx;
  544. s->handler = handler;
  545. }
  546. void ff_rtp_parse_set_crypto(RTPDemuxContext *s, const char *suite,
  547. const char *params)
  548. {
  549. if (!ff_srtp_set_crypto(&s->srtp, suite, params))
  550. s->srtp_enabled = 1;
  551. }
  552. static int rtp_set_prft(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp) {
  553. AVProducerReferenceTime *prft =
  554. (AVProducerReferenceTime *) av_packet_new_side_data(
  555. pkt, AV_PKT_DATA_PRFT, sizeof(AVProducerReferenceTime));
  556. if (!prft)
  557. return AVERROR(ENOMEM);
  558. prft->wallclock = ff_parse_ntp_time(s->last_rtcp_ntp_time) - NTP_OFFSET_US +
  559. timestamp - s->last_rtcp_timestamp;
  560. prft->flags = 24;
  561. return 0;
  562. }
  563. /**
  564. * This was the second switch in rtp_parse packet.
  565. * Normalizes time, if required, sets stream_index, etc.
  566. */
  567. static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
  568. {
  569. if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE)
  570. return; /* Timestamp already set by depacketizer */
  571. if (timestamp == RTP_NOTS_VALUE)
  572. return;
  573. if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE) {
  574. if (rtp_set_prft(s, pkt, timestamp) < 0) {
  575. av_log(s->ic, AV_LOG_WARNING, "rtpdec: failed to set prft");
  576. }
  577. }
  578. if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && s->ic->nb_streams > 1) {
  579. int64_t addend;
  580. int delta_timestamp;
  581. /* compute pts from timestamp with received ntp_time */
  582. delta_timestamp = timestamp - s->last_rtcp_timestamp;
  583. /* convert to the PTS timebase */
  584. addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time,
  585. s->st->time_base.den,
  586. (uint64_t) s->st->time_base.num << 32);
  587. pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
  588. delta_timestamp;
  589. return;
  590. }
  591. if (!s->base_timestamp)
  592. s->base_timestamp = timestamp;
  593. /* assume that the difference is INT32_MIN < x < INT32_MAX,
  594. * but allow the first timestamp to exceed INT32_MAX */
  595. if (!s->timestamp)
  596. s->unwrapped_timestamp += timestamp;
  597. else
  598. s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
  599. s->timestamp = timestamp;
  600. pkt->pts = s->unwrapped_timestamp + s->range_start_offset -
  601. s->base_timestamp;
  602. }
  603. static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
  604. const uint8_t *buf, int len)
  605. {
  606. unsigned int ssrc;
  607. int payload_type, seq, flags = 0;
  608. int ext, csrc;
  609. AVStream *st;
  610. uint32_t timestamp;
  611. int rv = 0;
  612. csrc = buf[0] & 0x0f;
  613. ext = buf[0] & 0x10;
  614. payload_type = buf[1] & 0x7f;
  615. if (buf[1] & 0x80)
  616. flags |= RTP_FLAG_MARKER;
  617. seq = AV_RB16(buf + 2);
  618. timestamp = AV_RB32(buf + 4);
  619. ssrc = AV_RB32(buf + 8);
  620. /* store the ssrc in the RTPDemuxContext */
  621. s->ssrc = ssrc;
  622. /* NOTE: we can handle only one payload type */
  623. if (s->payload_type != payload_type)
  624. return -1;
  625. st = s->st;
  626. // only do something with this if all the rtp checks pass...
  627. if (!rtp_valid_packet_in_sequence(&s->statistics, seq)) {
  628. av_log(s->ic, AV_LOG_ERROR,
  629. "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
  630. payload_type, seq, ((s->seq + 1) & 0xffff));
  631. return -1;
  632. }
  633. if (buf[0] & 0x20) {
  634. int padding = buf[len - 1];
  635. if (len >= 12 + padding)
  636. len -= padding;
  637. }
  638. s->seq = seq;
  639. len -= 12;
  640. buf += 12;
  641. len -= 4 * csrc;
  642. buf += 4 * csrc;
  643. if (len < 0)
  644. return AVERROR_INVALIDDATA;
  645. /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
  646. if (ext) {
  647. if (len < 4)
  648. return -1;
  649. /* calculate the header extension length (stored as number
  650. * of 32-bit words) */
  651. ext = (AV_RB16(buf + 2) + 1) << 2;
  652. if (len < ext)
  653. return -1;
  654. // skip past RTP header extension
  655. len -= ext;
  656. buf += ext;
  657. }
  658. if (s->handler && s->handler->parse_packet) {
  659. rv = s->handler->parse_packet(s->ic, s->dynamic_protocol_context,
  660. s->st, pkt, &timestamp, buf, len, seq,
  661. flags);
  662. } else if (st) {
  663. if ((rv = av_new_packet(pkt, len)) < 0)
  664. return rv;
  665. memcpy(pkt->data, buf, len);
  666. pkt->stream_index = st->index;
  667. } else {
  668. return AVERROR(EINVAL);
  669. }
  670. // now perform timestamp things....
  671. finalize_packet(s, pkt, timestamp);
  672. return rv;
  673. }
  674. void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
  675. {
  676. while (s->queue) {
  677. RTPPacket *next = s->queue->next;
  678. av_freep(&s->queue->buf);
  679. av_freep(&s->queue);
  680. s->queue = next;
  681. }
  682. s->seq = 0;
  683. s->queue_len = 0;
  684. s->prev_ret = 0;
  685. }
  686. static int enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
  687. {
  688. uint16_t seq = AV_RB16(buf + 2);
  689. RTPPacket **cur = &s->queue, *packet;
  690. /* Find the correct place in the queue to insert the packet */
  691. while (*cur) {
  692. int16_t diff = seq - (*cur)->seq;
  693. if (diff < 0)
  694. break;
  695. cur = &(*cur)->next;
  696. }
  697. packet = av_mallocz(sizeof(*packet));
  698. if (!packet)
  699. return AVERROR(ENOMEM);
  700. packet->recvtime = av_gettime_relative();
  701. packet->seq = seq;
  702. packet->len = len;
  703. packet->buf = buf;
  704. packet->next = *cur;
  705. *cur = packet;
  706. s->queue_len++;
  707. return 0;
  708. }
  709. static int has_next_packet(RTPDemuxContext *s)
  710. {
  711. return s->queue && s->queue->seq == (uint16_t) (s->seq + 1);
  712. }
  713. int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
  714. {
  715. return s->queue ? s->queue->recvtime : 0;
  716. }
  717. static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
  718. {
  719. int rv;
  720. RTPPacket *next;
  721. if (s->queue_len <= 0)
  722. return -1;
  723. if (!has_next_packet(s))
  724. av_log(s->ic, AV_LOG_WARNING,
  725. "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
  726. /* Parse the first packet in the queue, and dequeue it */
  727. rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
  728. next = s->queue->next;
  729. av_freep(&s->queue->buf);
  730. av_freep(&s->queue);
  731. s->queue = next;
  732. s->queue_len--;
  733. return rv;
  734. }
  735. static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
  736. uint8_t **bufptr, int len)
  737. {
  738. uint8_t *buf = bufptr ? *bufptr : NULL;
  739. int flags = 0;
  740. uint32_t timestamp;
  741. int rv = 0;
  742. if (!buf) {
  743. /* If parsing of the previous packet actually returned 0 or an error,
  744. * there's nothing more to be parsed from that packet, but we may have
  745. * indicated that we can return the next enqueued packet. */
  746. if (s->prev_ret <= 0)
  747. return rtp_parse_queued_packet(s, pkt);
  748. /* return the next packets, if any */
  749. if (s->handler && s->handler->parse_packet) {
  750. /* timestamp should be overwritten by parse_packet, if not,
  751. * the packet is left with pts == AV_NOPTS_VALUE */
  752. timestamp = RTP_NOTS_VALUE;
  753. rv = s->handler->parse_packet(s->ic, s->dynamic_protocol_context,
  754. s->st, pkt, &timestamp, NULL, 0, 0,
  755. flags);
  756. finalize_packet(s, pkt, timestamp);
  757. return rv;
  758. }
  759. }
  760. if (len < 12)
  761. return -1;
  762. if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
  763. return -1;
  764. if (RTP_PT_IS_RTCP(buf[1])) {
  765. return rtcp_parse_packet(s, buf, len);
  766. }
  767. if (s->st) {
  768. int64_t received = av_gettime_relative();
  769. uint32_t arrival_ts = av_rescale_q(received, AV_TIME_BASE_Q,
  770. s->st->time_base);
  771. timestamp = AV_RB32(buf + 4);
  772. // Calculate the jitter immediately, before queueing the packet
  773. // into the reordering queue.
  774. rtcp_update_jitter(&s->statistics, timestamp, arrival_ts);
  775. }
  776. if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
  777. /* First packet, or no reordering */
  778. return rtp_parse_packet_internal(s, pkt, buf, len);
  779. } else {
  780. uint16_t seq = AV_RB16(buf + 2);
  781. int16_t diff = seq - s->seq;
  782. if (diff < 0) {
  783. /* Packet older than the previously emitted one, drop */
  784. av_log(s->ic, AV_LOG_WARNING,
  785. "RTP: dropping old packet received too late\n");
  786. return -1;
  787. } else if (diff <= 1) {
  788. /* Correct packet */
  789. rv = rtp_parse_packet_internal(s, pkt, buf, len);
  790. return rv;
  791. } else {
  792. /* Still missing some packet, enqueue this one. */
  793. rv = enqueue_packet(s, buf, len);
  794. if (rv < 0)
  795. return rv;
  796. *bufptr = NULL;
  797. /* Return the first enqueued packet if the queue is full,
  798. * even if we're missing something */
  799. if (s->queue_len >= s->queue_size) {
  800. av_log(s->ic, AV_LOG_WARNING, "jitter buffer full\n");
  801. return rtp_parse_queued_packet(s, pkt);
  802. }
  803. return -1;
  804. }
  805. }
  806. }
  807. /**
  808. * Parse an RTP or RTCP packet directly sent as a buffer.
  809. * @param s RTP parse context.
  810. * @param pkt returned packet
  811. * @param bufptr pointer to the input buffer or NULL to read the next packets
  812. * @param len buffer len
  813. * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
  814. * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
  815. */
  816. int ff_rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
  817. uint8_t **bufptr, int len)
  818. {
  819. int rv;
  820. if (s->srtp_enabled && bufptr && ff_srtp_decrypt(&s->srtp, *bufptr, &len) < 0)
  821. return -1;
  822. rv = rtp_parse_one_packet(s, pkt, bufptr, len);
  823. s->prev_ret = rv;
  824. while (rv < 0 && has_next_packet(s))
  825. rv = rtp_parse_queued_packet(s, pkt);
  826. return rv ? rv : has_next_packet(s);
  827. }
  828. void ff_rtp_parse_close(RTPDemuxContext *s)
  829. {
  830. ff_rtp_reset_packet_queue(s);
  831. ff_srtp_free(&s->srtp);
  832. av_free(s);
  833. }
  834. int ff_parse_fmtp(AVFormatContext *s,
  835. AVStream *stream, PayloadContext *data, const char *p,
  836. int (*parse_fmtp)(AVFormatContext *s,
  837. AVStream *stream,
  838. PayloadContext *data,
  839. const char *attr, const char *value))
  840. {
  841. char attr[256];
  842. char *value;
  843. int res;
  844. int value_size = strlen(p) + 1;
  845. if (!(value = av_malloc(value_size))) {
  846. av_log(s, AV_LOG_ERROR, "Failed to allocate data for FMTP.\n");
  847. return AVERROR(ENOMEM);
  848. }
  849. // remove protocol identifier
  850. while (*p && *p == ' ')
  851. p++; // strip spaces
  852. while (*p && *p != ' ')
  853. p++; // eat protocol identifier
  854. while (*p && *p == ' ')
  855. p++; // strip trailing spaces
  856. while (ff_rtsp_next_attr_and_value(&p,
  857. attr, sizeof(attr),
  858. value, value_size)) {
  859. res = parse_fmtp(s, stream, data, attr, value);
  860. if (res < 0 && res != AVERROR_PATCHWELCOME) {
  861. av_free(value);
  862. return res;
  863. }
  864. }
  865. av_free(value);
  866. return 0;
  867. }
  868. int ff_rtp_finalize_packet(AVPacket *pkt, AVIOContext **dyn_buf, int stream_idx)
  869. {
  870. int ret;
  871. av_packet_unref(pkt);
  872. pkt->size = avio_close_dyn_buf(*dyn_buf, &pkt->data);
  873. pkt->stream_index = stream_idx;
  874. *dyn_buf = NULL;
  875. if ((ret = av_packet_from_data(pkt, pkt->data, pkt->size)) < 0) {
  876. av_freep(&pkt->data);
  877. return ret;
  878. }
  879. return pkt->size;
  880. }