rdt.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. /*
  2. * Realmedia RTSP protocol (RDT) support.
  3. * Copyright (c) 2007 Ronald S. Bultje
  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. /**
  22. * @file
  23. * @brief Realmedia RTSP protocol (RDT) support
  24. * @author Ronald S. Bultje <rbultje@ronald.bitfreak.net>
  25. */
  26. #include "avformat.h"
  27. #include "libavutil/avstring.h"
  28. #include "libavutil/mem.h"
  29. #include "demux.h"
  30. #include "rtpdec.h"
  31. #include "rdt.h"
  32. #include "libavutil/base64.h"
  33. #include "libavutil/md5.h"
  34. #include "rm.h"
  35. #include "internal.h"
  36. #include "avio_internal.h"
  37. #include "libavcodec/get_bits.h"
  38. struct RDTDemuxContext {
  39. AVFormatContext *ic; /**< the containing (RTSP) demux context */
  40. /** Each RDT stream-set (represented by one RTSPStream) can contain
  41. * multiple streams (of the same content, but with possibly different
  42. * codecs/bitrates). Each such stream is represented by one AVStream
  43. * in the AVFormatContext, and this variable points to the offset in
  44. * that array such that the first is the first stream of this set. */
  45. AVStream **streams;
  46. int n_streams; /**< streams with identical content in this set */
  47. void *dynamic_protocol_context;
  48. DynamicPayloadPacketHandlerProc parse_packet;
  49. uint32_t prev_timestamp;
  50. int prev_set_id, prev_stream_id;
  51. };
  52. RDTDemuxContext *
  53. ff_rdt_parse_open(AVFormatContext *ic, int first_stream_of_set_idx,
  54. void *priv_data, const RTPDynamicProtocolHandler *handler)
  55. {
  56. RDTDemuxContext *s = av_mallocz(sizeof(RDTDemuxContext));
  57. if (!s)
  58. return NULL;
  59. s->ic = ic;
  60. s->streams = &ic->streams[first_stream_of_set_idx];
  61. do {
  62. s->n_streams++;
  63. } while (first_stream_of_set_idx + s->n_streams < ic->nb_streams &&
  64. s->streams[s->n_streams]->id == s->streams[0]->id);
  65. s->prev_set_id = -1;
  66. s->prev_stream_id = -1;
  67. s->prev_timestamp = -1;
  68. s->parse_packet = handler ? handler->parse_packet : NULL;
  69. s->dynamic_protocol_context = priv_data;
  70. return s;
  71. }
  72. void
  73. ff_rdt_parse_close(RDTDemuxContext *s)
  74. {
  75. av_free(s);
  76. }
  77. struct PayloadContext {
  78. AVFormatContext *rmctx;
  79. int nb_rmst;
  80. RMStream **rmst;
  81. uint8_t *mlti_data;
  82. unsigned int mlti_data_size;
  83. char buffer[RTP_MAX_PACKET_LENGTH + AV_INPUT_BUFFER_PADDING_SIZE];
  84. int audio_pkt_cnt; /**< remaining audio packets in rmdec */
  85. };
  86. void
  87. ff_rdt_calc_response_and_checksum(char response[41], char chksum[9],
  88. const char *challenge)
  89. {
  90. int ch_len = strlen (challenge), i;
  91. unsigned char zres[16],
  92. buf[64] = { 0xa1, 0xe9, 0x14, 0x9d, 0x0e, 0x6b, 0x3b, 0x59 };
  93. #define XOR_TABLE_SIZE 37
  94. static const unsigned char xor_table[XOR_TABLE_SIZE] = {
  95. 0x05, 0x18, 0x74, 0xd0, 0x0d, 0x09, 0x02, 0x53,
  96. 0xc0, 0x01, 0x05, 0x05, 0x67, 0x03, 0x19, 0x70,
  97. 0x08, 0x27, 0x66, 0x10, 0x10, 0x72, 0x08, 0x09,
  98. 0x63, 0x11, 0x03, 0x71, 0x08, 0x08, 0x70, 0x02,
  99. 0x10, 0x57, 0x05, 0x18, 0x54 };
  100. /* some (length) checks */
  101. if (ch_len == 40) /* what a hack... */
  102. ch_len = 32;
  103. else if (ch_len > 56)
  104. ch_len = 56;
  105. memcpy(buf + 8, challenge, ch_len);
  106. /* xor challenge bytewise with xor_table */
  107. for (i = 0; i < XOR_TABLE_SIZE; i++)
  108. buf[8 + i] ^= xor_table[i];
  109. av_md5_sum(zres, buf, 64);
  110. ff_data_to_hex(response, zres, 16, 1);
  111. /* add tail */
  112. strcpy (response + 32, "01d0a8e3");
  113. /* calculate checksum */
  114. for (i = 0; i < 8; i++)
  115. chksum[i] = response[i * 4];
  116. chksum[8] = 0;
  117. }
  118. static int
  119. rdt_load_mdpr (PayloadContext *rdt, AVStream *st, int rule_nr)
  120. {
  121. FFIOContext pb0;
  122. AVIOContext *const pb = &pb0.pub;
  123. unsigned int size;
  124. uint32_t tag;
  125. /**
  126. * Layout of the MLTI chunk:
  127. * 4: MLTI
  128. * 2: number of streams
  129. * Then for each stream ([number_of_streams] times):
  130. * 2: mdpr index
  131. * 2: number of mdpr chunks
  132. * Then for each mdpr chunk ([number_of_mdpr_chunks] times):
  133. * 4: size
  134. * [size]: data
  135. * we skip MDPR chunks until we reach the one of the stream
  136. * we're interested in, and forward that ([size]+[data]) to
  137. * the RM demuxer to parse the stream-specific header data.
  138. */
  139. if (!rdt->mlti_data)
  140. return -1;
  141. ffio_init_read_context(&pb0, rdt->mlti_data, rdt->mlti_data_size);
  142. tag = avio_rl32(pb);
  143. if (tag == MKTAG('M', 'L', 'T', 'I')) {
  144. int num, chunk_nr;
  145. /* read index of MDPR chunk numbers */
  146. num = avio_rb16(pb);
  147. if (rule_nr < 0 || rule_nr >= num)
  148. return -1;
  149. avio_skip(pb, rule_nr * 2);
  150. chunk_nr = avio_rb16(pb);
  151. avio_skip(pb, (num - 1 - rule_nr) * 2);
  152. /* read MDPR chunks */
  153. num = avio_rb16(pb);
  154. if (chunk_nr >= num)
  155. return -1;
  156. while (chunk_nr--)
  157. avio_skip(pb, avio_rb32(pb));
  158. size = avio_rb32(pb);
  159. } else {
  160. size = rdt->mlti_data_size;
  161. avio_seek(pb, 0, SEEK_SET);
  162. }
  163. if (ff_rm_read_mdpr_codecdata(rdt->rmctx, pb, st, rdt->rmst[st->index], size, NULL) < 0)
  164. return -1;
  165. return 0;
  166. }
  167. /**
  168. * Actual data handling.
  169. */
  170. int
  171. ff_rdt_parse_header(const uint8_t *buf, int len,
  172. int *pset_id, int *pseq_no, int *pstream_id,
  173. int *pis_keyframe, uint32_t *ptimestamp)
  174. {
  175. GetBitContext gb;
  176. int consumed = 0, set_id, seq_no, stream_id, is_keyframe,
  177. len_included, need_reliable;
  178. uint32_t timestamp;
  179. /* skip status packets */
  180. while (len >= 5 && buf[1] == 0xFF /* status packet */) {
  181. int pkt_len;
  182. if (!(buf[0] & 0x80))
  183. return -1; /* not followed by a data packet */
  184. pkt_len = AV_RB16(buf+3);
  185. if (pkt_len > len)
  186. return AVERROR_INVALIDDATA;
  187. buf += pkt_len;
  188. len -= pkt_len;
  189. consumed += pkt_len;
  190. }
  191. if (len < 16)
  192. return -1;
  193. /**
  194. * Layout of the header (in bits):
  195. * 1: len_included
  196. * Flag indicating whether this header includes a length field;
  197. * this can be used to concatenate multiple RDT packets in a
  198. * single UDP/TCP data frame and is used to precede RDT data
  199. * by stream status packets
  200. * 1: need_reliable
  201. * Flag indicating whether this header includes a "reliable
  202. * sequence number"; these are apparently sequence numbers of
  203. * data packets alone. For data packets, this flag is always
  204. * set, according to the Real documentation [1]
  205. * 5: set_id
  206. * ID of a set of streams of identical content, possibly with
  207. * different codecs or bitrates
  208. * 1: is_reliable
  209. * Flag set for certain streams deemed less tolerable for packet
  210. * loss
  211. * 16: seq_no
  212. * Packet sequence number; if >=0xFF00, this is a non-data packet
  213. * containing stream status info, the second byte indicates the
  214. * type of status packet (see wireshark docs / source code [2])
  215. * if (len_included) {
  216. * 16: packet_len
  217. * } else {
  218. * packet_len = remainder of UDP/TCP frame
  219. * }
  220. * 1: is_back_to_back
  221. * Back-to-Back flag; used for timing, set for one in every 10
  222. * packets, according to the Real documentation [1]
  223. * 1: is_slow_data
  224. * Slow-data flag; currently unused, according to Real docs [1]
  225. * 5: stream_id
  226. * ID of the stream within this particular set of streams
  227. * 1: is_no_keyframe
  228. * Non-keyframe flag (unset if packet belongs to a keyframe)
  229. * 32: timestamp (PTS)
  230. * if (set_id == 0x1F) {
  231. * 16: set_id (extended set-of-streams ID; see set_id)
  232. * }
  233. * if (need_reliable) {
  234. * 16: reliable_seq_no
  235. * Reliable sequence number (see need_reliable)
  236. * }
  237. * if (stream_id == 0x3F) {
  238. * 16: stream_id (extended stream ID; see stream_id)
  239. * }
  240. * [1] https://protocol.helixcommunity.org/files/2005/devdocs/RDT_Feature_Level_20.txt
  241. * [2] http://www.wireshark.org/docs/dfref/r/rdt.html and
  242. * http://anonsvn.wireshark.org/viewvc/trunk/epan/dissectors/packet-rdt.c
  243. */
  244. init_get_bits(&gb, buf, len << 3);
  245. len_included = get_bits1(&gb);
  246. need_reliable = get_bits1(&gb);
  247. set_id = get_bits(&gb, 5);
  248. skip_bits(&gb, 1);
  249. seq_no = get_bits(&gb, 16);
  250. if (len_included)
  251. skip_bits(&gb, 16);
  252. skip_bits(&gb, 2);
  253. stream_id = get_bits(&gb, 5);
  254. is_keyframe = !get_bits1(&gb);
  255. timestamp = get_bits_long(&gb, 32);
  256. if (set_id == 0x1f)
  257. set_id = get_bits(&gb, 16);
  258. if (need_reliable)
  259. skip_bits(&gb, 16);
  260. if (stream_id == 0x1f)
  261. stream_id = get_bits(&gb, 16);
  262. if (pset_id) *pset_id = set_id;
  263. if (pseq_no) *pseq_no = seq_no;
  264. if (pstream_id) *pstream_id = stream_id;
  265. if (pis_keyframe) *pis_keyframe = is_keyframe;
  266. if (ptimestamp) *ptimestamp = timestamp;
  267. return consumed + (get_bits_count(&gb) >> 3);
  268. }
  269. /** return 0 on packet, no more left, 1 on packet, 1 on partial packet... */
  270. static int
  271. rdt_parse_packet (AVFormatContext *ctx, PayloadContext *rdt, AVStream *st,
  272. AVPacket *pkt, uint32_t *timestamp,
  273. const uint8_t *buf, int len, uint16_t rtp_seq, int flags)
  274. {
  275. int seq = 1, res;
  276. if (rdt->audio_pkt_cnt == 0) {
  277. FFIOContext pb;
  278. int pos, rmflags;
  279. ffio_init_read_context(&pb, buf, len);
  280. rmflags = (flags & RTP_FLAG_KEY) ? 2 : 0;
  281. res = ff_rm_parse_packet(rdt->rmctx, &pb.pub, st, rdt->rmst[st->index],
  282. len, pkt, &seq, rmflags, *timestamp);
  283. pos = avio_tell(&pb.pub);
  284. if (res < 0)
  285. return res;
  286. if (res > 0) {
  287. if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
  288. memcpy (rdt->buffer, buf + pos, len - pos);
  289. rdt->rmctx->pb = avio_alloc_context (rdt->buffer, len - pos, 0,
  290. NULL, NULL, NULL, NULL);
  291. }
  292. goto get_cache;
  293. }
  294. } else {
  295. get_cache:
  296. rdt->audio_pkt_cnt =
  297. ff_rm_retrieve_cache (rdt->rmctx, rdt->rmctx->pb,
  298. st, rdt->rmst[st->index], pkt);
  299. if (rdt->audio_pkt_cnt == 0 &&
  300. st->codecpar->codec_id == AV_CODEC_ID_AAC)
  301. avio_context_free(&rdt->rmctx->pb);
  302. }
  303. pkt->stream_index = st->index;
  304. pkt->pts = *timestamp;
  305. return rdt->audio_pkt_cnt > 0;
  306. }
  307. int
  308. ff_rdt_parse_packet(RDTDemuxContext *s, AVPacket *pkt,
  309. uint8_t **bufptr, int len)
  310. {
  311. uint8_t *buf = bufptr ? *bufptr : NULL;
  312. int seq_no, flags = 0, stream_id, set_id, is_keyframe;
  313. uint32_t timestamp;
  314. int rv= 0;
  315. if (!s->parse_packet)
  316. return -1;
  317. if (!buf && s->prev_stream_id != -1) {
  318. /* return the next packets, if any */
  319. timestamp= 0; ///< Should not be used if buf is NULL, but should be set to the timestamp of the packet returned....
  320. rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
  321. s->streams[s->prev_stream_id],
  322. pkt, &timestamp, NULL, 0, 0, flags);
  323. return rv;
  324. }
  325. if (len < 12)
  326. return -1;
  327. rv = ff_rdt_parse_header(buf, len, &set_id, &seq_no, &stream_id, &is_keyframe, &timestamp);
  328. if (rv < 0)
  329. return rv;
  330. if (is_keyframe &&
  331. (set_id != s->prev_set_id || timestamp != s->prev_timestamp ||
  332. stream_id != s->prev_stream_id)) {
  333. flags |= RTP_FLAG_KEY;
  334. s->prev_set_id = set_id;
  335. s->prev_timestamp = timestamp;
  336. }
  337. s->prev_stream_id = stream_id;
  338. buf += rv;
  339. len -= rv;
  340. if (s->prev_stream_id >= s->n_streams) {
  341. s->prev_stream_id = -1;
  342. return -1;
  343. }
  344. rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
  345. s->streams[s->prev_stream_id],
  346. pkt, &timestamp, buf, len, 0, flags);
  347. return rv;
  348. }
  349. void
  350. ff_rdt_subscribe_rule (char *cmd, int size,
  351. int stream_nr, int rule_nr)
  352. {
  353. av_strlcatf(cmd, size, "stream=%d;rule=%d,stream=%d;rule=%d",
  354. stream_nr, rule_nr * 2, stream_nr, rule_nr * 2 + 1);
  355. }
  356. static unsigned char *
  357. rdt_parse_b64buf (unsigned int *target_len, const char *p)
  358. {
  359. unsigned char *target;
  360. int len = strlen(p);
  361. if (*p == '\"') {
  362. p++;
  363. len -= 2; /* skip embracing " at start/end */
  364. }
  365. *target_len = len * 3 / 4;
  366. target = av_mallocz(*target_len + AV_INPUT_BUFFER_PADDING_SIZE);
  367. if (!target)
  368. return NULL;
  369. av_base64_decode(target, p, *target_len);
  370. return target;
  371. }
  372. static int
  373. rdt_parse_sdp_line (AVFormatContext *s, int st_index,
  374. PayloadContext *rdt, const char *line)
  375. {
  376. AVStream *stream = s->streams[st_index];
  377. const char *p = line;
  378. if (av_strstart(p, "OpaqueData:buffer;", &p)) {
  379. rdt->mlti_data = rdt_parse_b64buf(&rdt->mlti_data_size, p);
  380. } else if (av_strstart(p, "StartTime:integer;", &p))
  381. ffstream(stream)->first_dts = atoi(p);
  382. else if (av_strstart(p, "ASMRuleBook:string;", &p)) {
  383. int n, first = -1;
  384. for (n = 0; n < s->nb_streams; n++)
  385. if (s->streams[n]->id == stream->id) {
  386. int count = s->streams[n]->index + 1, err;
  387. if (first == -1) first = n;
  388. if (rdt->nb_rmst < count) {
  389. if ((err = av_reallocp(&rdt->rmst,
  390. count * sizeof(*rdt->rmst))) < 0) {
  391. rdt->nb_rmst = 0;
  392. return err;
  393. }
  394. memset(rdt->rmst + rdt->nb_rmst, 0,
  395. (count - rdt->nb_rmst) * sizeof(*rdt->rmst));
  396. rdt->nb_rmst = count;
  397. }
  398. rdt->rmst[s->streams[n]->index] = ff_rm_alloc_rmstream();
  399. if (!rdt->rmst[s->streams[n]->index])
  400. return AVERROR(ENOMEM);
  401. rdt_load_mdpr(rdt, s->streams[n], (n - first) * 2);
  402. }
  403. }
  404. return 0;
  405. }
  406. static void
  407. real_parse_asm_rule(AVStream *st, const char *p, const char *end)
  408. {
  409. do {
  410. /* can be either averagebandwidth= or AverageBandwidth= */
  411. if (sscanf(p, " %*1[Aa]verage%*1[Bb]andwidth=%"SCNd64, &st->codecpar->bit_rate) == 1)
  412. break;
  413. if (!(p = strchr(p, ',')) || p > end)
  414. p = end;
  415. p++;
  416. } while (p < end);
  417. }
  418. static AVStream *
  419. add_dstream(AVFormatContext *s, AVStream *orig_st)
  420. {
  421. AVStream *st;
  422. if (!(st = avformat_new_stream(s, NULL)))
  423. return NULL;
  424. st->id = orig_st->id;
  425. st->codecpar->codec_type = orig_st->codecpar->codec_type;
  426. ffstream(st)->first_dts = ffstream(orig_st)->first_dts;
  427. return st;
  428. }
  429. static void
  430. real_parse_asm_rulebook(AVFormatContext *s, AVStream *orig_st,
  431. const char *p)
  432. {
  433. const char *end;
  434. int n_rules = 0, odd = 0;
  435. AVStream *st;
  436. /**
  437. * The ASMRuleBook contains a list of comma-separated strings per rule,
  438. * and each rule is separated by a ;. The last one also has a ; at the
  439. * end so we can use it as delimiter.
  440. * Every rule occurs twice, once for when the RTSP packet header marker
  441. * is set and once for if it isn't. We only read the first because we
  442. * don't care much (that's what the "odd" variable is for).
  443. * Each rule contains a set of one or more statements, optionally
  444. * preceded by a single condition. If there's a condition, the rule
  445. * starts with a '#'. Multiple conditions are merged between brackets,
  446. * so there are never multiple conditions spread out over separate
  447. * statements. Generally, these conditions are bitrate limits (min/max)
  448. * for multi-bitrate streams.
  449. */
  450. if (*p == '\"') p++;
  451. while (1) {
  452. if (!(end = strchr(p, ';')))
  453. break;
  454. if (!odd && end != p) {
  455. if (n_rules > 0)
  456. st = add_dstream(s, orig_st);
  457. else
  458. st = orig_st;
  459. if (!st)
  460. break;
  461. real_parse_asm_rule(st, p, end);
  462. n_rules++;
  463. }
  464. p = end + 1;
  465. odd ^= 1;
  466. }
  467. }
  468. void
  469. ff_real_parse_sdp_a_line (AVFormatContext *s, int stream_index,
  470. const char *line)
  471. {
  472. const char *p = line;
  473. if (av_strstart(p, "ASMRuleBook:string;", &p))
  474. real_parse_asm_rulebook(s, s->streams[stream_index], p);
  475. }
  476. static av_cold int rdt_init(AVFormatContext *s, int st_index, PayloadContext *rdt)
  477. {
  478. int ret;
  479. rdt->rmctx = avformat_alloc_context();
  480. if (!rdt->rmctx)
  481. return AVERROR(ENOMEM);
  482. if ((ret = ff_copy_whiteblacklists(rdt->rmctx, s)) < 0)
  483. return ret;
  484. return avformat_open_input(&rdt->rmctx, "", &ff_rdt_demuxer.p, NULL);
  485. }
  486. static void
  487. rdt_close_context (PayloadContext *rdt)
  488. {
  489. int i;
  490. for (i = 0; i < rdt->nb_rmst; i++)
  491. if (rdt->rmst[i]) {
  492. ff_rm_free_rmstream(rdt->rmst[i]);
  493. av_freep(&rdt->rmst[i]);
  494. }
  495. if (rdt->rmctx)
  496. avformat_close_input(&rdt->rmctx);
  497. av_freep(&rdt->mlti_data);
  498. av_freep(&rdt->rmst);
  499. }
  500. #define RDT_HANDLER(n, s, t) \
  501. const RTPDynamicProtocolHandler ff_rdt_ ## n ## _handler = { \
  502. .enc_name = s, \
  503. .codec_type = t, \
  504. .codec_id = AV_CODEC_ID_NONE, \
  505. .priv_data_size = sizeof(PayloadContext), \
  506. .init = rdt_init, \
  507. .parse_sdp_a_line = rdt_parse_sdp_line, \
  508. .close = rdt_close_context, \
  509. .parse_packet = rdt_parse_packet \
  510. }
  511. RDT_HANDLER(live_video, "x-pn-multirate-realvideo-live", AVMEDIA_TYPE_VIDEO);
  512. RDT_HANDLER(live_audio, "x-pn-multirate-realaudio-live", AVMEDIA_TYPE_AUDIO);
  513. RDT_HANDLER(video, "x-pn-realvideo", AVMEDIA_TYPE_VIDEO);
  514. RDT_HANDLER(audio, "x-pn-realaudio", AVMEDIA_TYPE_AUDIO);