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.

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