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.

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