rtpdec.c 25 KB

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