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.

817 lines
27KB

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