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.

792 lines
25KB

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