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.

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