rtpdec.c 25 KB

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