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.

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