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.

534 lines
17KB

  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_xiph.h"
  35. //#define DEBUG
  36. /* TODO: - add RTCP statistics reporting (should be optional).
  37. - add support for h263/mpeg4 packetized output : IDEA: send a
  38. buffer to 'rtp_write_packet' contains all the packets for ONE
  39. frame. Each packet should have a four byte header containing
  40. the length in big endian format (same trick as
  41. 'url_open_dyn_packet_buf')
  42. */
  43. /* statistics functions */
  44. RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
  45. void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
  46. {
  47. handler->next= RTPFirstDynamicPayloadHandler;
  48. RTPFirstDynamicPayloadHandler= handler;
  49. }
  50. void av_register_rtp_dynamic_payload_handlers(void)
  51. {
  52. ff_register_dynamic_payload_handler(&ff_mp4v_es_dynamic_handler);
  53. ff_register_dynamic_payload_handler(&ff_mpeg4_generic_dynamic_handler);
  54. ff_register_dynamic_payload_handler(&ff_amr_nb_dynamic_handler);
  55. ff_register_dynamic_payload_handler(&ff_amr_wb_dynamic_handler);
  56. ff_register_dynamic_payload_handler(&ff_h263_1998_dynamic_handler);
  57. ff_register_dynamic_payload_handler(&ff_h263_2000_dynamic_handler);
  58. ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
  59. ff_register_dynamic_payload_handler(&ff_vorbis_dynamic_handler);
  60. ff_register_dynamic_payload_handler(&ff_theora_dynamic_handler);
  61. ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfv_handler);
  62. ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfa_handler);
  63. }
  64. static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
  65. {
  66. if (buf[1] != 200)
  67. return -1;
  68. s->last_rtcp_ntp_time = AV_RB64(buf + 8);
  69. if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE)
  70. s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
  71. s->last_rtcp_timestamp = AV_RB32(buf + 16);
  72. return 0;
  73. }
  74. #define RTP_SEQ_MOD (1<<16)
  75. /**
  76. * called on parse open packet
  77. */
  78. static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence) // called on parse open packet.
  79. {
  80. memset(s, 0, sizeof(RTPStatistics));
  81. s->max_seq= base_sequence;
  82. s->probation= 1;
  83. }
  84. /**
  85. * called whenever there is a large jump in sequence numbers, or when they get out of probation...
  86. */
  87. static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
  88. {
  89. s->max_seq= seq;
  90. s->cycles= 0;
  91. s->base_seq= seq -1;
  92. s->bad_seq= RTP_SEQ_MOD + 1;
  93. s->received= 0;
  94. s->expected_prior= 0;
  95. s->received_prior= 0;
  96. s->jitter= 0;
  97. s->transit= 0;
  98. }
  99. /**
  100. * returns 1 if we should handle this packet.
  101. */
  102. static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
  103. {
  104. uint16_t udelta= seq - s->max_seq;
  105. const int MAX_DROPOUT= 3000;
  106. const int MAX_MISORDER = 100;
  107. const int MIN_SEQUENTIAL = 2;
  108. /* source not valid until MIN_SEQUENTIAL packets with sequence seq. numbers have been received */
  109. if(s->probation)
  110. {
  111. if(seq==s->max_seq + 1) {
  112. s->probation--;
  113. s->max_seq= seq;
  114. if(s->probation==0) {
  115. rtp_init_sequence(s, seq);
  116. s->received++;
  117. return 1;
  118. }
  119. } else {
  120. s->probation= MIN_SEQUENTIAL - 1;
  121. s->max_seq = seq;
  122. }
  123. } else if (udelta < MAX_DROPOUT) {
  124. // in order, with permissible gap
  125. if(seq < s->max_seq) {
  126. //sequence number wrapped; count antother 64k cycles
  127. s->cycles += RTP_SEQ_MOD;
  128. }
  129. s->max_seq= seq;
  130. } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
  131. // sequence made a large jump...
  132. if(seq==s->bad_seq) {
  133. // two sequential packets-- assume that the other side restarted without telling us; just resync.
  134. rtp_init_sequence(s, seq);
  135. } else {
  136. s->bad_seq= (seq + 1) & (RTP_SEQ_MOD-1);
  137. return 0;
  138. }
  139. } else {
  140. // duplicate or reordered packet...
  141. }
  142. s->received++;
  143. return 1;
  144. }
  145. #if 0
  146. /**
  147. * This function is currently unused; without a valid local ntp time, I don't see how we could calculate the
  148. * difference between the arrival and sent timestamp. As a result, the jitter and transit statistics values
  149. * never change. I left this in in case someone else can see a way. (rdm)
  150. */
  151. static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp, uint32_t arrival_timestamp)
  152. {
  153. uint32_t transit= arrival_timestamp - sent_timestamp;
  154. int d;
  155. s->transit= transit;
  156. d= FFABS(transit - s->transit);
  157. s->jitter += d - ((s->jitter + 8)>>4);
  158. }
  159. #endif
  160. int rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
  161. {
  162. ByteIOContext *pb;
  163. uint8_t *buf;
  164. int len;
  165. int rtcp_bytes;
  166. RTPStatistics *stats= &s->statistics;
  167. uint32_t lost;
  168. uint32_t extended_max;
  169. uint32_t expected_interval;
  170. uint32_t received_interval;
  171. uint32_t lost_interval;
  172. uint32_t expected;
  173. uint32_t fraction;
  174. uint64_t ntp_time= s->last_rtcp_ntp_time; // TODO: Get local ntp time?
  175. if (!s->rtp_ctx || (count < 1))
  176. return -1;
  177. /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
  178. /* XXX: mpeg pts hardcoded. RTCP send every 0.5 seconds */
  179. s->octet_count += count;
  180. rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
  181. RTCP_TX_RATIO_DEN;
  182. rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
  183. if (rtcp_bytes < 28)
  184. return -1;
  185. s->last_octet_count = s->octet_count;
  186. if (url_open_dyn_buf(&pb) < 0)
  187. return -1;
  188. // Receiver Report
  189. put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
  190. put_byte(pb, 201);
  191. put_be16(pb, 7); /* length in words - 1 */
  192. put_be32(pb, s->ssrc); // our own SSRC
  193. put_be32(pb, s->ssrc); // XXX: should be the server's here!
  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, 202);
  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, 201); /* 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) {
  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= 0; ///< Should not be used if buf is NULL, but should be set to the timestamp of the packet returned....
  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. }