rtpdec.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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. #include "libavutil/mathematics.h"
  22. #include "libavutil/avstring.h"
  23. #include "libavutil/intreadwrite.h"
  24. #include "libavutil/mem.h"
  25. #include "libavutil/time.h"
  26. #include "libavcodec/bytestream.h"
  27. #include "avformat.h"
  28. #include "network.h"
  29. #include "srtp.h"
  30. #include "url.h"
  31. #include "rtpdec.h"
  32. #include "rtpdec_formats.h"
  33. #include "internal.h"
  34. #define MIN_FEEDBACK_INTERVAL 200000 /* 200 ms in us */
  35. static const RTPDynamicProtocolHandler l24_dynamic_handler = {
  36. .enc_name = "L24",
  37. .codec_type = AVMEDIA_TYPE_AUDIO,
  38. .codec_id = AV_CODEC_ID_PCM_S24BE,
  39. };
  40. static const RTPDynamicProtocolHandler gsm_dynamic_handler = {
  41. .enc_name = "GSM",
  42. .codec_type = AVMEDIA_TYPE_AUDIO,
  43. .codec_id = AV_CODEC_ID_GSM,
  44. };
  45. static const RTPDynamicProtocolHandler realmedia_mp3_dynamic_handler = {
  46. .enc_name = "X-MP3-draft-00",
  47. .codec_type = AVMEDIA_TYPE_AUDIO,
  48. .codec_id = AV_CODEC_ID_MP3ADU,
  49. };
  50. static const RTPDynamicProtocolHandler speex_dynamic_handler = {
  51. .enc_name = "speex",
  52. .codec_type = AVMEDIA_TYPE_AUDIO,
  53. .codec_id = AV_CODEC_ID_SPEEX,
  54. };
  55. static const RTPDynamicProtocolHandler t140_dynamic_handler = { /* RFC 4103 */
  56. .enc_name = "t140",
  57. .codec_type = AVMEDIA_TYPE_SUBTITLE,
  58. .codec_id = AV_CODEC_ID_TEXT,
  59. };
  60. extern const RTPDynamicProtocolHandler ff_rdt_video_handler;
  61. extern const RTPDynamicProtocolHandler ff_rdt_audio_handler;
  62. extern const RTPDynamicProtocolHandler ff_rdt_live_video_handler;
  63. extern const RTPDynamicProtocolHandler ff_rdt_live_audio_handler;
  64. static const RTPDynamicProtocolHandler *const rtp_dynamic_protocol_handler_list[] = {
  65. /* rtp */
  66. &ff_ac3_dynamic_handler,
  67. &ff_amr_nb_dynamic_handler,
  68. &ff_amr_wb_dynamic_handler,
  69. &ff_av1_dynamic_handler,
  70. &ff_dv_dynamic_handler,
  71. &ff_g726_16_dynamic_handler,
  72. &ff_g726_24_dynamic_handler,
  73. &ff_g726_32_dynamic_handler,
  74. &ff_g726_40_dynamic_handler,
  75. &ff_g726le_16_dynamic_handler,
  76. &ff_g726le_24_dynamic_handler,
  77. &ff_g726le_32_dynamic_handler,
  78. &ff_g726le_40_dynamic_handler,
  79. &ff_h261_dynamic_handler,
  80. &ff_h263_1998_dynamic_handler,
  81. &ff_h263_2000_dynamic_handler,
  82. &ff_h263_rfc2190_dynamic_handler,
  83. &ff_h264_dynamic_handler,
  84. &ff_hevc_dynamic_handler,
  85. &ff_ilbc_dynamic_handler,
  86. &ff_jpeg_dynamic_handler,
  87. &ff_mp4a_latm_dynamic_handler,
  88. &ff_mp4v_es_dynamic_handler,
  89. &ff_mpeg_audio_dynamic_handler,
  90. &ff_mpeg_audio_robust_dynamic_handler,
  91. &ff_mpeg_video_dynamic_handler,
  92. &ff_mpeg4_generic_dynamic_handler,
  93. &ff_mpegts_dynamic_handler,
  94. &ff_ms_rtp_asf_pfa_handler,
  95. &ff_ms_rtp_asf_pfv_handler,
  96. &ff_qcelp_dynamic_handler,
  97. &ff_qdm2_dynamic_handler,
  98. &ff_qt_rtp_aud_handler,
  99. &ff_qt_rtp_vid_handler,
  100. &ff_quicktime_rtp_aud_handler,
  101. &ff_quicktime_rtp_vid_handler,
  102. &ff_rfc4175_rtp_handler,
  103. &ff_svq3_dynamic_handler,
  104. &ff_theora_dynamic_handler,
  105. &ff_vc2hq_dynamic_handler,
  106. &ff_vorbis_dynamic_handler,
  107. &ff_vp8_dynamic_handler,
  108. &ff_vp9_dynamic_handler,
  109. &gsm_dynamic_handler,
  110. &l24_dynamic_handler,
  111. &ff_opus_dynamic_handler,
  112. &realmedia_mp3_dynamic_handler,
  113. &speex_dynamic_handler,
  114. &t140_dynamic_handler,
  115. /* rdt */
  116. &ff_rdt_video_handler,
  117. &ff_rdt_audio_handler,
  118. &ff_rdt_live_video_handler,
  119. &ff_rdt_live_audio_handler,
  120. NULL,
  121. };
  122. /**
  123. * Iterate over all registered rtp dynamic protocol handlers.
  124. *
  125. * @param opaque a pointer where libavformat will store the iteration state.
  126. * Must point to NULL to start the iteration.
  127. *
  128. * @return the next registered rtp dynamic protocol handler
  129. * or NULL when the iteration is finished
  130. */
  131. static const RTPDynamicProtocolHandler *rtp_handler_iterate(void **opaque)
  132. {
  133. uintptr_t i = (uintptr_t)*opaque;
  134. const RTPDynamicProtocolHandler *r = rtp_dynamic_protocol_handler_list[i];
  135. if (r)
  136. *opaque = (void*)(i + 1);
  137. return r;
  138. }
  139. const RTPDynamicProtocolHandler *ff_rtp_handler_find_by_name(const char *name,
  140. enum AVMediaType codec_type)
  141. {
  142. void *i = 0;
  143. const RTPDynamicProtocolHandler *handler;
  144. while (handler = rtp_handler_iterate(&i)) {
  145. if (handler->enc_name &&
  146. !av_strcasecmp(name, handler->enc_name) &&
  147. codec_type == handler->codec_type)
  148. return handler;
  149. }
  150. return NULL;
  151. }
  152. const RTPDynamicProtocolHandler *ff_rtp_handler_find_by_id(int id,
  153. enum AVMediaType codec_type)
  154. {
  155. void *i = 0;
  156. const RTPDynamicProtocolHandler *handler;
  157. while (handler = rtp_handler_iterate(&i)) {
  158. if (handler->static_payload_id && handler->static_payload_id == id &&
  159. codec_type == handler->codec_type)
  160. return handler;
  161. }
  162. return NULL;
  163. }
  164. static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf,
  165. int len)
  166. {
  167. int payload_len;
  168. while (len >= 4) {
  169. payload_len = FFMIN(len, (AV_RB16(buf + 2) + 1) * 4);
  170. switch (buf[1]) {
  171. case RTCP_SR:
  172. if (payload_len < 28) {
  173. av_log(s->ic, AV_LOG_ERROR, "Invalid RTCP SR packet length\n");
  174. return AVERROR_INVALIDDATA;
  175. }
  176. s->last_sr.ssrc = AV_RB32(buf + 4);
  177. s->last_sr.ntp_timestamp = AV_RB64(buf + 8);
  178. s->last_sr.rtp_timestamp = AV_RB32(buf + 16);
  179. s->last_sr.sender_nb_packets = AV_RB32(buf + 20);
  180. s->last_sr.sender_nb_bytes = AV_RB32(buf + 24);
  181. s->pending_sr = 1;
  182. s->last_rtcp_reception_time = av_gettime_relative();
  183. if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
  184. s->first_rtcp_ntp_time = s->last_sr.ntp_timestamp;
  185. if (!s->base_timestamp)
  186. s->base_timestamp = s->last_sr.rtp_timestamp;
  187. s->rtcp_ts_offset = (int32_t)(s->last_sr.rtp_timestamp - s->base_timestamp);
  188. }
  189. break;
  190. case RTCP_BYE:
  191. return -RTCP_BYE;
  192. }
  193. buf += payload_len;
  194. len -= payload_len;
  195. }
  196. return -1;
  197. }
  198. #define RTP_SEQ_MOD (1 << 16)
  199. static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence)
  200. {
  201. memset(s, 0, sizeof(RTPStatistics));
  202. s->max_seq = base_sequence;
  203. s->probation = 1;
  204. }
  205. /*
  206. * Called whenever there is a large jump in sequence numbers,
  207. * or when they get out of probation...
  208. */
  209. static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
  210. {
  211. s->max_seq = seq;
  212. s->cycles = 0;
  213. s->base_seq = seq - 1;
  214. s->bad_seq = RTP_SEQ_MOD + 1;
  215. s->received = 0;
  216. s->expected_prior = 0;
  217. s->received_prior = 0;
  218. s->jitter = 0;
  219. s->transit = 0;
  220. }
  221. /* Returns 1 if we should handle this packet. */
  222. static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
  223. {
  224. uint16_t udelta = seq - s->max_seq;
  225. const int MAX_DROPOUT = 3000;
  226. const int MAX_MISORDER = 100;
  227. const int MIN_SEQUENTIAL = 2;
  228. /* source not valid until MIN_SEQUENTIAL packets with sequence
  229. * seq. numbers have been received */
  230. if (s->probation) {
  231. if (seq == s->max_seq + 1) {
  232. s->probation--;
  233. s->max_seq = seq;
  234. if (s->probation == 0) {
  235. rtp_init_sequence(s, seq);
  236. s->received++;
  237. return 1;
  238. }
  239. } else {
  240. s->probation = MIN_SEQUENTIAL - 1;
  241. s->max_seq = seq;
  242. }
  243. } else if (udelta < MAX_DROPOUT) {
  244. // in order, with permissible gap
  245. if (seq < s->max_seq) {
  246. // sequence number wrapped; count another 64k cycles
  247. s->cycles += RTP_SEQ_MOD;
  248. }
  249. s->max_seq = seq;
  250. } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
  251. // sequence made a large jump...
  252. if (seq == s->bad_seq) {
  253. /* two sequential packets -- assume that the other side
  254. * restarted without telling us; just resync. */
  255. rtp_init_sequence(s, seq);
  256. } else {
  257. s->bad_seq = (seq + 1) & (RTP_SEQ_MOD - 1);
  258. return 0;
  259. }
  260. } else {
  261. // duplicate or reordered packet...
  262. }
  263. s->received++;
  264. return 1;
  265. }
  266. static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp,
  267. uint32_t arrival_timestamp)
  268. {
  269. // Most of this is pretty straight from RFC 3550 appendix A.8
  270. uint32_t transit = arrival_timestamp - sent_timestamp;
  271. uint32_t prev_transit = s->transit;
  272. int32_t d = transit - prev_transit;
  273. // Doing the FFABS() call directly on the "transit - prev_transit"
  274. // expression doesn't work, since it's an unsigned expression. Doing the
  275. // transit calculation in unsigned is desired though, since it most
  276. // probably will need to wrap around.
  277. d = FFABS(d);
  278. s->transit = transit;
  279. if (!prev_transit)
  280. return;
  281. s->jitter += d - (int32_t) ((s->jitter + 8) >> 4);
  282. }
  283. int ff_rtp_check_and_send_back_rr(RTPDemuxContext *s, URLContext *fd,
  284. AVIOContext *avio, int count)
  285. {
  286. AVIOContext *pb;
  287. uint8_t *buf;
  288. int len;
  289. int rtcp_bytes;
  290. RTPStatistics *stats = &s->statistics;
  291. uint32_t lost;
  292. uint32_t extended_max;
  293. uint32_t expected_interval;
  294. uint32_t received_interval;
  295. int32_t lost_interval;
  296. uint32_t expected;
  297. uint32_t fraction;
  298. if ((!fd && !avio) || (count < 1))
  299. return -1;
  300. /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
  301. /* XXX: MPEG pts hardcoded. RTCP send every 0.5 seconds */
  302. s->octet_count += count;
  303. rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
  304. RTCP_TX_RATIO_DEN;
  305. rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
  306. if (rtcp_bytes < 28)
  307. return -1;
  308. s->last_octet_count = s->octet_count;
  309. if (!fd)
  310. pb = avio;
  311. else if (avio_open_dyn_buf(&pb) < 0)
  312. return -1;
  313. // Receiver Report
  314. avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
  315. avio_w8(pb, RTCP_RR);
  316. avio_wb16(pb, 7); /* length in words - 1 */
  317. // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
  318. avio_wb32(pb, s->ssrc + 1);
  319. avio_wb32(pb, s->ssrc); // server SSRC
  320. // some placeholders we should really fill...
  321. // RFC 1889/p64
  322. extended_max = stats->cycles + stats->max_seq;
  323. expected = extended_max - stats->base_seq;
  324. lost = expected - stats->received;
  325. lost = FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
  326. expected_interval = expected - stats->expected_prior;
  327. stats->expected_prior = expected;
  328. received_interval = stats->received - stats->received_prior;
  329. stats->received_prior = stats->received;
  330. lost_interval = expected_interval - received_interval;
  331. if (expected_interval == 0 || lost_interval <= 0)
  332. fraction = 0;
  333. else
  334. fraction = (lost_interval << 8) / expected_interval;
  335. fraction = (fraction << 24) | lost;
  336. avio_wb32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
  337. avio_wb32(pb, extended_max); /* max sequence received */
  338. avio_wb32(pb, stats->jitter >> 4); /* jitter */
  339. if (s->last_sr.ntp_timestamp == AV_NOPTS_VALUE) {
  340. avio_wb32(pb, 0); /* last SR timestamp */
  341. avio_wb32(pb, 0); /* delay since last SR */
  342. } else {
  343. uint32_t middle_32_bits = s->last_sr.ntp_timestamp >> 16; // this is valid, right? do we need to handle 64 bit values special?
  344. uint32_t delay_since_last = av_rescale(av_gettime_relative() - s->last_rtcp_reception_time,
  345. 65536, AV_TIME_BASE);
  346. avio_wb32(pb, middle_32_bits); /* last SR timestamp */
  347. avio_wb32(pb, delay_since_last); /* delay since last SR */
  348. }
  349. // CNAME
  350. avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
  351. avio_w8(pb, RTCP_SDES);
  352. len = strlen(s->hostname);
  353. avio_wb16(pb, (7 + len + 3) / 4); /* length in words - 1 */
  354. avio_wb32(pb, s->ssrc + 1);
  355. avio_w8(pb, 0x01);
  356. avio_w8(pb, len);
  357. avio_write(pb, s->hostname, len);
  358. avio_w8(pb, 0); /* END */
  359. // padding
  360. for (len = (7 + len) % 4; len % 4; len++)
  361. avio_w8(pb, 0);
  362. avio_flush(pb);
  363. if (!fd)
  364. return 0;
  365. len = avio_close_dyn_buf(pb, &buf);
  366. if ((len > 0) && buf) {
  367. av_unused int result;
  368. av_log(s->ic, AV_LOG_TRACE, "sending %d bytes of RR\n", len);
  369. result = ffurl_write(fd, buf, len);
  370. av_log(s->ic, AV_LOG_TRACE, "result from ffurl_write: %d\n", result);
  371. av_free(buf);
  372. }
  373. return 0;
  374. }
  375. void ff_rtp_send_punch_packets(URLContext *rtp_handle)
  376. {
  377. uint8_t buf[RTP_MIN_PACKET_LENGTH], *ptr = buf;
  378. /* Send a small RTP packet */
  379. bytestream_put_byte(&ptr, (RTP_VERSION << 6));
  380. bytestream_put_byte(&ptr, 0); /* Payload type */
  381. bytestream_put_be16(&ptr, 0); /* Seq */
  382. bytestream_put_be32(&ptr, 0); /* Timestamp */
  383. bytestream_put_be32(&ptr, 0); /* SSRC */
  384. ffurl_write(rtp_handle, buf, ptr - buf);
  385. /* Send a minimal RTCP RR */
  386. ptr = buf;
  387. bytestream_put_byte(&ptr, (RTP_VERSION << 6));
  388. bytestream_put_byte(&ptr, RTCP_RR); /* receiver report */
  389. bytestream_put_be16(&ptr, 1); /* length in words - 1 */
  390. bytestream_put_be32(&ptr, 0); /* our own SSRC */
  391. ffurl_write(rtp_handle, buf, ptr - buf);
  392. }
  393. static int find_missing_packets(RTPDemuxContext *s, uint16_t *first_missing,
  394. uint16_t *missing_mask)
  395. {
  396. int i;
  397. uint16_t next_seq = s->seq + 1;
  398. RTPPacket *pkt = s->queue;
  399. if (!pkt || pkt->seq == next_seq)
  400. return 0;
  401. *missing_mask = 0;
  402. for (i = 1; i <= 16; i++) {
  403. uint16_t missing_seq = next_seq + i;
  404. while (pkt) {
  405. int16_t diff = pkt->seq - missing_seq;
  406. if (diff >= 0)
  407. break;
  408. pkt = pkt->next;
  409. }
  410. if (!pkt)
  411. break;
  412. if (pkt->seq == missing_seq)
  413. continue;
  414. *missing_mask |= 1 << (i - 1);
  415. }
  416. *first_missing = next_seq;
  417. return 1;
  418. }
  419. int ff_rtp_send_rtcp_feedback(RTPDemuxContext *s, URLContext *fd,
  420. AVIOContext *avio)
  421. {
  422. int len, need_keyframe, missing_packets;
  423. AVIOContext *pb;
  424. uint8_t *buf;
  425. int64_t now;
  426. uint16_t first_missing = 0, missing_mask = 0;
  427. if (!fd && !avio)
  428. return -1;
  429. need_keyframe = s->handler && s->handler->need_keyframe &&
  430. s->handler->need_keyframe(s->dynamic_protocol_context);
  431. missing_packets = find_missing_packets(s, &first_missing, &missing_mask);
  432. if (!need_keyframe && !missing_packets)
  433. return 0;
  434. /* Send new feedback if enough time has elapsed since the last
  435. * feedback packet. */
  436. now = av_gettime_relative();
  437. if (s->last_feedback_time &&
  438. (now - s->last_feedback_time) < MIN_FEEDBACK_INTERVAL)
  439. return 0;
  440. s->last_feedback_time = now;
  441. if (!fd)
  442. pb = avio;
  443. else if (avio_open_dyn_buf(&pb) < 0)
  444. return -1;
  445. if (need_keyframe) {
  446. avio_w8(pb, (RTP_VERSION << 6) | 1); /* PLI */
  447. avio_w8(pb, RTCP_PSFB);
  448. avio_wb16(pb, 2); /* length in words - 1 */
  449. // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
  450. avio_wb32(pb, s->ssrc + 1);
  451. avio_wb32(pb, s->ssrc); // server SSRC
  452. }
  453. if (missing_packets) {
  454. avio_w8(pb, (RTP_VERSION << 6) | 1); /* NACK */
  455. avio_w8(pb, RTCP_RTPFB);
  456. avio_wb16(pb, 3); /* length in words - 1 */
  457. avio_wb32(pb, s->ssrc + 1);
  458. avio_wb32(pb, s->ssrc); // server SSRC
  459. avio_wb16(pb, first_missing);
  460. avio_wb16(pb, missing_mask);
  461. }
  462. avio_flush(pb);
  463. if (!fd)
  464. return 0;
  465. len = avio_close_dyn_buf(pb, &buf);
  466. if (len > 0 && buf) {
  467. ffurl_write(fd, buf, len);
  468. av_free(buf);
  469. }
  470. return 0;
  471. }
  472. /**
  473. * open a new RTP parse context for stream 'st'. 'st' can be NULL for
  474. * MPEG-2 TS streams.
  475. */
  476. RTPDemuxContext *ff_rtp_parse_open(AVFormatContext *s1, AVStream *st,
  477. int payload_type, int queue_size)
  478. {
  479. RTPDemuxContext *s;
  480. s = av_mallocz(sizeof(RTPDemuxContext));
  481. if (!s)
  482. return NULL;
  483. s->payload_type = payload_type;
  484. s->last_sr.ntp_timestamp = AV_NOPTS_VALUE;
  485. s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
  486. s->ic = s1;
  487. s->st = st;
  488. s->queue_size = queue_size;
  489. av_log(s->ic, AV_LOG_VERBOSE, "setting jitter buffer size to %d\n",
  490. s->queue_size);
  491. rtp_init_statistics(&s->statistics, 0);
  492. if (st) {
  493. switch (st->codecpar->codec_id) {
  494. case AV_CODEC_ID_ADPCM_G722:
  495. /* According to RFC 3551, the stream clock rate is 8000
  496. * even if the sample rate is 16000. */
  497. if (st->codecpar->sample_rate == 8000)
  498. st->codecpar->sample_rate = 16000;
  499. break;
  500. case AV_CODEC_ID_PCM_MULAW: {
  501. AVCodecParameters *par = st->codecpar;
  502. par->bits_per_coded_sample = av_get_bits_per_sample(par->codec_id);
  503. par->block_align = par->ch_layout.nb_channels * par->bits_per_coded_sample / 8;
  504. par->bit_rate = par->block_align * 8LL * par->sample_rate;
  505. break;
  506. }
  507. default:
  508. break;
  509. }
  510. }
  511. // needed to send back RTCP RR in RTSP sessions
  512. gethostname(s->hostname, sizeof(s->hostname));
  513. return s;
  514. }
  515. void ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
  516. const RTPDynamicProtocolHandler *handler)
  517. {
  518. s->dynamic_protocol_context = ctx;
  519. s->handler = handler;
  520. }
  521. void ff_rtp_parse_set_crypto(RTPDemuxContext *s, const char *suite,
  522. const char *params)
  523. {
  524. if (!ff_srtp_set_crypto(&s->srtp, suite, params))
  525. s->srtp_enabled = 1;
  526. }
  527. static int rtp_set_prft(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp) {
  528. int64_t rtcp_time, delta_time;
  529. int32_t delta_timestamp;
  530. AVProducerReferenceTime *prft =
  531. (AVProducerReferenceTime *) av_packet_new_side_data(
  532. pkt, AV_PKT_DATA_PRFT, sizeof(AVProducerReferenceTime));
  533. if (!prft)
  534. return AVERROR(ENOMEM);
  535. rtcp_time = ff_parse_ntp_time(s->last_sr.ntp_timestamp) - NTP_OFFSET_US;
  536. /* Cast to int32_t to handle timestamp wraparound correctly */
  537. delta_timestamp = (int32_t)(timestamp - s->last_sr.rtp_timestamp);
  538. delta_time = av_rescale_q(delta_timestamp, s->st->time_base, AV_TIME_BASE_Q);
  539. prft->wallclock = rtcp_time + delta_time;
  540. prft->flags = 24;
  541. return 0;
  542. }
  543. static int rtp_add_sr_sidedata(RTPDemuxContext *s, AVPacket *pkt) {
  544. AVRTCPSenderReport *sr =
  545. (AVRTCPSenderReport *) av_packet_new_side_data(
  546. pkt, AV_PKT_DATA_RTCP_SR, sizeof(AVRTCPSenderReport));
  547. if (!sr)
  548. return AVERROR(ENOMEM);
  549. memcpy(sr, &s->last_sr, sizeof(AVRTCPSenderReport));
  550. s->pending_sr = 0;
  551. return 0;
  552. }
  553. /**
  554. * This was the second switch in rtp_parse packet.
  555. * Normalizes time, if required, sets stream_index, etc.
  556. */
  557. static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
  558. {
  559. if (s->pending_sr) {
  560. int ret = rtp_add_sr_sidedata(s, pkt);
  561. if (ret < 0)
  562. av_log(s->ic, AV_LOG_WARNING, "rtpdec: failed to add SR sidedata\n");
  563. }
  564. if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE)
  565. return; /* Timestamp already set by depacketizer */
  566. if (timestamp == RTP_NOTS_VALUE)
  567. return;
  568. if (s->last_sr.ntp_timestamp != AV_NOPTS_VALUE) {
  569. if (rtp_set_prft(s, pkt, timestamp) < 0) {
  570. av_log(s->ic, AV_LOG_WARNING, "rtpdec: failed to set prft");
  571. }
  572. }
  573. if (s->last_sr.ntp_timestamp != AV_NOPTS_VALUE && s->ic->nb_streams > 1) {
  574. int64_t addend;
  575. int32_t delta_timestamp;
  576. /* compute pts from timestamp with received ntp_time */
  577. /* Cast to int32_t to handle timestamp wraparound correctly */
  578. delta_timestamp = (int32_t)(timestamp - s->last_sr.rtp_timestamp);
  579. /* convert to the PTS timebase */
  580. addend = av_rescale(s->last_sr.ntp_timestamp - s->first_rtcp_ntp_time,
  581. s->st->time_base.den,
  582. (uint64_t) s->st->time_base.num << 32);
  583. pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
  584. delta_timestamp;
  585. return;
  586. }
  587. if (!s->base_timestamp)
  588. s->base_timestamp = timestamp;
  589. /* assume that the difference is INT32_MIN < x < INT32_MAX,
  590. * but allow the first timestamp to exceed INT32_MAX */
  591. if (!s->timestamp)
  592. s->unwrapped_timestamp += timestamp;
  593. else
  594. s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
  595. s->timestamp = timestamp;
  596. pkt->pts = s->unwrapped_timestamp + s->range_start_offset -
  597. s->base_timestamp;
  598. }
  599. static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
  600. const uint8_t *buf, int len)
  601. {
  602. unsigned int ssrc;
  603. int payload_type, seq, flags = 0;
  604. int ext, csrc;
  605. AVStream *st;
  606. uint32_t timestamp;
  607. int rv = 0;
  608. csrc = buf[0] & 0x0f;
  609. ext = buf[0] & 0x10;
  610. payload_type = buf[1] & 0x7f;
  611. if (buf[1] & 0x80)
  612. flags |= RTP_FLAG_MARKER;
  613. seq = AV_RB16(buf + 2);
  614. timestamp = AV_RB32(buf + 4);
  615. ssrc = AV_RB32(buf + 8);
  616. /* store the ssrc in the RTPDemuxContext */
  617. s->ssrc = ssrc;
  618. /* NOTE: we can handle only one payload type */
  619. if (s->payload_type != payload_type)
  620. return -1;
  621. st = s->st;
  622. // only do something with this if all the rtp checks pass...
  623. if (!rtp_valid_packet_in_sequence(&s->statistics, seq)) {
  624. av_log(s->ic, AV_LOG_ERROR,
  625. "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
  626. payload_type, seq, ((s->seq + 1) & 0xffff));
  627. return -1;
  628. }
  629. if (buf[0] & 0x20) {
  630. int padding = buf[len - 1];
  631. if (len >= 12 + padding)
  632. len -= padding;
  633. }
  634. s->seq = seq;
  635. len -= 12;
  636. buf += 12;
  637. len -= 4 * csrc;
  638. buf += 4 * csrc;
  639. if (len < 0)
  640. return AVERROR_INVALIDDATA;
  641. /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
  642. if (ext) {
  643. if (len < 4)
  644. return -1;
  645. /* calculate the header extension length (stored as number
  646. * of 32-bit words) */
  647. ext = (AV_RB16(buf + 2) + 1) << 2;
  648. if (len < ext)
  649. return -1;
  650. // skip past RTP header extension
  651. len -= ext;
  652. buf += ext;
  653. }
  654. if (s->handler && s->handler->parse_packet) {
  655. rv = s->handler->parse_packet(s->ic, s->dynamic_protocol_context,
  656. s->st, pkt, &timestamp, buf, len, seq,
  657. flags);
  658. } else if (st) {
  659. if ((rv = av_new_packet(pkt, len)) < 0)
  660. return rv;
  661. memcpy(pkt->data, buf, len);
  662. pkt->stream_index = st->index;
  663. } else {
  664. return AVERROR(EINVAL);
  665. }
  666. // now perform timestamp things....
  667. finalize_packet(s, pkt, timestamp);
  668. return rv;
  669. }
  670. void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
  671. {
  672. while (s->queue) {
  673. RTPPacket *next = s->queue->next;
  674. av_freep(&s->queue->buf);
  675. av_freep(&s->queue);
  676. s->queue = next;
  677. }
  678. s->seq = 0;
  679. s->queue_len = 0;
  680. s->prev_ret = 0;
  681. }
  682. static int enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
  683. {
  684. uint16_t seq = AV_RB16(buf + 2);
  685. RTPPacket **cur = &s->queue, *packet;
  686. /* Find the correct place in the queue to insert the packet */
  687. while (*cur) {
  688. int16_t diff = seq - (*cur)->seq;
  689. if (diff < 0)
  690. break;
  691. cur = &(*cur)->next;
  692. }
  693. packet = av_mallocz(sizeof(*packet));
  694. if (!packet)
  695. return AVERROR(ENOMEM);
  696. packet->recvtime = av_gettime_relative();
  697. packet->seq = seq;
  698. packet->len = len;
  699. packet->buf = buf;
  700. packet->next = *cur;
  701. *cur = packet;
  702. s->queue_len++;
  703. return 0;
  704. }
  705. static int has_next_packet(RTPDemuxContext *s)
  706. {
  707. return s->queue && s->queue->seq == (uint16_t) (s->seq + 1);
  708. }
  709. int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
  710. {
  711. return s->queue ? s->queue->recvtime : 0;
  712. }
  713. static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
  714. {
  715. int rv;
  716. RTPPacket *next;
  717. if (s->queue_len <= 0)
  718. return -1;
  719. if (!has_next_packet(s)) {
  720. int pkt_missed = s->queue->seq - s->seq - 1;
  721. if (pkt_missed < 0)
  722. pkt_missed += UINT16_MAX;
  723. av_log(s->ic, AV_LOG_WARNING,
  724. "RTP: missed %d packets\n", pkt_missed);
  725. }
  726. /* Parse the first packet in the queue, and dequeue it */
  727. rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
  728. next = s->queue->next;
  729. av_freep(&s->queue->buf);
  730. av_freep(&s->queue);
  731. s->queue = next;
  732. s->queue_len--;
  733. return rv;
  734. }
  735. static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
  736. uint8_t **bufptr, int len)
  737. {
  738. uint8_t *buf = bufptr ? *bufptr : NULL;
  739. int flags = 0;
  740. uint32_t timestamp;
  741. int rv = 0;
  742. if (!buf) {
  743. /* If parsing of the previous packet actually returned 0 or an error,
  744. * there's nothing more to be parsed from that packet, but we may have
  745. * indicated that we can return the next enqueued packet. */
  746. if (s->prev_ret <= 0)
  747. return rtp_parse_queued_packet(s, pkt);
  748. /* return the next packets, if any */
  749. if (s->handler && s->handler->parse_packet) {
  750. /* timestamp should be overwritten by parse_packet, if not,
  751. * the packet is left with pts == AV_NOPTS_VALUE */
  752. timestamp = RTP_NOTS_VALUE;
  753. rv = s->handler->parse_packet(s->ic, s->dynamic_protocol_context,
  754. s->st, pkt, &timestamp, NULL, 0, 0,
  755. flags);
  756. finalize_packet(s, pkt, timestamp);
  757. return rv;
  758. }
  759. }
  760. if (len < 12)
  761. return -1;
  762. if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
  763. return -1;
  764. if (RTP_PT_IS_RTCP(buf[1])) {
  765. return rtcp_parse_packet(s, buf, len);
  766. }
  767. if (s->st) {
  768. int64_t received = av_gettime_relative();
  769. uint32_t arrival_ts = av_rescale_q(received, AV_TIME_BASE_Q,
  770. s->st->time_base);
  771. timestamp = AV_RB32(buf + 4);
  772. // Calculate the jitter immediately, before queueing the packet
  773. // into the reordering queue.
  774. rtcp_update_jitter(&s->statistics, timestamp, arrival_ts);
  775. }
  776. if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
  777. /* First packet, or no reordering */
  778. return rtp_parse_packet_internal(s, pkt, buf, len);
  779. } else {
  780. uint16_t seq = AV_RB16(buf + 2);
  781. int16_t diff = seq - s->seq;
  782. if (diff < 0) {
  783. /* Packet older than the previously emitted one, drop */
  784. av_log(s->ic, AV_LOG_WARNING,
  785. "RTP: dropping old packet received too late\n");
  786. return -1;
  787. } else if (diff <= 1) {
  788. /* Correct packet */
  789. rv = rtp_parse_packet_internal(s, pkt, buf, len);
  790. return rv;
  791. } else {
  792. /* Still missing some packet, enqueue this one. */
  793. rv = enqueue_packet(s, buf, len);
  794. if (rv < 0)
  795. return rv;
  796. *bufptr = NULL;
  797. /* Return the first enqueued packet if the queue is full,
  798. * even if we're missing something */
  799. if (s->queue_len >= s->queue_size) {
  800. av_log(s->ic, AV_LOG_WARNING, "jitter buffer full\n");
  801. return rtp_parse_queued_packet(s, pkt);
  802. }
  803. return -1;
  804. }
  805. }
  806. }
  807. /**
  808. * Parse an RTP or RTCP packet directly sent as a buffer.
  809. * @param s RTP parse context.
  810. * @param pkt returned packet
  811. * @param bufptr pointer to the input buffer or NULL to read the next packets
  812. * @param len buffer len
  813. * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
  814. * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
  815. */
  816. int ff_rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
  817. uint8_t **bufptr, int len)
  818. {
  819. int rv;
  820. if (s->srtp_enabled && bufptr && ff_srtp_decrypt(&s->srtp, *bufptr, &len) < 0)
  821. return -1;
  822. rv = rtp_parse_one_packet(s, pkt, bufptr, len);
  823. s->prev_ret = rv;
  824. while (rv < 0 && has_next_packet(s))
  825. rv = rtp_parse_queued_packet(s, pkt);
  826. return rv ? rv : has_next_packet(s);
  827. }
  828. void ff_rtp_parse_close(RTPDemuxContext *s)
  829. {
  830. ff_rtp_reset_packet_queue(s);
  831. ff_srtp_free(&s->srtp);
  832. av_free(s);
  833. }
  834. int ff_parse_fmtp(AVFormatContext *s,
  835. AVStream *stream, PayloadContext *data, const char *p,
  836. int (*parse_fmtp)(AVFormatContext *s,
  837. AVStream *stream,
  838. PayloadContext *data,
  839. const char *attr, const char *value))
  840. {
  841. char attr[256];
  842. char *value;
  843. int res;
  844. int value_size = strlen(p) + 1;
  845. if (!(value = av_malloc(value_size))) {
  846. av_log(s, AV_LOG_ERROR, "Failed to allocate data for FMTP.\n");
  847. return AVERROR(ENOMEM);
  848. }
  849. // remove protocol identifier
  850. while (*p && *p == ' ')
  851. p++; // strip spaces
  852. while (*p && *p != ' ')
  853. p++; // eat protocol identifier
  854. while (*p && *p == ' ')
  855. p++; // strip trailing spaces
  856. while (ff_rtsp_next_attr_and_value(&p,
  857. attr, sizeof(attr),
  858. value, value_size)) {
  859. res = parse_fmtp(s, stream, data, attr, value);
  860. if (res < 0 && res != AVERROR_PATCHWELCOME) {
  861. av_free(value);
  862. return res;
  863. }
  864. }
  865. av_free(value);
  866. return 0;
  867. }
  868. int ff_rtp_finalize_packet(AVPacket *pkt, AVIOContext **dyn_buf, int stream_idx)
  869. {
  870. int ret;
  871. av_packet_unref(pkt);
  872. pkt->size = avio_close_dyn_buf(*dyn_buf, &pkt->data);
  873. pkt->stream_index = stream_idx;
  874. *dyn_buf = NULL;
  875. if ((ret = av_packet_from_data(pkt, pkt->data, pkt->size)) < 0) {
  876. av_freep(&pkt->data);
  877. return ret;
  878. }
  879. return pkt->size;
  880. }