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.

779 lines
25KB

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