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.

925 lines
30KB

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