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.

879 lines
28KB

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