rtpdec.c 18 KB

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