rtpdec.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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/bitstream.h"
  24. #include "avformat.h"
  25. #include "mpegts.h"
  26. #include <unistd.h>
  27. #include "network.h"
  28. #include "rtpdec.h"
  29. #include "rtp_h264.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. 'url_open_dyn_packet_buf')
  37. */
  38. /* statistics functions */
  39. RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
  40. static RTPDynamicProtocolHandler mp4v_es_handler= {"MP4V-ES", CODEC_TYPE_VIDEO, CODEC_ID_MPEG4};
  41. static RTPDynamicProtocolHandler mpeg4_generic_handler= {"mpeg4-generic", CODEC_TYPE_AUDIO, CODEC_ID_AAC};
  42. void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
  43. {
  44. handler->next= RTPFirstDynamicPayloadHandler;
  45. RTPFirstDynamicPayloadHandler= handler;
  46. }
  47. void av_register_rtp_dynamic_payload_handlers(void)
  48. {
  49. ff_register_dynamic_payload_handler(&mp4v_es_handler);
  50. ff_register_dynamic_payload_handler(&mpeg4_generic_handler);
  51. ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
  52. }
  53. static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
  54. {
  55. if (buf[1] != 200)
  56. return -1;
  57. s->last_rtcp_ntp_time = AV_RB64(buf + 8);
  58. if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE)
  59. s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
  60. s->last_rtcp_timestamp = AV_RB32(buf + 16);
  61. return 0;
  62. }
  63. #define RTP_SEQ_MOD (1<<16)
  64. /**
  65. * called on parse open packet
  66. */
  67. static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence) // called on parse open packet.
  68. {
  69. memset(s, 0, sizeof(RTPStatistics));
  70. s->max_seq= base_sequence;
  71. s->probation= 1;
  72. }
  73. /**
  74. * called whenever there is a large jump in sequence numbers, or when they get out of probation...
  75. */
  76. static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
  77. {
  78. s->max_seq= seq;
  79. s->cycles= 0;
  80. s->base_seq= seq -1;
  81. s->bad_seq= RTP_SEQ_MOD + 1;
  82. s->received= 0;
  83. s->expected_prior= 0;
  84. s->received_prior= 0;
  85. s->jitter= 0;
  86. s->transit= 0;
  87. }
  88. /**
  89. * returns 1 if we should handle this packet.
  90. */
  91. static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
  92. {
  93. uint16_t udelta= seq - s->max_seq;
  94. const int MAX_DROPOUT= 3000;
  95. const int MAX_MISORDER = 100;
  96. const int MIN_SEQUENTIAL = 2;
  97. /* source not valid until MIN_SEQUENTIAL packets with sequence seq. numbers have been received */
  98. if(s->probation)
  99. {
  100. if(seq==s->max_seq + 1) {
  101. s->probation--;
  102. s->max_seq= seq;
  103. if(s->probation==0) {
  104. rtp_init_sequence(s, seq);
  105. s->received++;
  106. return 1;
  107. }
  108. } else {
  109. s->probation= MIN_SEQUENTIAL - 1;
  110. s->max_seq = seq;
  111. }
  112. } else if (udelta < MAX_DROPOUT) {
  113. // in order, with permissible gap
  114. if(seq < s->max_seq) {
  115. //sequence number wrapped; count antother 64k cycles
  116. s->cycles += RTP_SEQ_MOD;
  117. }
  118. s->max_seq= seq;
  119. } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
  120. // sequence made a large jump...
  121. if(seq==s->bad_seq) {
  122. // two sequential packets-- assume that the other side restarted without telling us; just resync.
  123. rtp_init_sequence(s, seq);
  124. } else {
  125. s->bad_seq= (seq + 1) & (RTP_SEQ_MOD-1);
  126. return 0;
  127. }
  128. } else {
  129. // duplicate or reordered packet...
  130. }
  131. s->received++;
  132. return 1;
  133. }
  134. #if 0
  135. /**
  136. * This function is currently unused; without a valid local ntp time, I don't see how we could calculate the
  137. * difference between the arrival and sent timestamp. As a result, the jitter and transit statistics values
  138. * never change. I left this in in case someone else can see a way. (rdm)
  139. */
  140. static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp, uint32_t arrival_timestamp)
  141. {
  142. uint32_t transit= arrival_timestamp - sent_timestamp;
  143. int d;
  144. s->transit= transit;
  145. d= FFABS(transit - s->transit);
  146. s->jitter += d - ((s->jitter + 8)>>4);
  147. }
  148. #endif
  149. int rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
  150. {
  151. ByteIOContext *pb;
  152. uint8_t *buf;
  153. int len;
  154. int rtcp_bytes;
  155. RTPStatistics *stats= &s->statistics;
  156. uint32_t lost;
  157. uint32_t extended_max;
  158. uint32_t expected_interval;
  159. uint32_t received_interval;
  160. uint32_t lost_interval;
  161. uint32_t expected;
  162. uint32_t fraction;
  163. uint64_t ntp_time= s->last_rtcp_ntp_time; // TODO: Get local ntp time?
  164. if (!s->rtp_ctx || (count < 1))
  165. return -1;
  166. /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
  167. /* XXX: mpeg pts hardcoded. RTCP send every 0.5 seconds */
  168. s->octet_count += count;
  169. rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
  170. RTCP_TX_RATIO_DEN;
  171. rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
  172. if (rtcp_bytes < 28)
  173. return -1;
  174. s->last_octet_count = s->octet_count;
  175. if (url_open_dyn_buf(&pb) < 0)
  176. return -1;
  177. // Receiver Report
  178. put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
  179. put_byte(pb, 201);
  180. put_be16(pb, 7); /* length in words - 1 */
  181. put_be32(pb, s->ssrc); // our own SSRC
  182. put_be32(pb, s->ssrc); // XXX: should be the server's here!
  183. // some placeholders we should really fill...
  184. // RFC 1889/p64
  185. extended_max= stats->cycles + stats->max_seq;
  186. expected= extended_max - stats->base_seq + 1;
  187. lost= expected - stats->received;
  188. lost= FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
  189. expected_interval= expected - stats->expected_prior;
  190. stats->expected_prior= expected;
  191. received_interval= stats->received - stats->received_prior;
  192. stats->received_prior= stats->received;
  193. lost_interval= expected_interval - received_interval;
  194. if (expected_interval==0 || lost_interval<=0) fraction= 0;
  195. else fraction = (lost_interval<<8)/expected_interval;
  196. fraction= (fraction<<24) | lost;
  197. put_be32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
  198. put_be32(pb, extended_max); /* max sequence received */
  199. put_be32(pb, stats->jitter>>4); /* jitter */
  200. if(s->last_rtcp_ntp_time==AV_NOPTS_VALUE)
  201. {
  202. put_be32(pb, 0); /* last SR timestamp */
  203. put_be32(pb, 0); /* delay since last SR */
  204. } else {
  205. uint32_t middle_32_bits= s->last_rtcp_ntp_time>>16; // this is valid, right? do we need to handle 64 bit values special?
  206. uint32_t delay_since_last= ntp_time - s->last_rtcp_ntp_time;
  207. put_be32(pb, middle_32_bits); /* last SR timestamp */
  208. put_be32(pb, delay_since_last); /* delay since last SR */
  209. }
  210. // CNAME
  211. put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
  212. put_byte(pb, 202);
  213. len = strlen(s->hostname);
  214. put_be16(pb, (6 + len + 3) / 4); /* length in words - 1 */
  215. put_be32(pb, s->ssrc);
  216. put_byte(pb, 0x01);
  217. put_byte(pb, len);
  218. put_buffer(pb, s->hostname, len);
  219. // padding
  220. for (len = (6 + len) % 4; len % 4; len++) {
  221. put_byte(pb, 0);
  222. }
  223. put_flush_packet(pb);
  224. len = url_close_dyn_buf(pb, &buf);
  225. if ((len > 0) && buf) {
  226. int result;
  227. dprintf(s->ic, "sending %d bytes of RR\n", len);
  228. result= url_write(s->rtp_ctx, buf, len);
  229. dprintf(s->ic, "result from url_write: %d\n", result);
  230. av_free(buf);
  231. }
  232. return 0;
  233. }
  234. /**
  235. * open a new RTP parse context for stream 'st'. 'st' can be NULL for
  236. * MPEG2TS streams to indicate that they should be demuxed inside the
  237. * rtp demux (otherwise CODEC_ID_MPEG2TS packets are returned)
  238. * TODO: change this to not take rtp_payload data, and use the new dynamic payload system.
  239. */
  240. RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, RTPPayloadData *rtp_payload_data)
  241. {
  242. RTPDemuxContext *s;
  243. s = av_mallocz(sizeof(RTPDemuxContext));
  244. if (!s)
  245. return NULL;
  246. s->payload_type = payload_type;
  247. s->last_rtcp_ntp_time = AV_NOPTS_VALUE;
  248. s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
  249. s->ic = s1;
  250. s->st = st;
  251. s->rtp_payload_data = rtp_payload_data;
  252. rtp_init_statistics(&s->statistics, 0); // do we know the initial sequence from sdp?
  253. if (!strcmp(ff_rtp_enc_name(payload_type), "MP2T")) {
  254. s->ts = mpegts_parse_open(s->ic);
  255. if (s->ts == NULL) {
  256. av_free(s);
  257. return NULL;
  258. }
  259. } else {
  260. av_set_pts_info(st, 32, 1, 90000);
  261. switch(st->codec->codec_id) {
  262. case CODEC_ID_MPEG1VIDEO:
  263. case CODEC_ID_MPEG2VIDEO:
  264. case CODEC_ID_MP2:
  265. case CODEC_ID_MP3:
  266. case CODEC_ID_MPEG4:
  267. case CODEC_ID_H264:
  268. st->need_parsing = AVSTREAM_PARSE_FULL;
  269. break;
  270. default:
  271. if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
  272. av_set_pts_info(st, 32, 1, st->codec->sample_rate);
  273. }
  274. break;
  275. }
  276. }
  277. // needed to send back RTCP RR in RTSP sessions
  278. s->rtp_ctx = rtpc;
  279. gethostname(s->hostname, sizeof(s->hostname));
  280. return s;
  281. }
  282. void
  283. rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
  284. RTPDynamicProtocolHandler *handler)
  285. {
  286. s->dynamic_protocol_context = ctx;
  287. s->parse_packet = handler->parse_packet;
  288. }
  289. static int rtp_parse_mp4_au(RTPDemuxContext *s, const uint8_t *buf)
  290. {
  291. int au_headers_length, au_header_size, i;
  292. GetBitContext getbitcontext;
  293. RTPPayloadData *infos;
  294. infos = s->rtp_payload_data;
  295. if (infos == NULL)
  296. return -1;
  297. /* decode the first 2 bytes where the AUHeader sections are stored
  298. length in bits */
  299. au_headers_length = AV_RB16(buf);
  300. if (au_headers_length > RTP_MAX_PACKET_LENGTH)
  301. return -1;
  302. infos->au_headers_length_bytes = (au_headers_length + 7) / 8;
  303. /* skip AU headers length section (2 bytes) */
  304. buf += 2;
  305. init_get_bits(&getbitcontext, buf, infos->au_headers_length_bytes * 8);
  306. /* XXX: Wrong if optionnal additional sections are present (cts, dts etc...) */
  307. au_header_size = infos->sizelength + infos->indexlength;
  308. if (au_header_size <= 0 || (au_headers_length % au_header_size != 0))
  309. return -1;
  310. infos->nb_au_headers = au_headers_length / au_header_size;
  311. infos->au_headers = av_malloc(sizeof(struct AUHeaders) * infos->nb_au_headers);
  312. /* XXX: We handle multiple AU Section as only one (need to fix this for interleaving)
  313. In my test, the FAAD decoder does not behave correctly when sending each AU one by one
  314. but does when sending the whole as one big packet... */
  315. infos->au_headers[0].size = 0;
  316. infos->au_headers[0].index = 0;
  317. for (i = 0; i < infos->nb_au_headers; ++i) {
  318. infos->au_headers[0].size += get_bits_long(&getbitcontext, infos->sizelength);
  319. infos->au_headers[0].index = get_bits_long(&getbitcontext, infos->indexlength);
  320. }
  321. infos->nb_au_headers = 1;
  322. return 0;
  323. }
  324. /**
  325. * This was the second switch in rtp_parse packet. Normalizes time, if required, sets stream_index, etc.
  326. */
  327. static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
  328. {
  329. if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE) {
  330. int64_t addend;
  331. int delta_timestamp;
  332. /* compute pts from timestamp with received ntp_time */
  333. delta_timestamp = timestamp - s->last_rtcp_timestamp;
  334. /* convert to the PTS timebase */
  335. 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);
  336. pkt->pts = addend + delta_timestamp;
  337. }
  338. pkt->stream_index = s->st->index;
  339. }
  340. /**
  341. * Parse an RTP or RTCP packet directly sent as a buffer.
  342. * @param s RTP parse context.
  343. * @param pkt returned packet
  344. * @param buf input buffer or NULL to read the next packets
  345. * @param len buffer len
  346. * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
  347. * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
  348. */
  349. int rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
  350. const uint8_t *buf, int len)
  351. {
  352. unsigned int ssrc, h;
  353. int payload_type, seq, ret, flags = 0;
  354. AVStream *st;
  355. uint32_t timestamp;
  356. int rv= 0;
  357. if (!buf) {
  358. /* return the next packets, if any */
  359. if(s->st && s->parse_packet) {
  360. timestamp= 0; ///< Should not be used if buf is NULL, but should be set to the timestamp of the packet returned....
  361. rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
  362. s->st, pkt, &timestamp, NULL, 0, flags);
  363. finalize_packet(s, pkt, timestamp);
  364. return rv;
  365. } else {
  366. // TODO: Move to a dynamic packet handler (like above)
  367. if (s->read_buf_index >= s->read_buf_size)
  368. return -1;
  369. ret = mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
  370. s->read_buf_size - s->read_buf_index);
  371. if (ret < 0)
  372. return -1;
  373. s->read_buf_index += ret;
  374. if (s->read_buf_index < s->read_buf_size)
  375. return 1;
  376. else
  377. return 0;
  378. }
  379. }
  380. if (len < 12)
  381. return -1;
  382. if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
  383. return -1;
  384. if (buf[1] >= 200 && buf[1] <= 204) {
  385. rtcp_parse_packet(s, buf, len);
  386. return -1;
  387. }
  388. payload_type = buf[1] & 0x7f;
  389. if (buf[1] & 0x80)
  390. flags |= RTP_FLAG_MARKER;
  391. seq = AV_RB16(buf + 2);
  392. timestamp = AV_RB32(buf + 4);
  393. ssrc = AV_RB32(buf + 8);
  394. /* store the ssrc in the RTPDemuxContext */
  395. s->ssrc = ssrc;
  396. /* NOTE: we can handle only one payload type */
  397. if (s->payload_type != payload_type)
  398. return -1;
  399. st = s->st;
  400. // only do something with this if all the rtp checks pass...
  401. if(!rtp_valid_packet_in_sequence(&s->statistics, seq))
  402. {
  403. av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
  404. payload_type, seq, ((s->seq + 1) & 0xffff));
  405. return -1;
  406. }
  407. s->seq = seq;
  408. len -= 12;
  409. buf += 12;
  410. if (!st) {
  411. /* specific MPEG2TS demux support */
  412. ret = mpegts_parse_packet(s->ts, pkt, buf, len);
  413. if (ret < 0)
  414. return -1;
  415. if (ret < len) {
  416. s->read_buf_size = len - ret;
  417. memcpy(s->buf, buf + ret, s->read_buf_size);
  418. s->read_buf_index = 0;
  419. return 1;
  420. }
  421. } else if (s->parse_packet) {
  422. rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
  423. s->st, pkt, &timestamp, buf, len, flags);
  424. } else {
  425. // at this point, the RTP header has been stripped; This is ASSUMING that there is only 1 CSRC, which in't wise.
  426. switch(st->codec->codec_id) {
  427. case CODEC_ID_MP2:
  428. /* better than nothing: skip mpeg audio RTP header */
  429. if (len <= 4)
  430. return -1;
  431. h = AV_RB32(buf);
  432. len -= 4;
  433. buf += 4;
  434. av_new_packet(pkt, len);
  435. memcpy(pkt->data, buf, len);
  436. break;
  437. case CODEC_ID_MPEG1VIDEO:
  438. case CODEC_ID_MPEG2VIDEO:
  439. /* better than nothing: skip mpeg video RTP header */
  440. if (len <= 4)
  441. return -1;
  442. h = AV_RB32(buf);
  443. buf += 4;
  444. len -= 4;
  445. if (h & (1 << 26)) {
  446. /* mpeg2 */
  447. if (len <= 4)
  448. return -1;
  449. buf += 4;
  450. len -= 4;
  451. }
  452. av_new_packet(pkt, len);
  453. memcpy(pkt->data, buf, len);
  454. break;
  455. // moved from below, verbatim. this is because this section handles packets, and the lower switch handles
  456. // timestamps.
  457. // TODO: Put this into a dynamic packet handler...
  458. case CODEC_ID_AAC:
  459. if (rtp_parse_mp4_au(s, buf))
  460. return -1;
  461. {
  462. RTPPayloadData *infos = s->rtp_payload_data;
  463. if (infos == NULL)
  464. return -1;
  465. buf += infos->au_headers_length_bytes + 2;
  466. len -= infos->au_headers_length_bytes + 2;
  467. /* XXX: Fixme we only handle the case where rtp_parse_mp4_au define
  468. one au_header */
  469. av_new_packet(pkt, infos->au_headers[0].size);
  470. memcpy(pkt->data, buf, infos->au_headers[0].size);
  471. buf += infos->au_headers[0].size;
  472. len -= infos->au_headers[0].size;
  473. }
  474. s->read_buf_size = len;
  475. rv= 0;
  476. break;
  477. default:
  478. av_new_packet(pkt, len);
  479. memcpy(pkt->data, buf, len);
  480. break;
  481. }
  482. // now perform timestamp things....
  483. finalize_packet(s, pkt, timestamp);
  484. }
  485. return rv;
  486. }
  487. void rtp_parse_close(RTPDemuxContext *s)
  488. {
  489. // TODO: fold this into the protocol specific data fields.
  490. if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
  491. mpegts_parse_close(s->ts);
  492. }
  493. av_free(s);
  494. }