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.

785 lines
25KB

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