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.

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