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.

561 lines
18KB

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