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.

960 lines
31KB

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