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.

569 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_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] != 200)
  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, 201);
  190. put_be16(pb, 7); /* length in words - 1 */
  191. put_be32(pb, s->ssrc); // our own SSRC
  192. put_be32(pb, s->ssrc); // XXX: should be the server's here!
  193. // some placeholders we should really fill...
  194. // RFC 1889/p64
  195. extended_max= stats->cycles + stats->max_seq;
  196. expected= extended_max - stats->base_seq + 1;
  197. lost= expected - stats->received;
  198. lost= FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
  199. expected_interval= expected - stats->expected_prior;
  200. stats->expected_prior= expected;
  201. received_interval= stats->received - stats->received_prior;
  202. stats->received_prior= stats->received;
  203. lost_interval= expected_interval - received_interval;
  204. if (expected_interval==0 || lost_interval<=0) fraction= 0;
  205. else fraction = (lost_interval<<8)/expected_interval;
  206. fraction= (fraction<<24) | lost;
  207. put_be32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
  208. put_be32(pb, extended_max); /* max sequence received */
  209. put_be32(pb, stats->jitter>>4); /* jitter */
  210. if(s->last_rtcp_ntp_time==AV_NOPTS_VALUE)
  211. {
  212. put_be32(pb, 0); /* last SR timestamp */
  213. put_be32(pb, 0); /* delay since last SR */
  214. } else {
  215. uint32_t middle_32_bits= s->last_rtcp_ntp_time>>16; // this is valid, right? do we need to handle 64 bit values special?
  216. uint32_t delay_since_last= ntp_time - s->last_rtcp_ntp_time;
  217. put_be32(pb, middle_32_bits); /* last SR timestamp */
  218. put_be32(pb, delay_since_last); /* delay since last SR */
  219. }
  220. // CNAME
  221. put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
  222. put_byte(pb, 202);
  223. len = strlen(s->hostname);
  224. put_be16(pb, (6 + len + 3) / 4); /* length in words - 1 */
  225. put_be32(pb, s->ssrc);
  226. put_byte(pb, 0x01);
  227. put_byte(pb, len);
  228. put_buffer(pb, s->hostname, len);
  229. // padding
  230. for (len = (6 + len) % 4; len % 4; len++) {
  231. put_byte(pb, 0);
  232. }
  233. put_flush_packet(pb);
  234. len = url_close_dyn_buf(pb, &buf);
  235. if ((len > 0) && buf) {
  236. int result;
  237. dprintf(s->ic, "sending %d bytes of RR\n", len);
  238. result= url_write(s->rtp_ctx, buf, len);
  239. dprintf(s->ic, "result from url_write: %d\n", result);
  240. av_free(buf);
  241. }
  242. return 0;
  243. }
  244. void rtp_send_punch_packets(URLContext* rtp_handle)
  245. {
  246. ByteIOContext *pb;
  247. uint8_t *buf;
  248. int len;
  249. /* Send a small RTP packet */
  250. if (url_open_dyn_buf(&pb) < 0)
  251. return;
  252. put_byte(pb, (RTP_VERSION << 6));
  253. put_byte(pb, 0); /* Payload type */
  254. put_be16(pb, 0); /* Seq */
  255. put_be32(pb, 0); /* Timestamp */
  256. put_be32(pb, 0); /* SSRC */
  257. put_flush_packet(pb);
  258. len = url_close_dyn_buf(pb, &buf);
  259. if ((len > 0) && buf)
  260. url_write(rtp_handle, buf, len);
  261. av_free(buf);
  262. /* Send a minimal RTCP RR */
  263. if (url_open_dyn_buf(&pb) < 0)
  264. return;
  265. put_byte(pb, (RTP_VERSION << 6));
  266. put_byte(pb, 201); /* receiver report */
  267. put_be16(pb, 1); /* length in words - 1 */
  268. put_be32(pb, 0); /* our own SSRC */
  269. put_flush_packet(pb);
  270. len = url_close_dyn_buf(pb, &buf);
  271. if ((len > 0) && buf)
  272. url_write(rtp_handle, buf, len);
  273. av_free(buf);
  274. }
  275. /**
  276. * open a new RTP parse context for stream 'st'. 'st' can be NULL for
  277. * MPEG2TS streams to indicate that they should be demuxed inside the
  278. * rtp demux (otherwise CODEC_ID_MPEG2TS packets are returned)
  279. */
  280. RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type)
  281. {
  282. RTPDemuxContext *s;
  283. s = av_mallocz(sizeof(RTPDemuxContext));
  284. if (!s)
  285. return NULL;
  286. s->payload_type = payload_type;
  287. s->last_rtcp_ntp_time = AV_NOPTS_VALUE;
  288. s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
  289. s->ic = s1;
  290. s->st = st;
  291. rtp_init_statistics(&s->statistics, 0); // do we know the initial sequence from sdp?
  292. if (!strcmp(ff_rtp_enc_name(payload_type), "MP2T")) {
  293. s->ts = ff_mpegts_parse_open(s->ic);
  294. if (s->ts == NULL) {
  295. av_free(s);
  296. return NULL;
  297. }
  298. } else {
  299. av_set_pts_info(st, 32, 1, 90000);
  300. switch(st->codec->codec_id) {
  301. case CODEC_ID_MPEG1VIDEO:
  302. case CODEC_ID_MPEG2VIDEO:
  303. case CODEC_ID_MP2:
  304. case CODEC_ID_MP3:
  305. case CODEC_ID_MPEG4:
  306. case CODEC_ID_H263:
  307. case CODEC_ID_H264:
  308. st->need_parsing = AVSTREAM_PARSE_FULL;
  309. break;
  310. default:
  311. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  312. av_set_pts_info(st, 32, 1, st->codec->sample_rate);
  313. }
  314. break;
  315. }
  316. }
  317. // needed to send back RTCP RR in RTSP sessions
  318. s->rtp_ctx = rtpc;
  319. gethostname(s->hostname, sizeof(s->hostname));
  320. return s;
  321. }
  322. void
  323. rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
  324. RTPDynamicProtocolHandler *handler)
  325. {
  326. s->dynamic_protocol_context = ctx;
  327. s->parse_packet = handler->parse_packet;
  328. }
  329. /**
  330. * This was the second switch in rtp_parse packet. Normalizes time, if required, sets stream_index, etc.
  331. */
  332. static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
  333. {
  334. if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && timestamp != RTP_NOTS_VALUE) {
  335. int64_t addend;
  336. int delta_timestamp;
  337. /* compute pts from timestamp with received ntp_time */
  338. delta_timestamp = timestamp - s->last_rtcp_timestamp;
  339. /* convert to the PTS timebase */
  340. 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);
  341. pkt->pts = s->range_start_offset + addend + delta_timestamp;
  342. }
  343. }
  344. /**
  345. * Parse an RTP or RTCP packet directly sent as a buffer.
  346. * @param s RTP parse context.
  347. * @param pkt returned packet
  348. * @param buf input buffer or NULL to read the next packets
  349. * @param len buffer len
  350. * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
  351. * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
  352. */
  353. int rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
  354. const uint8_t *buf, int len)
  355. {
  356. unsigned int ssrc, h;
  357. int payload_type, seq, ret, flags = 0;
  358. AVStream *st;
  359. uint32_t timestamp;
  360. int rv= 0;
  361. if (!buf) {
  362. /* return the next packets, if any */
  363. if(s->st && s->parse_packet) {
  364. /* timestamp should be overwritten by parse_packet, if not,
  365. * the packet is left with pts == AV_NOPTS_VALUE */
  366. timestamp = RTP_NOTS_VALUE;
  367. rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
  368. s->st, pkt, &timestamp, NULL, 0, flags);
  369. finalize_packet(s, pkt, timestamp);
  370. return rv;
  371. } else {
  372. // TODO: Move to a dynamic packet handler (like above)
  373. if (s->read_buf_index >= s->read_buf_size)
  374. return -1;
  375. ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
  376. s->read_buf_size - s->read_buf_index);
  377. if (ret < 0)
  378. return -1;
  379. s->read_buf_index += ret;
  380. if (s->read_buf_index < s->read_buf_size)
  381. return 1;
  382. else
  383. return 0;
  384. }
  385. }
  386. if (len < 12)
  387. return -1;
  388. if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
  389. return -1;
  390. if (buf[1] >= 200 && buf[1] <= 204) {
  391. rtcp_parse_packet(s, buf, len);
  392. return -1;
  393. }
  394. payload_type = buf[1] & 0x7f;
  395. if (buf[1] & 0x80)
  396. flags |= RTP_FLAG_MARKER;
  397. seq = AV_RB16(buf + 2);
  398. timestamp = AV_RB32(buf + 4);
  399. ssrc = AV_RB32(buf + 8);
  400. /* store the ssrc in the RTPDemuxContext */
  401. s->ssrc = ssrc;
  402. /* NOTE: we can handle only one payload type */
  403. if (s->payload_type != payload_type)
  404. return -1;
  405. st = s->st;
  406. // only do something with this if all the rtp checks pass...
  407. if(!rtp_valid_packet_in_sequence(&s->statistics, seq))
  408. {
  409. av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
  410. payload_type, seq, ((s->seq + 1) & 0xffff));
  411. return -1;
  412. }
  413. s->seq = seq;
  414. len -= 12;
  415. buf += 12;
  416. if (!st) {
  417. /* specific MPEG2TS demux support */
  418. ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
  419. if (ret < 0)
  420. return -1;
  421. if (ret < len) {
  422. s->read_buf_size = len - ret;
  423. memcpy(s->buf, buf + ret, s->read_buf_size);
  424. s->read_buf_index = 0;
  425. return 1;
  426. }
  427. return 0;
  428. } else if (s->parse_packet) {
  429. rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
  430. s->st, pkt, &timestamp, buf, len, flags);
  431. } else {
  432. // at this point, the RTP header has been stripped; This is ASSUMING that there is only 1 CSRC, which in't wise.
  433. switch(st->codec->codec_id) {
  434. case CODEC_ID_MP2:
  435. case CODEC_ID_MP3:
  436. /* better than nothing: skip mpeg audio RTP header */
  437. if (len <= 4)
  438. return -1;
  439. h = AV_RB32(buf);
  440. len -= 4;
  441. buf += 4;
  442. av_new_packet(pkt, len);
  443. memcpy(pkt->data, buf, len);
  444. break;
  445. case CODEC_ID_MPEG1VIDEO:
  446. case CODEC_ID_MPEG2VIDEO:
  447. /* better than nothing: skip mpeg video RTP header */
  448. if (len <= 4)
  449. return -1;
  450. h = AV_RB32(buf);
  451. buf += 4;
  452. len -= 4;
  453. if (h & (1 << 26)) {
  454. /* mpeg2 */
  455. if (len <= 4)
  456. return -1;
  457. buf += 4;
  458. len -= 4;
  459. }
  460. av_new_packet(pkt, len);
  461. memcpy(pkt->data, buf, len);
  462. break;
  463. default:
  464. av_new_packet(pkt, len);
  465. memcpy(pkt->data, buf, len);
  466. break;
  467. }
  468. pkt->stream_index = st->index;
  469. }
  470. // now perform timestamp things....
  471. finalize_packet(s, pkt, timestamp);
  472. return rv;
  473. }
  474. void rtp_parse_close(RTPDemuxContext *s)
  475. {
  476. if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
  477. ff_mpegts_parse_close(s->ts);
  478. }
  479. av_free(s);
  480. }
  481. int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
  482. int (*parse_fmtp)(AVStream *stream,
  483. PayloadContext *data,
  484. char *attr, char *value))
  485. {
  486. char attr[256];
  487. char *value;
  488. int res;
  489. int value_size = strlen(p) + 1;
  490. if (!(value = av_malloc(value_size))) {
  491. av_log(stream, AV_LOG_ERROR, "Failed to allocate data for FMTP.");
  492. return AVERROR(ENOMEM);
  493. }
  494. // remove protocol identifier
  495. while (*p && *p == ' ') p++; // strip spaces
  496. while (*p && *p != ' ') p++; // eat protocol identifier
  497. while (*p && *p == ' ') p++; // strip trailing spaces
  498. while (ff_rtsp_next_attr_and_value(&p,
  499. attr, sizeof(attr),
  500. value, value_size)) {
  501. res = parse_fmtp(stream, data, attr, value);
  502. if (res < 0 && res != AVERROR_PATCHWELCOME) {
  503. av_free(value);
  504. return res;
  505. }
  506. }
  507. av_free(value);
  508. return 0;
  509. }