You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

567 lines
18KB

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