rtpdec.c 25 KB

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