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.

882 lines
28KB

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