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
26KB

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