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.

791 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_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 {
  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_ADPCM_G722:
  354. /* According to RFC 3551, the stream clock rate is 8000
  355. * even if the sample rate is 16000. */
  356. if (st->codec->sample_rate == 8000)
  357. st->codec->sample_rate = 16000;
  358. break;
  359. default:
  360. break;
  361. }
  362. }
  363. // needed to send back RTCP RR in RTSP sessions
  364. s->rtp_ctx = rtpc;
  365. gethostname(s->hostname, sizeof(s->hostname));
  366. return s;
  367. }
  368. void
  369. ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
  370. RTPDynamicProtocolHandler *handler)
  371. {
  372. s->dynamic_protocol_context = ctx;
  373. s->parse_packet = handler->parse_packet;
  374. }
  375. /**
  376. * This was the second switch in rtp_parse packet. Normalizes time, if required, sets stream_index, etc.
  377. */
  378. static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
  379. {
  380. if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE)
  381. return; /* Timestamp already set by depacketizer */
  382. if (timestamp == RTP_NOTS_VALUE)
  383. return;
  384. if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && s->ic->nb_streams > 1) {
  385. int64_t addend;
  386. int delta_timestamp;
  387. /* compute pts from timestamp with received ntp_time */
  388. delta_timestamp = timestamp - s->last_rtcp_timestamp;
  389. /* convert to the PTS timebase */
  390. 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);
  391. pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
  392. delta_timestamp;
  393. return;
  394. }
  395. if (!s->base_timestamp)
  396. s->base_timestamp = timestamp;
  397. /* assume that the difference is INT32_MIN < x < INT32_MAX, but allow the first timestamp to exceed INT32_MAX */
  398. if (!s->timestamp)
  399. s->unwrapped_timestamp += timestamp;
  400. else
  401. s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
  402. s->timestamp = timestamp;
  403. pkt->pts = s->unwrapped_timestamp + s->range_start_offset - s->base_timestamp;
  404. }
  405. static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
  406. const uint8_t *buf, int len)
  407. {
  408. unsigned int ssrc, h;
  409. int payload_type, seq, ret, flags = 0;
  410. int ext;
  411. AVStream *st;
  412. uint32_t timestamp;
  413. int rv= 0;
  414. ext = buf[0] & 0x10;
  415. payload_type = buf[1] & 0x7f;
  416. if (buf[1] & 0x80)
  417. flags |= RTP_FLAG_MARKER;
  418. seq = AV_RB16(buf + 2);
  419. timestamp = AV_RB32(buf + 4);
  420. ssrc = AV_RB32(buf + 8);
  421. /* store the ssrc in the RTPDemuxContext */
  422. s->ssrc = ssrc;
  423. /* NOTE: we can handle only one payload type */
  424. if (s->payload_type != payload_type)
  425. return -1;
  426. st = s->st;
  427. // only do something with this if all the rtp checks pass...
  428. if(!rtp_valid_packet_in_sequence(&s->statistics, seq))
  429. {
  430. av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
  431. payload_type, seq, ((s->seq + 1) & 0xffff));
  432. return -1;
  433. }
  434. if (buf[0] & 0x20) {
  435. int padding = buf[len - 1];
  436. if (len >= 12 + padding)
  437. len -= padding;
  438. }
  439. s->seq = seq;
  440. len -= 12;
  441. buf += 12;
  442. /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
  443. if (ext) {
  444. if (len < 4)
  445. return -1;
  446. /* calculate the header extension length (stored as number
  447. * of 32-bit words) */
  448. ext = (AV_RB16(buf + 2) + 1) << 2;
  449. if (len < ext)
  450. return -1;
  451. // skip past RTP header extension
  452. len -= ext;
  453. buf += ext;
  454. }
  455. if (!st) {
  456. /* specific MPEG2TS demux support */
  457. ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
  458. /* The only error that can be returned from ff_mpegts_parse_packet
  459. * is "no more data to return from the provided buffer", so return
  460. * AVERROR(EAGAIN) for all errors */
  461. if (ret < 0)
  462. return AVERROR(EAGAIN);
  463. if (ret < len) {
  464. s->read_buf_size = len - ret;
  465. memcpy(s->buf, buf + ret, s->read_buf_size);
  466. s->read_buf_index = 0;
  467. return 1;
  468. }
  469. return 0;
  470. } else if (s->parse_packet) {
  471. rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
  472. s->st, pkt, &timestamp, buf, len, flags);
  473. } else {
  474. // at this point, the RTP header has been stripped; This is ASSUMING that there is only 1 CSRC, which in't wise.
  475. switch(st->codec->codec_id) {
  476. case CODEC_ID_MP2:
  477. case CODEC_ID_MP3:
  478. /* better than nothing: skip mpeg audio RTP header */
  479. if (len <= 4)
  480. return -1;
  481. h = AV_RB32(buf);
  482. len -= 4;
  483. buf += 4;
  484. av_new_packet(pkt, len);
  485. memcpy(pkt->data, buf, len);
  486. break;
  487. case CODEC_ID_MPEG1VIDEO:
  488. case CODEC_ID_MPEG2VIDEO:
  489. /* better than nothing: skip mpeg video RTP header */
  490. if (len <= 4)
  491. return -1;
  492. h = AV_RB32(buf);
  493. buf += 4;
  494. len -= 4;
  495. if (h & (1 << 26)) {
  496. /* mpeg2 */
  497. if (len <= 4)
  498. return -1;
  499. buf += 4;
  500. len -= 4;
  501. }
  502. av_new_packet(pkt, len);
  503. memcpy(pkt->data, buf, len);
  504. break;
  505. default:
  506. av_new_packet(pkt, len);
  507. memcpy(pkt->data, buf, len);
  508. break;
  509. }
  510. pkt->stream_index = st->index;
  511. }
  512. // now perform timestamp things....
  513. finalize_packet(s, pkt, timestamp);
  514. return rv;
  515. }
  516. void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
  517. {
  518. while (s->queue) {
  519. RTPPacket *next = s->queue->next;
  520. av_free(s->queue->buf);
  521. av_free(s->queue);
  522. s->queue = next;
  523. }
  524. s->seq = 0;
  525. s->queue_len = 0;
  526. s->prev_ret = 0;
  527. }
  528. static void enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
  529. {
  530. uint16_t seq = AV_RB16(buf + 2);
  531. RTPPacket *cur = s->queue, *prev = NULL, *packet;
  532. /* Find the correct place in the queue to insert the packet */
  533. while (cur) {
  534. int16_t diff = seq - cur->seq;
  535. if (diff < 0)
  536. break;
  537. prev = cur;
  538. cur = cur->next;
  539. }
  540. packet = av_mallocz(sizeof(*packet));
  541. if (!packet)
  542. return;
  543. packet->recvtime = av_gettime();
  544. packet->seq = seq;
  545. packet->len = len;
  546. packet->buf = buf;
  547. packet->next = cur;
  548. if (prev)
  549. prev->next = packet;
  550. else
  551. s->queue = packet;
  552. s->queue_len++;
  553. }
  554. static int has_next_packet(RTPDemuxContext *s)
  555. {
  556. return s->queue && s->queue->seq == (uint16_t) (s->seq + 1);
  557. }
  558. int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
  559. {
  560. return s->queue ? s->queue->recvtime : 0;
  561. }
  562. static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
  563. {
  564. int rv;
  565. RTPPacket *next;
  566. if (s->queue_len <= 0)
  567. return -1;
  568. if (!has_next_packet(s))
  569. av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
  570. "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
  571. /* Parse the first packet in the queue, and dequeue it */
  572. rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
  573. next = s->queue->next;
  574. av_free(s->queue->buf);
  575. av_free(s->queue);
  576. s->queue = next;
  577. s->queue_len--;
  578. return rv;
  579. }
  580. static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
  581. uint8_t **bufptr, int len)
  582. {
  583. uint8_t* buf = bufptr ? *bufptr : NULL;
  584. int ret, flags = 0;
  585. uint32_t timestamp;
  586. int rv= 0;
  587. if (!buf) {
  588. /* If parsing of the previous packet actually returned 0 or an error,
  589. * there's nothing more to be parsed from that packet, but we may have
  590. * indicated that we can return the next enqueued packet. */
  591. if (s->prev_ret <= 0)
  592. return rtp_parse_queued_packet(s, pkt);
  593. /* return the next packets, if any */
  594. if(s->st && s->parse_packet) {
  595. /* timestamp should be overwritten by parse_packet, if not,
  596. * the packet is left with pts == AV_NOPTS_VALUE */
  597. timestamp = RTP_NOTS_VALUE;
  598. rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
  599. s->st, pkt, &timestamp, NULL, 0, flags);
  600. finalize_packet(s, pkt, timestamp);
  601. return rv;
  602. } else {
  603. // TODO: Move to a dynamic packet handler (like above)
  604. if (s->read_buf_index >= s->read_buf_size)
  605. return AVERROR(EAGAIN);
  606. ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
  607. s->read_buf_size - s->read_buf_index);
  608. if (ret < 0)
  609. return AVERROR(EAGAIN);
  610. s->read_buf_index += ret;
  611. if (s->read_buf_index < s->read_buf_size)
  612. return 1;
  613. else
  614. return 0;
  615. }
  616. }
  617. if (len < 12)
  618. return -1;
  619. if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
  620. return -1;
  621. if (RTP_PT_IS_RTCP(buf[1])) {
  622. return rtcp_parse_packet(s, buf, len);
  623. }
  624. if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
  625. /* First packet, or no reordering */
  626. return rtp_parse_packet_internal(s, pkt, buf, len);
  627. } else {
  628. uint16_t seq = AV_RB16(buf + 2);
  629. int16_t diff = seq - s->seq;
  630. if (diff < 0) {
  631. /* Packet older than the previously emitted one, drop */
  632. av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
  633. "RTP: dropping old packet received too late\n");
  634. return -1;
  635. } else if (diff <= 1) {
  636. /* Correct packet */
  637. rv = rtp_parse_packet_internal(s, pkt, buf, len);
  638. return rv;
  639. } else {
  640. /* Still missing some packet, enqueue this one. */
  641. enqueue_packet(s, buf, len);
  642. *bufptr = NULL;
  643. /* Return the first enqueued packet if the queue is full,
  644. * even if we're missing something */
  645. if (s->queue_len >= s->queue_size)
  646. return rtp_parse_queued_packet(s, pkt);
  647. return -1;
  648. }
  649. }
  650. }
  651. /**
  652. * Parse an RTP or RTCP packet directly sent as a buffer.
  653. * @param s RTP parse context.
  654. * @param pkt returned packet
  655. * @param bufptr pointer to the input buffer or NULL to read the next packets
  656. * @param len buffer len
  657. * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
  658. * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
  659. */
  660. int ff_rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
  661. uint8_t **bufptr, int len)
  662. {
  663. int rv = rtp_parse_one_packet(s, pkt, bufptr, len);
  664. s->prev_ret = rv;
  665. while (rv == AVERROR(EAGAIN) && has_next_packet(s))
  666. rv = rtp_parse_queued_packet(s, pkt);
  667. return rv ? rv : has_next_packet(s);
  668. }
  669. void ff_rtp_parse_close(RTPDemuxContext *s)
  670. {
  671. ff_rtp_reset_packet_queue(s);
  672. if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
  673. ff_mpegts_parse_close(s->ts);
  674. }
  675. av_free(s);
  676. }
  677. int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
  678. int (*parse_fmtp)(AVStream *stream,
  679. PayloadContext *data,
  680. char *attr, char *value))
  681. {
  682. char attr[256];
  683. char *value;
  684. int res;
  685. int value_size = strlen(p) + 1;
  686. if (!(value = av_malloc(value_size))) {
  687. av_log(stream, AV_LOG_ERROR, "Failed to allocate data for FMTP.");
  688. return AVERROR(ENOMEM);
  689. }
  690. // remove protocol identifier
  691. while (*p && *p == ' ') p++; // strip spaces
  692. while (*p && *p != ' ') p++; // eat protocol identifier
  693. while (*p && *p == ' ') p++; // strip trailing spaces
  694. while (ff_rtsp_next_attr_and_value(&p,
  695. attr, sizeof(attr),
  696. value, value_size)) {
  697. res = parse_fmtp(stream, data, attr, value);
  698. if (res < 0 && res != AVERROR_PATCHWELCOME) {
  699. av_free(value);
  700. return res;
  701. }
  702. }
  703. av_free(value);
  704. return 0;
  705. }