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.

797 lines
26KB

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