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.

941 lines
30KB

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