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.

902 lines
29KB

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