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.

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