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.

919 lines
29KB

  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 "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. /* statistics functions */
  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_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. int ff_rtp_check_and_send_back_rr(RTPDemuxContext *s, URLContext *fd,
  208. AVIOContext *avio, int count)
  209. {
  210. AVIOContext *pb;
  211. uint8_t *buf;
  212. int len;
  213. int rtcp_bytes;
  214. RTPStatistics *stats = &s->statistics;
  215. uint32_t lost;
  216. uint32_t extended_max;
  217. uint32_t expected_interval;
  218. uint32_t received_interval;
  219. uint32_t lost_interval;
  220. uint32_t expected;
  221. uint32_t fraction;
  222. uint64_t ntp_time = s->last_rtcp_ntp_time; // TODO: Get local ntp time?
  223. if ((!fd && !avio) || (count < 1))
  224. return -1;
  225. /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
  226. /* XXX: MPEG pts hardcoded. RTCP send every 0.5 seconds */
  227. s->octet_count += count;
  228. rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
  229. RTCP_TX_RATIO_DEN;
  230. rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
  231. if (rtcp_bytes < 28)
  232. return -1;
  233. s->last_octet_count = s->octet_count;
  234. if (!fd)
  235. pb = avio;
  236. else if (avio_open_dyn_buf(&pb) < 0)
  237. return -1;
  238. // Receiver Report
  239. avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
  240. avio_w8(pb, RTCP_RR);
  241. avio_wb16(pb, 7); /* length in words - 1 */
  242. // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
  243. avio_wb32(pb, s->ssrc + 1);
  244. avio_wb32(pb, s->ssrc); // server SSRC
  245. // some placeholders we should really fill...
  246. // RFC 1889/p64
  247. extended_max = stats->cycles + stats->max_seq;
  248. expected = extended_max - stats->base_seq + 1;
  249. lost = expected - stats->received;
  250. lost = FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
  251. expected_interval = expected - stats->expected_prior;
  252. stats->expected_prior = expected;
  253. received_interval = stats->received - stats->received_prior;
  254. stats->received_prior = stats->received;
  255. lost_interval = expected_interval - received_interval;
  256. if (expected_interval == 0 || lost_interval <= 0)
  257. fraction = 0;
  258. else
  259. fraction = (lost_interval << 8) / expected_interval;
  260. fraction = (fraction << 24) | lost;
  261. avio_wb32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
  262. avio_wb32(pb, extended_max); /* max sequence received */
  263. avio_wb32(pb, stats->jitter >> 4); /* jitter */
  264. if (s->last_rtcp_ntp_time == AV_NOPTS_VALUE) {
  265. avio_wb32(pb, 0); /* last SR timestamp */
  266. avio_wb32(pb, 0); /* delay since last SR */
  267. } else {
  268. uint32_t middle_32_bits = s->last_rtcp_ntp_time >> 16; // this is valid, right? do we need to handle 64 bit values special?
  269. uint32_t delay_since_last = ntp_time - s->last_rtcp_ntp_time;
  270. avio_wb32(pb, middle_32_bits); /* last SR timestamp */
  271. avio_wb32(pb, delay_since_last); /* delay since last SR */
  272. }
  273. // CNAME
  274. avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
  275. avio_w8(pb, RTCP_SDES);
  276. len = strlen(s->hostname);
  277. avio_wb16(pb, (6 + len + 3) / 4); /* length in words - 1 */
  278. avio_wb32(pb, s->ssrc + 1);
  279. avio_w8(pb, 0x01);
  280. avio_w8(pb, len);
  281. avio_write(pb, s->hostname, len);
  282. // padding
  283. for (len = (6 + len) % 4; len % 4; len++)
  284. avio_w8(pb, 0);
  285. avio_flush(pb);
  286. if (!fd)
  287. return 0;
  288. len = avio_close_dyn_buf(pb, &buf);
  289. if ((len > 0) && buf) {
  290. int av_unused result;
  291. av_dlog(s->ic, "sending %d bytes of RR\n", len);
  292. result = ffurl_write(fd, buf, len);
  293. av_dlog(s->ic, "result from ffurl_write: %d\n", result);
  294. av_free(buf);
  295. }
  296. return 0;
  297. }
  298. void ff_rtp_send_punch_packets(URLContext *rtp_handle)
  299. {
  300. AVIOContext *pb;
  301. uint8_t *buf;
  302. int len;
  303. /* Send a small RTP packet */
  304. if (avio_open_dyn_buf(&pb) < 0)
  305. return;
  306. avio_w8(pb, (RTP_VERSION << 6));
  307. avio_w8(pb, 0); /* Payload type */
  308. avio_wb16(pb, 0); /* Seq */
  309. avio_wb32(pb, 0); /* Timestamp */
  310. avio_wb32(pb, 0); /* SSRC */
  311. avio_flush(pb);
  312. len = avio_close_dyn_buf(pb, &buf);
  313. if ((len > 0) && buf)
  314. ffurl_write(rtp_handle, buf, len);
  315. av_free(buf);
  316. /* Send a minimal RTCP RR */
  317. if (avio_open_dyn_buf(&pb) < 0)
  318. return;
  319. avio_w8(pb, (RTP_VERSION << 6));
  320. avio_w8(pb, RTCP_RR); /* receiver report */
  321. avio_wb16(pb, 1); /* length in words - 1 */
  322. avio_wb32(pb, 0); /* our own SSRC */
  323. avio_flush(pb);
  324. len = avio_close_dyn_buf(pb, &buf);
  325. if ((len > 0) && buf)
  326. ffurl_write(rtp_handle, buf, len);
  327. av_free(buf);
  328. }
  329. static int find_missing_packets(RTPDemuxContext *s, uint16_t *first_missing,
  330. uint16_t *missing_mask)
  331. {
  332. int i;
  333. uint16_t next_seq = s->seq + 1;
  334. RTPPacket *pkt = s->queue;
  335. if (!pkt || pkt->seq == next_seq)
  336. return 0;
  337. *missing_mask = 0;
  338. for (i = 1; i <= 16; i++) {
  339. uint16_t missing_seq = next_seq + i;
  340. while (pkt) {
  341. int16_t diff = pkt->seq - missing_seq;
  342. if (diff >= 0)
  343. break;
  344. pkt = pkt->next;
  345. }
  346. if (!pkt)
  347. break;
  348. if (pkt->seq == missing_seq)
  349. continue;
  350. *missing_mask |= 1 << (i - 1);
  351. }
  352. *first_missing = next_seq;
  353. return 1;
  354. }
  355. int ff_rtp_send_rtcp_feedback(RTPDemuxContext *s, URLContext *fd,
  356. AVIOContext *avio)
  357. {
  358. int len, need_keyframe, missing_packets;
  359. AVIOContext *pb;
  360. uint8_t *buf;
  361. int64_t now;
  362. uint16_t first_missing, missing_mask;
  363. if (!fd && !avio)
  364. return -1;
  365. need_keyframe = s->handler && s->handler->need_keyframe &&
  366. s->handler->need_keyframe(s->dynamic_protocol_context);
  367. missing_packets = find_missing_packets(s, &first_missing, &missing_mask);
  368. if (!need_keyframe && !missing_packets)
  369. return 0;
  370. /* Send new feedback if enough time has elapsed since the last
  371. * feedback packet. */
  372. now = av_gettime();
  373. if (s->last_feedback_time &&
  374. (now - s->last_feedback_time) < MIN_FEEDBACK_INTERVAL)
  375. return 0;
  376. s->last_feedback_time = now;
  377. if (!fd)
  378. pb = avio;
  379. else if (avio_open_dyn_buf(&pb) < 0)
  380. return -1;
  381. if (need_keyframe) {
  382. avio_w8(pb, (RTP_VERSION << 6) | 1); /* PLI */
  383. avio_w8(pb, RTCP_PSFB);
  384. avio_wb16(pb, 2); /* length in words - 1 */
  385. // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
  386. avio_wb32(pb, s->ssrc + 1);
  387. avio_wb32(pb, s->ssrc); // server SSRC
  388. }
  389. if (missing_packets) {
  390. avio_w8(pb, (RTP_VERSION << 6) | 1); /* NACK */
  391. avio_w8(pb, RTCP_RTPFB);
  392. avio_wb16(pb, 3); /* length in words - 1 */
  393. avio_wb32(pb, s->ssrc + 1);
  394. avio_wb32(pb, s->ssrc); // server SSRC
  395. avio_wb16(pb, first_missing);
  396. avio_wb16(pb, missing_mask);
  397. }
  398. avio_flush(pb);
  399. if (!fd)
  400. return 0;
  401. len = avio_close_dyn_buf(pb, &buf);
  402. if (len > 0 && buf) {
  403. ffurl_write(fd, buf, len);
  404. av_free(buf);
  405. }
  406. return 0;
  407. }
  408. /**
  409. * open a new RTP parse context for stream 'st'. 'st' can be NULL for
  410. * MPEG2-TS streams to indicate that they should be demuxed inside the
  411. * rtp demux (otherwise AV_CODEC_ID_MPEG2TS packets are returned)
  412. */
  413. RTPDemuxContext *ff_rtp_parse_open(AVFormatContext *s1, AVStream *st,
  414. int payload_type, int queue_size)
  415. {
  416. RTPDemuxContext *s;
  417. s = av_mallocz(sizeof(RTPDemuxContext));
  418. if (!s)
  419. return NULL;
  420. s->payload_type = payload_type;
  421. s->last_rtcp_ntp_time = AV_NOPTS_VALUE;
  422. s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
  423. s->ic = s1;
  424. s->st = st;
  425. s->queue_size = queue_size;
  426. rtp_init_statistics(&s->statistics, 0); // do we know the initial sequence from sdp?
  427. if (!strcmp(ff_rtp_enc_name(payload_type), "MP2T")) {
  428. s->ts = ff_mpegts_parse_open(s->ic);
  429. if (s->ts == NULL) {
  430. av_free(s);
  431. return NULL;
  432. }
  433. } else if (st) {
  434. switch (st->codec->codec_id) {
  435. case AV_CODEC_ID_MPEG1VIDEO:
  436. case AV_CODEC_ID_MPEG2VIDEO:
  437. case AV_CODEC_ID_MP2:
  438. case AV_CODEC_ID_MP3:
  439. case AV_CODEC_ID_MPEG4:
  440. case AV_CODEC_ID_H263:
  441. case AV_CODEC_ID_H264:
  442. st->need_parsing = AVSTREAM_PARSE_FULL;
  443. break;
  444. case AV_CODEC_ID_VORBIS:
  445. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  446. break;
  447. case AV_CODEC_ID_ADPCM_G722:
  448. /* According to RFC 3551, the stream clock rate is 8000
  449. * even if the sample rate is 16000. */
  450. if (st->codec->sample_rate == 8000)
  451. st->codec->sample_rate = 16000;
  452. break;
  453. default:
  454. break;
  455. }
  456. }
  457. // needed to send back RTCP RR in RTSP sessions
  458. gethostname(s->hostname, sizeof(s->hostname));
  459. return s;
  460. }
  461. void ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
  462. RTPDynamicProtocolHandler *handler)
  463. {
  464. s->dynamic_protocol_context = ctx;
  465. s->handler = handler;
  466. }
  467. /**
  468. * This was the second switch in rtp_parse packet.
  469. * Normalizes time, if required, sets stream_index, etc.
  470. */
  471. static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
  472. {
  473. if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE)
  474. return; /* Timestamp already set by depacketizer */
  475. if (timestamp == RTP_NOTS_VALUE)
  476. return;
  477. if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && s->ic->nb_streams > 1) {
  478. int64_t addend;
  479. int delta_timestamp;
  480. /* compute pts from timestamp with received ntp_time */
  481. delta_timestamp = timestamp - s->last_rtcp_timestamp;
  482. /* convert to the PTS timebase */
  483. addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time,
  484. s->st->time_base.den,
  485. (uint64_t) s->st->time_base.num << 32);
  486. pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
  487. delta_timestamp;
  488. return;
  489. }
  490. if (!s->base_timestamp)
  491. s->base_timestamp = timestamp;
  492. /* assume that the difference is INT32_MIN < x < INT32_MAX,
  493. * but allow the first timestamp to exceed INT32_MAX */
  494. if (!s->timestamp)
  495. s->unwrapped_timestamp += timestamp;
  496. else
  497. s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
  498. s->timestamp = timestamp;
  499. pkt->pts = s->unwrapped_timestamp + s->range_start_offset -
  500. s->base_timestamp;
  501. }
  502. static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
  503. const uint8_t *buf, int len)
  504. {
  505. unsigned int ssrc, h;
  506. int payload_type, seq, ret, flags = 0;
  507. int ext;
  508. AVStream *st;
  509. uint32_t timestamp;
  510. int rv = 0;
  511. ext = buf[0] & 0x10;
  512. payload_type = buf[1] & 0x7f;
  513. if (buf[1] & 0x80)
  514. flags |= RTP_FLAG_MARKER;
  515. seq = AV_RB16(buf + 2);
  516. timestamp = AV_RB32(buf + 4);
  517. ssrc = AV_RB32(buf + 8);
  518. /* store the ssrc in the RTPDemuxContext */
  519. s->ssrc = ssrc;
  520. /* NOTE: we can handle only one payload type */
  521. if (s->payload_type != payload_type)
  522. return -1;
  523. st = s->st;
  524. // only do something with this if all the rtp checks pass...
  525. if (!rtp_valid_packet_in_sequence(&s->statistics, seq)) {
  526. av_log(st ? st->codec : NULL, AV_LOG_ERROR,
  527. "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
  528. payload_type, seq, ((s->seq + 1) & 0xffff));
  529. return -1;
  530. }
  531. if (buf[0] & 0x20) {
  532. int padding = buf[len - 1];
  533. if (len >= 12 + padding)
  534. len -= padding;
  535. }
  536. s->seq = seq;
  537. len -= 12;
  538. buf += 12;
  539. /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
  540. if (ext) {
  541. if (len < 4)
  542. return -1;
  543. /* calculate the header extension length (stored as number
  544. * of 32-bit words) */
  545. ext = (AV_RB16(buf + 2) + 1) << 2;
  546. if (len < ext)
  547. return -1;
  548. // skip past RTP header extension
  549. len -= ext;
  550. buf += ext;
  551. }
  552. if (!st) {
  553. /* specific MPEG2-TS demux support */
  554. ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
  555. /* The only error that can be returned from ff_mpegts_parse_packet
  556. * is "no more data to return from the provided buffer", so return
  557. * AVERROR(EAGAIN) for all errors */
  558. if (ret < 0)
  559. return AVERROR(EAGAIN);
  560. if (ret < len) {
  561. s->read_buf_size = FFMIN(len - ret, sizeof(s->buf));
  562. memcpy(s->buf, buf + ret, s->read_buf_size);
  563. s->read_buf_index = 0;
  564. return 1;
  565. }
  566. return 0;
  567. } else if (s->handler && s->handler->parse_packet) {
  568. rv = s->handler->parse_packet(s->ic, s->dynamic_protocol_context,
  569. s->st, pkt, &timestamp, buf, len, seq,
  570. flags);
  571. } else {
  572. /* At this point, the RTP header has been stripped;
  573. * This is ASSUMING that there is only 1 CSRC, which isn't wise. */
  574. switch (st->codec->codec_id) {
  575. case AV_CODEC_ID_MP2:
  576. case AV_CODEC_ID_MP3:
  577. /* better than nothing: skip MPEG audio RTP header */
  578. if (len <= 4)
  579. return -1;
  580. h = AV_RB32(buf);
  581. len -= 4;
  582. buf += 4;
  583. if (av_new_packet(pkt, len) < 0)
  584. return AVERROR(ENOMEM);
  585. memcpy(pkt->data, buf, len);
  586. break;
  587. case AV_CODEC_ID_MPEG1VIDEO:
  588. case AV_CODEC_ID_MPEG2VIDEO:
  589. /* better than nothing: skip MPEG video RTP header */
  590. if (len <= 4)
  591. return -1;
  592. h = AV_RB32(buf);
  593. buf += 4;
  594. len -= 4;
  595. if (h & (1 << 26)) {
  596. /* MPEG-2 */
  597. if (len <= 4)
  598. return -1;
  599. buf += 4;
  600. len -= 4;
  601. }
  602. if (av_new_packet(pkt, len) < 0)
  603. return AVERROR(ENOMEM);
  604. memcpy(pkt->data, buf, len);
  605. break;
  606. default:
  607. if (av_new_packet(pkt, len) < 0)
  608. return AVERROR(ENOMEM);
  609. memcpy(pkt->data, buf, len);
  610. break;
  611. }
  612. pkt->stream_index = st->index;
  613. }
  614. // now perform timestamp things....
  615. finalize_packet(s, pkt, timestamp);
  616. return rv;
  617. }
  618. void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
  619. {
  620. while (s->queue) {
  621. RTPPacket *next = s->queue->next;
  622. av_free(s->queue->buf);
  623. av_free(s->queue);
  624. s->queue = next;
  625. }
  626. s->seq = 0;
  627. s->queue_len = 0;
  628. s->prev_ret = 0;
  629. }
  630. static void enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
  631. {
  632. uint16_t seq = AV_RB16(buf + 2);
  633. RTPPacket *cur = s->queue, *prev = NULL, *packet;
  634. /* Find the correct place in the queue to insert the packet */
  635. while (cur) {
  636. int16_t diff = seq - cur->seq;
  637. if (diff < 0)
  638. break;
  639. prev = cur;
  640. cur = cur->next;
  641. }
  642. packet = av_mallocz(sizeof(*packet));
  643. if (!packet)
  644. return;
  645. packet->recvtime = av_gettime();
  646. packet->seq = seq;
  647. packet->len = len;
  648. packet->buf = buf;
  649. packet->next = cur;
  650. if (prev)
  651. prev->next = packet;
  652. else
  653. s->queue = packet;
  654. s->queue_len++;
  655. }
  656. static int has_next_packet(RTPDemuxContext *s)
  657. {
  658. return s->queue && s->queue->seq == (uint16_t) (s->seq + 1);
  659. }
  660. int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
  661. {
  662. return s->queue ? s->queue->recvtime : 0;
  663. }
  664. static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
  665. {
  666. int rv;
  667. RTPPacket *next;
  668. if (s->queue_len <= 0)
  669. return -1;
  670. if (!has_next_packet(s))
  671. av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
  672. "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
  673. /* Parse the first packet in the queue, and dequeue it */
  674. rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
  675. next = s->queue->next;
  676. av_free(s->queue->buf);
  677. av_free(s->queue);
  678. s->queue = next;
  679. s->queue_len--;
  680. return rv;
  681. }
  682. static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
  683. uint8_t **bufptr, int len)
  684. {
  685. uint8_t *buf = bufptr ? *bufptr : NULL;
  686. int ret, flags = 0;
  687. uint32_t timestamp;
  688. int rv = 0;
  689. if (!buf) {
  690. /* If parsing of the previous packet actually returned 0 or an error,
  691. * there's nothing more to be parsed from that packet, but we may have
  692. * indicated that we can return the next enqueued packet. */
  693. if (s->prev_ret <= 0)
  694. return rtp_parse_queued_packet(s, pkt);
  695. /* return the next packets, if any */
  696. if (s->st && s->handler && s->handler->parse_packet) {
  697. /* timestamp should be overwritten by parse_packet, if not,
  698. * the packet is left with pts == AV_NOPTS_VALUE */
  699. timestamp = RTP_NOTS_VALUE;
  700. rv = s->handler->parse_packet(s->ic, s->dynamic_protocol_context,
  701. s->st, pkt, &timestamp, NULL, 0, 0,
  702. flags);
  703. finalize_packet(s, pkt, timestamp);
  704. return rv;
  705. } else {
  706. // TODO: Move to a dynamic packet handler (like above)
  707. if (s->read_buf_index >= s->read_buf_size)
  708. return AVERROR(EAGAIN);
  709. ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
  710. s->read_buf_size - s->read_buf_index);
  711. if (ret < 0)
  712. return AVERROR(EAGAIN);
  713. s->read_buf_index += ret;
  714. if (s->read_buf_index < s->read_buf_size)
  715. return 1;
  716. else
  717. return 0;
  718. }
  719. }
  720. if (len < 12)
  721. return -1;
  722. if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
  723. return -1;
  724. if (RTP_PT_IS_RTCP(buf[1])) {
  725. return rtcp_parse_packet(s, buf, len);
  726. }
  727. if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
  728. /* First packet, or no reordering */
  729. return rtp_parse_packet_internal(s, pkt, buf, len);
  730. } else {
  731. uint16_t seq = AV_RB16(buf + 2);
  732. int16_t diff = seq - s->seq;
  733. if (diff < 0) {
  734. /* Packet older than the previously emitted one, drop */
  735. av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
  736. "RTP: dropping old packet received too late\n");
  737. return -1;
  738. } else if (diff <= 1) {
  739. /* Correct packet */
  740. rv = rtp_parse_packet_internal(s, pkt, buf, len);
  741. return rv;
  742. } else {
  743. /* Still missing some packet, enqueue this one. */
  744. enqueue_packet(s, buf, len);
  745. *bufptr = NULL;
  746. /* Return the first enqueued packet if the queue is full,
  747. * even if we're missing something */
  748. if (s->queue_len >= s->queue_size)
  749. return rtp_parse_queued_packet(s, pkt);
  750. return -1;
  751. }
  752. }
  753. }
  754. /**
  755. * Parse an RTP or RTCP packet directly sent as a buffer.
  756. * @param s RTP parse context.
  757. * @param pkt returned packet
  758. * @param bufptr pointer to the input buffer or NULL to read the next packets
  759. * @param len buffer len
  760. * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
  761. * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
  762. */
  763. int ff_rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
  764. uint8_t **bufptr, int len)
  765. {
  766. int rv = rtp_parse_one_packet(s, pkt, bufptr, len);
  767. s->prev_ret = rv;
  768. while (rv == AVERROR(EAGAIN) && has_next_packet(s))
  769. rv = rtp_parse_queued_packet(s, pkt);
  770. return rv ? rv : has_next_packet(s);
  771. }
  772. void ff_rtp_parse_close(RTPDemuxContext *s)
  773. {
  774. ff_rtp_reset_packet_queue(s);
  775. if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
  776. ff_mpegts_parse_close(s->ts);
  777. }
  778. av_free(s);
  779. }
  780. int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
  781. int (*parse_fmtp)(AVStream *stream,
  782. PayloadContext *data,
  783. char *attr, char *value))
  784. {
  785. char attr[256];
  786. char *value;
  787. int res;
  788. int value_size = strlen(p) + 1;
  789. if (!(value = av_malloc(value_size))) {
  790. av_log(NULL, AV_LOG_ERROR, "Failed to allocate data for FMTP.\n");
  791. return AVERROR(ENOMEM);
  792. }
  793. // remove protocol identifier
  794. while (*p && *p == ' ')
  795. p++; // strip spaces
  796. while (*p && *p != ' ')
  797. p++; // eat protocol identifier
  798. while (*p && *p == ' ')
  799. p++; // strip trailing spaces
  800. while (ff_rtsp_next_attr_and_value(&p,
  801. attr, sizeof(attr),
  802. value, value_size)) {
  803. res = parse_fmtp(stream, data, attr, value);
  804. if (res < 0 && res != AVERROR_PATCHWELCOME) {
  805. av_free(value);
  806. return res;
  807. }
  808. }
  809. av_free(value);
  810. return 0;
  811. }
  812. int ff_rtp_finalize_packet(AVPacket *pkt, AVIOContext **dyn_buf, int stream_idx)
  813. {
  814. av_init_packet(pkt);
  815. pkt->size = avio_close_dyn_buf(*dyn_buf, &pkt->data);
  816. pkt->stream_index = stream_idx;
  817. pkt->destruct = av_destruct_packet;
  818. *dyn_buf = NULL;
  819. return pkt->size;
  820. }