rtpdec.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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 "libavutil/avstring.h"
  23. #include "libavcodec/get_bits.h"
  24. #include "avformat.h"
  25. #include "mpegts.h"
  26. #include "url.h"
  27. #include <unistd.h>
  28. #include "network.h"
  29. #include "rtpdec.h"
  30. #include "rtpdec_formats.h"
  31. //#define DEBUG
  32. /* TODO: - add RTCP statistics reporting (should be optional).
  33. - add support for h263/mpeg4 packetized output : IDEA: send a
  34. buffer to 'rtp_write_packet' contains all the packets for ONE
  35. frame. Each packet should have a four byte header containing
  36. the length in big endian format (same trick as
  37. 'ffio_open_dyn_packet_buf')
  38. */
  39. static RTPDynamicProtocolHandler ff_realmedia_mp3_dynamic_handler = {
  40. .enc_name = "X-MP3-draft-00",
  41. .codec_type = AVMEDIA_TYPE_AUDIO,
  42. .codec_id = CODEC_ID_MP3ADU,
  43. };
  44. /* statistics functions */
  45. static RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
  46. void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
  47. {
  48. handler->next= RTPFirstDynamicPayloadHandler;
  49. RTPFirstDynamicPayloadHandler= handler;
  50. }
  51. void av_register_rtp_dynamic_payload_handlers(void)
  52. {
  53. ff_register_dynamic_payload_handler(&ff_mp4v_es_dynamic_handler);
  54. ff_register_dynamic_payload_handler(&ff_mpeg4_generic_dynamic_handler);
  55. ff_register_dynamic_payload_handler(&ff_amr_nb_dynamic_handler);
  56. ff_register_dynamic_payload_handler(&ff_amr_wb_dynamic_handler);
  57. ff_register_dynamic_payload_handler(&ff_h263_1998_dynamic_handler);
  58. ff_register_dynamic_payload_handler(&ff_h263_2000_dynamic_handler);
  59. ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
  60. ff_register_dynamic_payload_handler(&ff_vorbis_dynamic_handler);
  61. ff_register_dynamic_payload_handler(&ff_theora_dynamic_handler);
  62. ff_register_dynamic_payload_handler(&ff_qdm2_dynamic_handler);
  63. ff_register_dynamic_payload_handler(&ff_svq3_dynamic_handler);
  64. ff_register_dynamic_payload_handler(&ff_mp4a_latm_dynamic_handler);
  65. ff_register_dynamic_payload_handler(&ff_vp8_dynamic_handler);
  66. ff_register_dynamic_payload_handler(&ff_qcelp_dynamic_handler);
  67. ff_register_dynamic_payload_handler(&ff_realmedia_mp3_dynamic_handler);
  68. ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfv_handler);
  69. ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfa_handler);
  70. ff_register_dynamic_payload_handler(&ff_qt_rtp_aud_handler);
  71. ff_register_dynamic_payload_handler(&ff_qt_rtp_vid_handler);
  72. ff_register_dynamic_payload_handler(&ff_quicktime_rtp_aud_handler);
  73. ff_register_dynamic_payload_handler(&ff_quicktime_rtp_vid_handler);
  74. 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 (!av_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 ff_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 + 1);
  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 ff_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 *ff_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. ff_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 (timestamp == RTP_NOTS_VALUE)
  382. return;
  383. if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && s->ic->nb_streams > 1) {
  384. int64_t addend;
  385. int delta_timestamp;
  386. /* compute pts from timestamp with received ntp_time */
  387. delta_timestamp = timestamp - s->last_rtcp_timestamp;
  388. /* convert to the PTS timebase */
  389. 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);
  390. pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
  391. delta_timestamp;
  392. return;
  393. }
  394. if (!s->base_timestamp)
  395. s->base_timestamp = timestamp;
  396. /* assume that the difference is INT32_MIN < x < INT32_MAX, but allow the first timestamp to exceed INT32_MAX */
  397. if (!s->timestamp)
  398. s->unwrapped_timestamp += timestamp;
  399. else
  400. s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
  401. s->timestamp = timestamp;
  402. pkt->pts = s->unwrapped_timestamp + s->range_start_offset - s->base_timestamp;
  403. }
  404. static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
  405. const uint8_t *buf, int len)
  406. {
  407. unsigned int ssrc, h;
  408. int payload_type, seq, ret, flags = 0;
  409. int ext;
  410. AVStream *st;
  411. uint32_t timestamp;
  412. int rv= 0;
  413. ext = buf[0] & 0x10;
  414. payload_type = buf[1] & 0x7f;
  415. if (buf[1] & 0x80)
  416. flags |= RTP_FLAG_MARKER;
  417. seq = AV_RB16(buf + 2);
  418. timestamp = AV_RB32(buf + 4);
  419. ssrc = AV_RB32(buf + 8);
  420. /* store the ssrc in the RTPDemuxContext */
  421. s->ssrc = ssrc;
  422. /* NOTE: we can handle only one payload type */
  423. if (s->payload_type != payload_type)
  424. return -1;
  425. st = s->st;
  426. // only do something with this if all the rtp checks pass...
  427. if(!rtp_valid_packet_in_sequence(&s->statistics, seq))
  428. {
  429. av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
  430. payload_type, seq, ((s->seq + 1) & 0xffff));
  431. return -1;
  432. }
  433. if (buf[0] & 0x20) {
  434. int padding = buf[len - 1];
  435. if (len >= 12 + padding)
  436. len -= padding;
  437. }
  438. s->seq = seq;
  439. len -= 12;
  440. buf += 12;
  441. /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
  442. if (ext) {
  443. if (len < 4)
  444. return -1;
  445. /* calculate the header extension length (stored as number
  446. * of 32-bit words) */
  447. ext = (AV_RB16(buf + 2) + 1) << 2;
  448. if (len < ext)
  449. return -1;
  450. // skip past RTP header extension
  451. len -= ext;
  452. buf += ext;
  453. }
  454. if (!st) {
  455. /* specific MPEG2TS demux support */
  456. ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
  457. /* The only error that can be returned from ff_mpegts_parse_packet
  458. * is "no more data to return from the provided buffer", so return
  459. * AVERROR(EAGAIN) for all errors */
  460. if (ret < 0)
  461. return AVERROR(EAGAIN);
  462. if (ret < len) {
  463. s->read_buf_size = len - ret;
  464. memcpy(s->buf, buf + ret, s->read_buf_size);
  465. s->read_buf_index = 0;
  466. return 1;
  467. }
  468. return 0;
  469. } else if (s->parse_packet) {
  470. rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
  471. s->st, pkt, &timestamp, buf, len, flags);
  472. } else {
  473. // at this point, the RTP header has been stripped; This is ASSUMING that there is only 1 CSRC, which in't wise.
  474. switch(st->codec->codec_id) {
  475. case CODEC_ID_MP2:
  476. case CODEC_ID_MP3:
  477. /* better than nothing: skip mpeg audio RTP header */
  478. if (len <= 4)
  479. return -1;
  480. h = AV_RB32(buf);
  481. len -= 4;
  482. buf += 4;
  483. av_new_packet(pkt, len);
  484. memcpy(pkt->data, buf, len);
  485. break;
  486. case CODEC_ID_MPEG1VIDEO:
  487. case CODEC_ID_MPEG2VIDEO:
  488. /* better than nothing: skip mpeg video RTP header */
  489. if (len <= 4)
  490. return -1;
  491. h = AV_RB32(buf);
  492. buf += 4;
  493. len -= 4;
  494. if (h & (1 << 26)) {
  495. /* mpeg2 */
  496. if (len <= 4)
  497. return -1;
  498. buf += 4;
  499. len -= 4;
  500. }
  501. av_new_packet(pkt, len);
  502. memcpy(pkt->data, buf, len);
  503. break;
  504. default:
  505. av_new_packet(pkt, len);
  506. memcpy(pkt->data, buf, len);
  507. break;
  508. }
  509. pkt->stream_index = st->index;
  510. }
  511. // now perform timestamp things....
  512. finalize_packet(s, pkt, timestamp);
  513. return rv;
  514. }
  515. void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
  516. {
  517. while (s->queue) {
  518. RTPPacket *next = s->queue->next;
  519. av_free(s->queue->buf);
  520. av_free(s->queue);
  521. s->queue = next;
  522. }
  523. s->seq = 0;
  524. s->queue_len = 0;
  525. s->prev_ret = 0;
  526. }
  527. static void enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
  528. {
  529. uint16_t seq = AV_RB16(buf + 2);
  530. RTPPacket *cur = s->queue, *prev = NULL, *packet;
  531. /* Find the correct place in the queue to insert the packet */
  532. while (cur) {
  533. int16_t diff = seq - cur->seq;
  534. if (diff < 0)
  535. break;
  536. prev = cur;
  537. cur = cur->next;
  538. }
  539. packet = av_mallocz(sizeof(*packet));
  540. if (!packet)
  541. return;
  542. packet->recvtime = av_gettime();
  543. packet->seq = seq;
  544. packet->len = len;
  545. packet->buf = buf;
  546. packet->next = cur;
  547. if (prev)
  548. prev->next = packet;
  549. else
  550. s->queue = packet;
  551. s->queue_len++;
  552. }
  553. static int has_next_packet(RTPDemuxContext *s)
  554. {
  555. return s->queue && s->queue->seq == (uint16_t) (s->seq + 1);
  556. }
  557. int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
  558. {
  559. return s->queue ? s->queue->recvtime : 0;
  560. }
  561. static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
  562. {
  563. int rv;
  564. RTPPacket *next;
  565. if (s->queue_len <= 0)
  566. return -1;
  567. if (!has_next_packet(s))
  568. av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
  569. "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
  570. /* Parse the first packet in the queue, and dequeue it */
  571. rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
  572. next = s->queue->next;
  573. av_free(s->queue->buf);
  574. av_free(s->queue);
  575. s->queue = next;
  576. s->queue_len--;
  577. return rv;
  578. }
  579. static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
  580. uint8_t **bufptr, int len)
  581. {
  582. uint8_t* buf = bufptr ? *bufptr : NULL;
  583. int ret, flags = 0;
  584. uint32_t timestamp;
  585. int rv= 0;
  586. if (!buf) {
  587. /* If parsing of the previous packet actually returned 0 or an error,
  588. * there's nothing more to be parsed from that packet, but we may have
  589. * indicated that we can return the next enqueued packet. */
  590. if (s->prev_ret <= 0)
  591. return rtp_parse_queued_packet(s, pkt);
  592. /* return the next packets, if any */
  593. if(s->st && s->parse_packet) {
  594. /* timestamp should be overwritten by parse_packet, if not,
  595. * the packet is left with pts == AV_NOPTS_VALUE */
  596. timestamp = RTP_NOTS_VALUE;
  597. rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
  598. s->st, pkt, &timestamp, NULL, 0, flags);
  599. finalize_packet(s, pkt, timestamp);
  600. return rv;
  601. } else {
  602. // TODO: Move to a dynamic packet handler (like above)
  603. if (s->read_buf_index >= s->read_buf_size)
  604. return AVERROR(EAGAIN);
  605. ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
  606. s->read_buf_size - s->read_buf_index);
  607. if (ret < 0)
  608. return AVERROR(EAGAIN);
  609. s->read_buf_index += ret;
  610. if (s->read_buf_index < s->read_buf_size)
  611. return 1;
  612. else
  613. return 0;
  614. }
  615. }
  616. if (len < 12)
  617. return -1;
  618. if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
  619. return -1;
  620. if (buf[1] >= RTCP_SR && buf[1] <= RTCP_APP) {
  621. return rtcp_parse_packet(s, buf, len);
  622. }
  623. if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
  624. /* First packet, or no reordering */
  625. return rtp_parse_packet_internal(s, pkt, buf, len);
  626. } else {
  627. uint16_t seq = AV_RB16(buf + 2);
  628. int16_t diff = seq - s->seq;
  629. if (diff < 0) {
  630. /* Packet older than the previously emitted one, drop */
  631. av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
  632. "RTP: dropping old packet received too late\n");
  633. return -1;
  634. } else if (diff <= 1) {
  635. /* Correct packet */
  636. rv = rtp_parse_packet_internal(s, pkt, buf, len);
  637. return rv;
  638. } else {
  639. /* Still missing some packet, enqueue this one. */
  640. enqueue_packet(s, buf, len);
  641. *bufptr = NULL;
  642. /* Return the first enqueued packet if the queue is full,
  643. * even if we're missing something */
  644. if (s->queue_len >= s->queue_size)
  645. return rtp_parse_queued_packet(s, pkt);
  646. return -1;
  647. }
  648. }
  649. }
  650. /**
  651. * Parse an RTP or RTCP packet directly sent as a buffer.
  652. * @param s RTP parse context.
  653. * @param pkt returned packet
  654. * @param bufptr pointer to the input buffer or NULL to read the next packets
  655. * @param len buffer len
  656. * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
  657. * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
  658. */
  659. int ff_rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
  660. uint8_t **bufptr, int len)
  661. {
  662. int rv = rtp_parse_one_packet(s, pkt, bufptr, len);
  663. s->prev_ret = rv;
  664. while (rv == AVERROR(EAGAIN) && has_next_packet(s))
  665. rv = rtp_parse_queued_packet(s, pkt);
  666. return rv ? rv : has_next_packet(s);
  667. }
  668. void ff_rtp_parse_close(RTPDemuxContext *s)
  669. {
  670. ff_rtp_reset_packet_queue(s);
  671. if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
  672. ff_mpegts_parse_close(s->ts);
  673. }
  674. av_free(s);
  675. }
  676. int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
  677. int (*parse_fmtp)(AVStream *stream,
  678. PayloadContext *data,
  679. char *attr, char *value))
  680. {
  681. char attr[256];
  682. char *value;
  683. int res;
  684. int value_size = strlen(p) + 1;
  685. if (!(value = av_malloc(value_size))) {
  686. av_log(stream, AV_LOG_ERROR, "Failed to allocate data for FMTP.");
  687. return AVERROR(ENOMEM);
  688. }
  689. // remove protocol identifier
  690. while (*p && *p == ' ') p++; // strip spaces
  691. while (*p && *p != ' ') p++; // eat protocol identifier
  692. while (*p && *p == ' ') p++; // strip trailing spaces
  693. while (ff_rtsp_next_attr_and_value(&p,
  694. attr, sizeof(attr),
  695. value, value_size)) {
  696. res = parse_fmtp(stream, data, attr, value);
  697. if (res < 0 && res != AVERROR_PATCHWELCOME) {
  698. av_free(value);
  699. return res;
  700. }
  701. }
  702. av_free(value);
  703. return 0;
  704. }