rtsp.c 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065
  1. /*
  2. * RTSP/SDP client
  3. * Copyright (c) 2002 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/base64.h"
  22. #include "libavutil/avstring.h"
  23. #include "libavutil/intreadwrite.h"
  24. #include "libavutil/mathematics.h"
  25. #include "libavutil/parseutils.h"
  26. #include "libavutil/random_seed.h"
  27. #include "libavutil/dict.h"
  28. #include "libavutil/opt.h"
  29. #include "avformat.h"
  30. #include "avio_internal.h"
  31. #include <sys/time.h>
  32. #if HAVE_POLL_H
  33. #include <poll.h>
  34. #endif
  35. #include "internal.h"
  36. #include "network.h"
  37. #include "os_support.h"
  38. #include "http.h"
  39. #include "rtsp.h"
  40. #include "rtpdec.h"
  41. #include "rdt.h"
  42. #include "rtpdec_formats.h"
  43. #include "rtpenc_chain.h"
  44. #include "url.h"
  45. #include "rtpenc.h"
  46. //#define DEBUG
  47. /* Timeout values for socket poll, in ms,
  48. * and read_packet(), in seconds */
  49. #define POLL_TIMEOUT_MS 100
  50. #define READ_PACKET_TIMEOUT_S 10
  51. #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / POLL_TIMEOUT_MS
  52. #define SDP_MAX_SIZE 16384
  53. #define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
  54. #define DEFAULT_REORDERING_DELAY 100000
  55. #define OFFSET(x) offsetof(RTSPState, x)
  56. #define DEC AV_OPT_FLAG_DECODING_PARAM
  57. #define ENC AV_OPT_FLAG_ENCODING_PARAM
  58. #define RTSP_FLAG_OPTS(name, longname) \
  59. { name, longname, OFFSET(rtsp_flags), AV_OPT_TYPE_FLAGS, {0}, INT_MIN, INT_MAX, DEC, "rtsp_flags" }, \
  60. { "filter_src", "Only receive packets from the negotiated peer IP", 0, AV_OPT_TYPE_CONST, {RTSP_FLAG_FILTER_SRC}, 0, 0, DEC, "rtsp_flags" }
  61. #define RTSP_MEDIATYPE_OPTS(name, longname) \
  62. { name, longname, OFFSET(media_type_mask), AV_OPT_TYPE_FLAGS, { (1 << (AVMEDIA_TYPE_DATA+1)) - 1 }, INT_MIN, INT_MAX, DEC, "allowed_media_types" }, \
  63. { "video", "Video", 0, AV_OPT_TYPE_CONST, {1 << AVMEDIA_TYPE_VIDEO}, 0, 0, DEC, "allowed_media_types" }, \
  64. { "audio", "Audio", 0, AV_OPT_TYPE_CONST, {1 << AVMEDIA_TYPE_AUDIO}, 0, 0, DEC, "allowed_media_types" }, \
  65. { "data", "Data", 0, AV_OPT_TYPE_CONST, {1 << AVMEDIA_TYPE_DATA}, 0, 0, DEC, "allowed_media_types" }
  66. const AVOption ff_rtsp_options[] = {
  67. { "initial_pause", "Don't start playing the stream immediately", OFFSET(initial_pause), AV_OPT_TYPE_INT, {0}, 0, 1, DEC },
  68. FF_RTP_FLAG_OPTS(RTSPState, rtp_muxer_flags)
  69. { "rtsp_transport", "RTSP transport protocols", OFFSET(lower_transport_mask), AV_OPT_TYPE_FLAGS, {0}, INT_MIN, INT_MAX, DEC|ENC, "rtsp_transport" }, \
  70. { "udp", "UDP", 0, AV_OPT_TYPE_CONST, {1 << RTSP_LOWER_TRANSPORT_UDP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
  71. { "tcp", "TCP", 0, AV_OPT_TYPE_CONST, {1 << RTSP_LOWER_TRANSPORT_TCP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
  72. { "udp_multicast", "UDP multicast", 0, AV_OPT_TYPE_CONST, {1 << RTSP_LOWER_TRANSPORT_UDP_MULTICAST}, 0, 0, DEC, "rtsp_transport" },
  73. { "http", "HTTP tunneling", 0, AV_OPT_TYPE_CONST, {(1 << RTSP_LOWER_TRANSPORT_HTTP)}, 0, 0, DEC, "rtsp_transport" },
  74. RTSP_FLAG_OPTS("rtsp_flags", "RTSP flags"),
  75. RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
  76. { "min_port", "Minimum local UDP port", OFFSET(rtp_port_min), AV_OPT_TYPE_INT, {RTSP_RTP_PORT_MIN}, 0, 65535, DEC|ENC },
  77. { "max_port", "Maximum local UDP port", OFFSET(rtp_port_max), AV_OPT_TYPE_INT, {RTSP_RTP_PORT_MAX}, 0, 65535, DEC|ENC },
  78. { NULL },
  79. };
  80. static const AVOption sdp_options[] = {
  81. RTSP_FLAG_OPTS("sdp_flags", "SDP flags"),
  82. RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
  83. { NULL },
  84. };
  85. static const AVOption rtp_options[] = {
  86. RTSP_FLAG_OPTS("rtp_flags", "RTP flags"),
  87. { NULL },
  88. };
  89. static void get_word_until_chars(char *buf, int buf_size,
  90. const char *sep, const char **pp)
  91. {
  92. const char *p;
  93. char *q;
  94. p = *pp;
  95. p += strspn(p, SPACE_CHARS);
  96. q = buf;
  97. while (!strchr(sep, *p) && *p != '\0') {
  98. if ((q - buf) < buf_size - 1)
  99. *q++ = *p;
  100. p++;
  101. }
  102. if (buf_size > 0)
  103. *q = '\0';
  104. *pp = p;
  105. }
  106. static void get_word_sep(char *buf, int buf_size, const char *sep,
  107. const char **pp)
  108. {
  109. if (**pp == '/') (*pp)++;
  110. get_word_until_chars(buf, buf_size, sep, pp);
  111. }
  112. static void get_word(char *buf, int buf_size, const char **pp)
  113. {
  114. get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
  115. }
  116. /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
  117. * and end time.
  118. * Used for seeking in the rtp stream.
  119. */
  120. static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
  121. {
  122. char buf[256];
  123. p += strspn(p, SPACE_CHARS);
  124. if (!av_stristart(p, "npt=", &p))
  125. return;
  126. *start = AV_NOPTS_VALUE;
  127. *end = AV_NOPTS_VALUE;
  128. get_word_sep(buf, sizeof(buf), "-", &p);
  129. av_parse_time(start, buf, 1);
  130. if (*p == '-') {
  131. p++;
  132. get_word_sep(buf, sizeof(buf), "-", &p);
  133. av_parse_time(end, buf, 1);
  134. }
  135. // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
  136. // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
  137. }
  138. static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
  139. {
  140. struct addrinfo hints = { 0 }, *ai = NULL;
  141. hints.ai_flags = AI_NUMERICHOST;
  142. if (getaddrinfo(buf, NULL, &hints, &ai))
  143. return -1;
  144. memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
  145. freeaddrinfo(ai);
  146. return 0;
  147. }
  148. #if CONFIG_RTPDEC
  149. static void init_rtp_handler(RTPDynamicProtocolHandler *handler,
  150. RTSPStream *rtsp_st, AVCodecContext *codec)
  151. {
  152. if (!handler)
  153. return;
  154. codec->codec_id = handler->codec_id;
  155. rtsp_st->dynamic_handler = handler;
  156. if (handler->alloc) {
  157. rtsp_st->dynamic_protocol_context = handler->alloc();
  158. if (!rtsp_st->dynamic_protocol_context)
  159. rtsp_st->dynamic_handler = NULL;
  160. }
  161. }
  162. /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
  163. static int sdp_parse_rtpmap(AVFormatContext *s,
  164. AVStream *st, RTSPStream *rtsp_st,
  165. int payload_type, const char *p)
  166. {
  167. AVCodecContext *codec = st->codec;
  168. char buf[256];
  169. int i;
  170. AVCodec *c;
  171. const char *c_name;
  172. /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
  173. * see if we can handle this kind of payload.
  174. * The space should normally not be there but some Real streams or
  175. * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
  176. * have a trailing space. */
  177. get_word_sep(buf, sizeof(buf), "/ ", &p);
  178. if (payload_type >= RTP_PT_PRIVATE) {
  179. RTPDynamicProtocolHandler *handler =
  180. ff_rtp_handler_find_by_name(buf, codec->codec_type);
  181. init_rtp_handler(handler, rtsp_st, codec);
  182. /* If no dynamic handler was found, check with the list of standard
  183. * allocated types, if such a stream for some reason happens to
  184. * use a private payload type. This isn't handled in rtpdec.c, since
  185. * the format name from the rtpmap line never is passed into rtpdec. */
  186. if (!rtsp_st->dynamic_handler)
  187. codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
  188. } else {
  189. /* We are in a standard case
  190. * (from http://www.iana.org/assignments/rtp-parameters). */
  191. /* search into AVRtpPayloadTypes[] */
  192. codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
  193. }
  194. c = avcodec_find_decoder(codec->codec_id);
  195. if (c && c->name)
  196. c_name = c->name;
  197. else
  198. c_name = "(null)";
  199. get_word_sep(buf, sizeof(buf), "/", &p);
  200. i = atoi(buf);
  201. switch (codec->codec_type) {
  202. case AVMEDIA_TYPE_AUDIO:
  203. av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
  204. codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
  205. codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
  206. if (i > 0) {
  207. codec->sample_rate = i;
  208. avpriv_set_pts_info(st, 32, 1, codec->sample_rate);
  209. get_word_sep(buf, sizeof(buf), "/", &p);
  210. i = atoi(buf);
  211. if (i > 0)
  212. codec->channels = i;
  213. // TODO: there is a bug here; if it is a mono stream, and
  214. // less than 22000Hz, faad upconverts to stereo and twice
  215. // the frequency. No problem, but the sample rate is being
  216. // set here by the sdp line. Patch on its way. (rdm)
  217. }
  218. av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
  219. codec->sample_rate);
  220. av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
  221. codec->channels);
  222. break;
  223. case AVMEDIA_TYPE_VIDEO:
  224. av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
  225. if (i > 0)
  226. avpriv_set_pts_info(st, 32, 1, i);
  227. break;
  228. default:
  229. break;
  230. }
  231. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->init)
  232. rtsp_st->dynamic_handler->init(s, st->index,
  233. rtsp_st->dynamic_protocol_context);
  234. return 0;
  235. }
  236. /* parse the attribute line from the fmtp a line of an sdp response. This
  237. * is broken out as a function because it is used in rtp_h264.c, which is
  238. * forthcoming. */
  239. int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
  240. char *value, int value_size)
  241. {
  242. *p += strspn(*p, SPACE_CHARS);
  243. if (**p) {
  244. get_word_sep(attr, attr_size, "=", p);
  245. if (**p == '=')
  246. (*p)++;
  247. get_word_sep(value, value_size, ";", p);
  248. if (**p == ';')
  249. (*p)++;
  250. return 1;
  251. }
  252. return 0;
  253. }
  254. typedef struct SDPParseState {
  255. /* SDP only */
  256. struct sockaddr_storage default_ip;
  257. int default_ttl;
  258. int skip_media; ///< set if an unknown m= line occurs
  259. } SDPParseState;
  260. static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
  261. int letter, const char *buf)
  262. {
  263. RTSPState *rt = s->priv_data;
  264. char buf1[64], st_type[64];
  265. const char *p;
  266. enum AVMediaType codec_type;
  267. int payload_type, i;
  268. AVStream *st;
  269. RTSPStream *rtsp_st;
  270. struct sockaddr_storage sdp_ip;
  271. int ttl;
  272. av_dlog(s, "sdp: %c='%s'\n", letter, buf);
  273. p = buf;
  274. if (s1->skip_media && letter != 'm')
  275. return;
  276. switch (letter) {
  277. case 'c':
  278. get_word(buf1, sizeof(buf1), &p);
  279. if (strcmp(buf1, "IN") != 0)
  280. return;
  281. get_word(buf1, sizeof(buf1), &p);
  282. if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
  283. return;
  284. get_word_sep(buf1, sizeof(buf1), "/", &p);
  285. if (get_sockaddr(buf1, &sdp_ip))
  286. return;
  287. ttl = 16;
  288. if (*p == '/') {
  289. p++;
  290. get_word_sep(buf1, sizeof(buf1), "/", &p);
  291. ttl = atoi(buf1);
  292. }
  293. if (s->nb_streams == 0) {
  294. s1->default_ip = sdp_ip;
  295. s1->default_ttl = ttl;
  296. } else {
  297. rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
  298. rtsp_st->sdp_ip = sdp_ip;
  299. rtsp_st->sdp_ttl = ttl;
  300. }
  301. break;
  302. case 's':
  303. av_dict_set(&s->metadata, "title", p, 0);
  304. break;
  305. case 'i':
  306. if (s->nb_streams == 0) {
  307. av_dict_set(&s->metadata, "comment", p, 0);
  308. break;
  309. }
  310. break;
  311. case 'm':
  312. /* new stream */
  313. s1->skip_media = 0;
  314. codec_type = AVMEDIA_TYPE_UNKNOWN;
  315. get_word(st_type, sizeof(st_type), &p);
  316. if (!strcmp(st_type, "audio")) {
  317. codec_type = AVMEDIA_TYPE_AUDIO;
  318. } else if (!strcmp(st_type, "video")) {
  319. codec_type = AVMEDIA_TYPE_VIDEO;
  320. } else if (!strcmp(st_type, "application")) {
  321. codec_type = AVMEDIA_TYPE_DATA;
  322. }
  323. if (codec_type == AVMEDIA_TYPE_UNKNOWN || !(rt->media_type_mask & (1 << codec_type))) {
  324. s1->skip_media = 1;
  325. return;
  326. }
  327. rtsp_st = av_mallocz(sizeof(RTSPStream));
  328. if (!rtsp_st)
  329. return;
  330. rtsp_st->stream_index = -1;
  331. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  332. rtsp_st->sdp_ip = s1->default_ip;
  333. rtsp_st->sdp_ttl = s1->default_ttl;
  334. get_word(buf1, sizeof(buf1), &p); /* port */
  335. rtsp_st->sdp_port = atoi(buf1);
  336. get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
  337. /* XXX: handle list of formats */
  338. get_word(buf1, sizeof(buf1), &p); /* format list */
  339. rtsp_st->sdp_payload_type = atoi(buf1);
  340. if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
  341. /* no corresponding stream */
  342. } else if (rt->server_type == RTSP_SERVER_WMS &&
  343. codec_type == AVMEDIA_TYPE_DATA) {
  344. /* RTX stream, a stream that carries all the other actual
  345. * audio/video streams. Don't expose this to the callers. */
  346. } else {
  347. st = avformat_new_stream(s, NULL);
  348. if (!st)
  349. return;
  350. st->id = rt->nb_rtsp_streams - 1;
  351. rtsp_st->stream_index = st->index;
  352. st->codec->codec_type = codec_type;
  353. if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
  354. RTPDynamicProtocolHandler *handler;
  355. /* if standard payload type, we can find the codec right now */
  356. ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
  357. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  358. st->codec->sample_rate > 0)
  359. avpriv_set_pts_info(st, 32, 1, st->codec->sample_rate);
  360. /* Even static payload types may need a custom depacketizer */
  361. handler = ff_rtp_handler_find_by_id(
  362. rtsp_st->sdp_payload_type, st->codec->codec_type);
  363. init_rtp_handler(handler, rtsp_st, st->codec);
  364. if (handler && handler->init)
  365. handler->init(s, st->index,
  366. rtsp_st->dynamic_protocol_context);
  367. }
  368. }
  369. /* put a default control url */
  370. av_strlcpy(rtsp_st->control_url, rt->control_uri,
  371. sizeof(rtsp_st->control_url));
  372. break;
  373. case 'a':
  374. if (av_strstart(p, "control:", &p)) {
  375. if (s->nb_streams == 0) {
  376. if (!strncmp(p, "rtsp://", 7))
  377. av_strlcpy(rt->control_uri, p,
  378. sizeof(rt->control_uri));
  379. } else {
  380. char proto[32];
  381. /* get the control url */
  382. rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
  383. /* XXX: may need to add full url resolution */
  384. av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
  385. NULL, NULL, 0, p);
  386. if (proto[0] == '\0') {
  387. /* relative control URL */
  388. if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
  389. av_strlcat(rtsp_st->control_url, "/",
  390. sizeof(rtsp_st->control_url));
  391. av_strlcat(rtsp_st->control_url, p,
  392. sizeof(rtsp_st->control_url));
  393. } else
  394. av_strlcpy(rtsp_st->control_url, p,
  395. sizeof(rtsp_st->control_url));
  396. }
  397. } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
  398. /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
  399. get_word(buf1, sizeof(buf1), &p);
  400. payload_type = atoi(buf1);
  401. rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
  402. if (rtsp_st->stream_index >= 0) {
  403. st = s->streams[rtsp_st->stream_index];
  404. sdp_parse_rtpmap(s, st, rtsp_st, payload_type, p);
  405. }
  406. } else if (av_strstart(p, "fmtp:", &p) ||
  407. av_strstart(p, "framesize:", &p)) {
  408. /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
  409. // let dynamic protocol handlers have a stab at the line.
  410. get_word(buf1, sizeof(buf1), &p);
  411. payload_type = atoi(buf1);
  412. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  413. rtsp_st = rt->rtsp_streams[i];
  414. if (rtsp_st->sdp_payload_type == payload_type &&
  415. rtsp_st->dynamic_handler &&
  416. rtsp_st->dynamic_handler->parse_sdp_a_line)
  417. rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
  418. rtsp_st->dynamic_protocol_context, buf);
  419. }
  420. } else if (av_strstart(p, "range:", &p)) {
  421. int64_t start, end;
  422. // this is so that seeking on a streamed file can work.
  423. rtsp_parse_range_npt(p, &start, &end);
  424. s->start_time = start;
  425. /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
  426. s->duration = (end == AV_NOPTS_VALUE) ?
  427. AV_NOPTS_VALUE : end - start;
  428. } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
  429. if (atoi(p) == 1)
  430. rt->transport = RTSP_TRANSPORT_RDT;
  431. } else if (av_strstart(p, "SampleRate:integer;", &p) &&
  432. s->nb_streams > 0) {
  433. st = s->streams[s->nb_streams - 1];
  434. st->codec->sample_rate = atoi(p);
  435. } else {
  436. if (rt->server_type == RTSP_SERVER_WMS)
  437. ff_wms_parse_sdp_a_line(s, p);
  438. if (s->nb_streams > 0) {
  439. rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
  440. if (rt->server_type == RTSP_SERVER_REAL)
  441. ff_real_parse_sdp_a_line(s, rtsp_st->stream_index, p);
  442. if (rtsp_st->dynamic_handler &&
  443. rtsp_st->dynamic_handler->parse_sdp_a_line)
  444. rtsp_st->dynamic_handler->parse_sdp_a_line(s,
  445. rtsp_st->stream_index,
  446. rtsp_st->dynamic_protocol_context, buf);
  447. }
  448. }
  449. break;
  450. }
  451. }
  452. int ff_sdp_parse(AVFormatContext *s, const char *content)
  453. {
  454. RTSPState *rt = s->priv_data;
  455. const char *p;
  456. int letter;
  457. /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
  458. * contain long SDP lines containing complete ASF Headers (several
  459. * kB) or arrays of MDPR (RM stream descriptor) headers plus
  460. * "rulebooks" describing their properties. Therefore, the SDP line
  461. * buffer is large.
  462. *
  463. * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
  464. * in rtpdec_xiph.c. */
  465. char buf[16384], *q;
  466. SDPParseState sdp_parse_state = { { 0 } }, *s1 = &sdp_parse_state;
  467. p = content;
  468. for (;;) {
  469. p += strspn(p, SPACE_CHARS);
  470. letter = *p;
  471. if (letter == '\0')
  472. break;
  473. p++;
  474. if (*p != '=')
  475. goto next_line;
  476. p++;
  477. /* get the content */
  478. q = buf;
  479. while (*p != '\n' && *p != '\r' && *p != '\0') {
  480. if ((q - buf) < sizeof(buf) - 1)
  481. *q++ = *p;
  482. p++;
  483. }
  484. *q = '\0';
  485. sdp_parse_line(s, s1, letter, buf);
  486. next_line:
  487. while (*p != '\n' && *p != '\0')
  488. p++;
  489. if (*p == '\n')
  490. p++;
  491. }
  492. rt->p = av_malloc(sizeof(struct pollfd)*2*(rt->nb_rtsp_streams+1));
  493. if (!rt->p) return AVERROR(ENOMEM);
  494. return 0;
  495. }
  496. #endif /* CONFIG_RTPDEC */
  497. void ff_rtsp_undo_setup(AVFormatContext *s)
  498. {
  499. RTSPState *rt = s->priv_data;
  500. int i;
  501. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  502. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  503. if (!rtsp_st)
  504. continue;
  505. if (rtsp_st->transport_priv) {
  506. if (s->oformat) {
  507. AVFormatContext *rtpctx = rtsp_st->transport_priv;
  508. av_write_trailer(rtpctx);
  509. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  510. uint8_t *ptr;
  511. avio_close_dyn_buf(rtpctx->pb, &ptr);
  512. av_free(ptr);
  513. } else {
  514. avio_close(rtpctx->pb);
  515. }
  516. avformat_free_context(rtpctx);
  517. } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
  518. ff_rdt_parse_close(rtsp_st->transport_priv);
  519. else if (CONFIG_RTPDEC)
  520. ff_rtp_parse_close(rtsp_st->transport_priv);
  521. }
  522. rtsp_st->transport_priv = NULL;
  523. if (rtsp_st->rtp_handle)
  524. ffurl_close(rtsp_st->rtp_handle);
  525. rtsp_st->rtp_handle = NULL;
  526. }
  527. }
  528. /* close and free RTSP streams */
  529. void ff_rtsp_close_streams(AVFormatContext *s)
  530. {
  531. RTSPState *rt = s->priv_data;
  532. int i;
  533. RTSPStream *rtsp_st;
  534. ff_rtsp_undo_setup(s);
  535. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  536. rtsp_st = rt->rtsp_streams[i];
  537. if (rtsp_st) {
  538. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
  539. rtsp_st->dynamic_handler->free(
  540. rtsp_st->dynamic_protocol_context);
  541. av_free(rtsp_st);
  542. }
  543. }
  544. av_free(rt->rtsp_streams);
  545. if (rt->asf_ctx) {
  546. avformat_close_input(&rt->asf_ctx);
  547. }
  548. av_free(rt->p);
  549. av_free(rt->recvbuf);
  550. }
  551. static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
  552. {
  553. RTSPState *rt = s->priv_data;
  554. AVStream *st = NULL;
  555. /* open the RTP context */
  556. if (rtsp_st->stream_index >= 0)
  557. st = s->streams[rtsp_st->stream_index];
  558. if (!st)
  559. s->ctx_flags |= AVFMTCTX_NOHEADER;
  560. if (s->oformat && CONFIG_RTSP_MUXER) {
  561. rtsp_st->transport_priv = ff_rtp_chain_mux_open(s, st,
  562. rtsp_st->rtp_handle,
  563. RTSP_TCP_MAX_PACKET_SIZE);
  564. /* Ownership of rtp_handle is passed to the rtp mux context */
  565. rtsp_st->rtp_handle = NULL;
  566. } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
  567. rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
  568. rtsp_st->dynamic_protocol_context,
  569. rtsp_st->dynamic_handler);
  570. else if (CONFIG_RTPDEC)
  571. rtsp_st->transport_priv = ff_rtp_parse_open(s, st, rtsp_st->rtp_handle,
  572. rtsp_st->sdp_payload_type,
  573. (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
  574. ? 0 : RTP_REORDER_QUEUE_DEFAULT_SIZE);
  575. if (!rtsp_st->transport_priv) {
  576. return AVERROR(ENOMEM);
  577. } else if (rt->transport != RTSP_TRANSPORT_RDT && CONFIG_RTPDEC) {
  578. if (rtsp_st->dynamic_handler) {
  579. ff_rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
  580. rtsp_st->dynamic_protocol_context,
  581. rtsp_st->dynamic_handler);
  582. }
  583. }
  584. return 0;
  585. }
  586. #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
  587. static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
  588. {
  589. const char *p;
  590. int v;
  591. p = *pp;
  592. p += strspn(p, SPACE_CHARS);
  593. v = strtol(p, (char **)&p, 10);
  594. if (*p == '-') {
  595. p++;
  596. *min_ptr = v;
  597. v = strtol(p, (char **)&p, 10);
  598. *max_ptr = v;
  599. } else {
  600. *min_ptr = v;
  601. *max_ptr = v;
  602. }
  603. *pp = p;
  604. }
  605. /* XXX: only one transport specification is parsed */
  606. static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
  607. {
  608. char transport_protocol[16];
  609. char profile[16];
  610. char lower_transport[16];
  611. char parameter[16];
  612. RTSPTransportField *th;
  613. char buf[256];
  614. reply->nb_transports = 0;
  615. for (;;) {
  616. p += strspn(p, SPACE_CHARS);
  617. if (*p == '\0')
  618. break;
  619. th = &reply->transports[reply->nb_transports];
  620. get_word_sep(transport_protocol, sizeof(transport_protocol),
  621. "/", &p);
  622. if (!av_strcasecmp (transport_protocol, "rtp")) {
  623. get_word_sep(profile, sizeof(profile), "/;,", &p);
  624. lower_transport[0] = '\0';
  625. /* rtp/avp/<protocol> */
  626. if (*p == '/') {
  627. get_word_sep(lower_transport, sizeof(lower_transport),
  628. ";,", &p);
  629. }
  630. th->transport = RTSP_TRANSPORT_RTP;
  631. } else if (!av_strcasecmp (transport_protocol, "x-pn-tng") ||
  632. !av_strcasecmp (transport_protocol, "x-real-rdt")) {
  633. /* x-pn-tng/<protocol> */
  634. get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
  635. profile[0] = '\0';
  636. th->transport = RTSP_TRANSPORT_RDT;
  637. }
  638. if (!av_strcasecmp(lower_transport, "TCP"))
  639. th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  640. else
  641. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
  642. if (*p == ';')
  643. p++;
  644. /* get each parameter */
  645. while (*p != '\0' && *p != ',') {
  646. get_word_sep(parameter, sizeof(parameter), "=;,", &p);
  647. if (!strcmp(parameter, "port")) {
  648. if (*p == '=') {
  649. p++;
  650. rtsp_parse_range(&th->port_min, &th->port_max, &p);
  651. }
  652. } else if (!strcmp(parameter, "client_port")) {
  653. if (*p == '=') {
  654. p++;
  655. rtsp_parse_range(&th->client_port_min,
  656. &th->client_port_max, &p);
  657. }
  658. } else if (!strcmp(parameter, "server_port")) {
  659. if (*p == '=') {
  660. p++;
  661. rtsp_parse_range(&th->server_port_min,
  662. &th->server_port_max, &p);
  663. }
  664. } else if (!strcmp(parameter, "interleaved")) {
  665. if (*p == '=') {
  666. p++;
  667. rtsp_parse_range(&th->interleaved_min,
  668. &th->interleaved_max, &p);
  669. }
  670. } else if (!strcmp(parameter, "multicast")) {
  671. if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
  672. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
  673. } else if (!strcmp(parameter, "ttl")) {
  674. if (*p == '=') {
  675. p++;
  676. th->ttl = strtol(p, (char **)&p, 10);
  677. }
  678. } else if (!strcmp(parameter, "destination")) {
  679. if (*p == '=') {
  680. p++;
  681. get_word_sep(buf, sizeof(buf), ";,", &p);
  682. get_sockaddr(buf, &th->destination);
  683. }
  684. } else if (!strcmp(parameter, "source")) {
  685. if (*p == '=') {
  686. p++;
  687. get_word_sep(buf, sizeof(buf), ";,", &p);
  688. av_strlcpy(th->source, buf, sizeof(th->source));
  689. }
  690. }
  691. while (*p != ';' && *p != '\0' && *p != ',')
  692. p++;
  693. if (*p == ';')
  694. p++;
  695. }
  696. if (*p == ',')
  697. p++;
  698. reply->nb_transports++;
  699. }
  700. }
  701. static void handle_rtp_info(RTSPState *rt, const char *url,
  702. uint32_t seq, uint32_t rtptime)
  703. {
  704. int i;
  705. if (!rtptime || !url[0])
  706. return;
  707. if (rt->transport != RTSP_TRANSPORT_RTP)
  708. return;
  709. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  710. RTSPStream *rtsp_st = rt->rtsp_streams[i];
  711. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  712. if (!rtpctx)
  713. continue;
  714. if (!strcmp(rtsp_st->control_url, url)) {
  715. rtpctx->base_timestamp = rtptime;
  716. break;
  717. }
  718. }
  719. }
  720. static void rtsp_parse_rtp_info(RTSPState *rt, const char *p)
  721. {
  722. int read = 0;
  723. char key[20], value[1024], url[1024] = "";
  724. uint32_t seq = 0, rtptime = 0;
  725. for (;;) {
  726. p += strspn(p, SPACE_CHARS);
  727. if (!*p)
  728. break;
  729. get_word_sep(key, sizeof(key), "=", &p);
  730. if (*p != '=')
  731. break;
  732. p++;
  733. get_word_sep(value, sizeof(value), ";, ", &p);
  734. read++;
  735. if (!strcmp(key, "url"))
  736. av_strlcpy(url, value, sizeof(url));
  737. else if (!strcmp(key, "seq"))
  738. seq = strtoul(value, NULL, 10);
  739. else if (!strcmp(key, "rtptime"))
  740. rtptime = strtoul(value, NULL, 10);
  741. if (*p == ',') {
  742. handle_rtp_info(rt, url, seq, rtptime);
  743. url[0] = '\0';
  744. seq = rtptime = 0;
  745. read = 0;
  746. }
  747. if (*p)
  748. p++;
  749. }
  750. if (read > 0)
  751. handle_rtp_info(rt, url, seq, rtptime);
  752. }
  753. void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
  754. RTSPState *rt, const char *method)
  755. {
  756. const char *p;
  757. /* NOTE: we do case independent match for broken servers */
  758. p = buf;
  759. if (av_stristart(p, "Session:", &p)) {
  760. int t;
  761. get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
  762. if (av_stristart(p, ";timeout=", &p) &&
  763. (t = strtol(p, NULL, 10)) > 0) {
  764. reply->timeout = t;
  765. }
  766. } else if (av_stristart(p, "Content-Length:", &p)) {
  767. reply->content_length = strtol(p, NULL, 10);
  768. } else if (av_stristart(p, "Transport:", &p)) {
  769. rtsp_parse_transport(reply, p);
  770. } else if (av_stristart(p, "CSeq:", &p)) {
  771. reply->seq = strtol(p, NULL, 10);
  772. } else if (av_stristart(p, "Range:", &p)) {
  773. rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
  774. } else if (av_stristart(p, "RealChallenge1:", &p)) {
  775. p += strspn(p, SPACE_CHARS);
  776. av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
  777. } else if (av_stristart(p, "Server:", &p)) {
  778. p += strspn(p, SPACE_CHARS);
  779. av_strlcpy(reply->server, p, sizeof(reply->server));
  780. } else if (av_stristart(p, "Notice:", &p) ||
  781. av_stristart(p, "X-Notice:", &p)) {
  782. reply->notice = strtol(p, NULL, 10);
  783. } else if (av_stristart(p, "Location:", &p)) {
  784. p += strspn(p, SPACE_CHARS);
  785. av_strlcpy(reply->location, p , sizeof(reply->location));
  786. } else if (av_stristart(p, "WWW-Authenticate:", &p) && rt) {
  787. p += strspn(p, SPACE_CHARS);
  788. ff_http_auth_handle_header(&rt->auth_state, "WWW-Authenticate", p);
  789. } else if (av_stristart(p, "Authentication-Info:", &p) && rt) {
  790. p += strspn(p, SPACE_CHARS);
  791. ff_http_auth_handle_header(&rt->auth_state, "Authentication-Info", p);
  792. } else if (av_stristart(p, "Content-Base:", &p) && rt) {
  793. p += strspn(p, SPACE_CHARS);
  794. if (method && !strcmp(method, "DESCRIBE"))
  795. av_strlcpy(rt->control_uri, p , sizeof(rt->control_uri));
  796. } else if (av_stristart(p, "RTP-Info:", &p) && rt) {
  797. p += strspn(p, SPACE_CHARS);
  798. if (method && !strcmp(method, "PLAY"))
  799. rtsp_parse_rtp_info(rt, p);
  800. } else if (av_stristart(p, "Public:", &p) && rt) {
  801. if (strstr(p, "GET_PARAMETER") &&
  802. method && !strcmp(method, "OPTIONS"))
  803. rt->get_parameter_supported = 1;
  804. } else if (av_stristart(p, "x-Accept-Dynamic-Rate:", &p) && rt) {
  805. p += strspn(p, SPACE_CHARS);
  806. rt->accept_dynamic_rate = atoi(p);
  807. }
  808. }
  809. /* skip a RTP/TCP interleaved packet */
  810. void ff_rtsp_skip_packet(AVFormatContext *s)
  811. {
  812. RTSPState *rt = s->priv_data;
  813. int ret, len, len1;
  814. uint8_t buf[1024];
  815. ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
  816. if (ret != 3)
  817. return;
  818. len = AV_RB16(buf + 1);
  819. av_dlog(s, "skipping RTP packet len=%d\n", len);
  820. /* skip payload */
  821. while (len > 0) {
  822. len1 = len;
  823. if (len1 > sizeof(buf))
  824. len1 = sizeof(buf);
  825. ret = ffurl_read_complete(rt->rtsp_hd, buf, len1);
  826. if (ret != len1)
  827. return;
  828. len -= len1;
  829. }
  830. }
  831. int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
  832. unsigned char **content_ptr,
  833. int return_on_interleaved_data, const char *method)
  834. {
  835. RTSPState *rt = s->priv_data;
  836. char buf[4096], buf1[1024], *q;
  837. unsigned char ch;
  838. const char *p;
  839. int ret, content_length, line_count = 0, request = 0;
  840. unsigned char *content = NULL;
  841. start:
  842. line_count = 0;
  843. request = 0;
  844. content = NULL;
  845. memset(reply, 0, sizeof(*reply));
  846. /* parse reply (XXX: use buffers) */
  847. rt->last_reply[0] = '\0';
  848. for (;;) {
  849. q = buf;
  850. for (;;) {
  851. ret = ffurl_read_complete(rt->rtsp_hd, &ch, 1);
  852. av_dlog(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
  853. if (ret != 1)
  854. return AVERROR_EOF;
  855. if (ch == '\n')
  856. break;
  857. if (ch == '$') {
  858. /* XXX: only parse it if first char on line ? */
  859. if (return_on_interleaved_data) {
  860. return 1;
  861. } else
  862. ff_rtsp_skip_packet(s);
  863. } else if (ch != '\r') {
  864. if ((q - buf) < sizeof(buf) - 1)
  865. *q++ = ch;
  866. }
  867. }
  868. *q = '\0';
  869. av_dlog(s, "line='%s'\n", buf);
  870. /* test if last line */
  871. if (buf[0] == '\0')
  872. break;
  873. p = buf;
  874. if (line_count == 0) {
  875. /* get reply code */
  876. get_word(buf1, sizeof(buf1), &p);
  877. if (!strncmp(buf1, "RTSP/", 5)) {
  878. get_word(buf1, sizeof(buf1), &p);
  879. reply->status_code = atoi(buf1);
  880. av_strlcpy(reply->reason, p, sizeof(reply->reason));
  881. } else {
  882. av_strlcpy(reply->reason, buf1, sizeof(reply->reason)); // method
  883. get_word(buf1, sizeof(buf1), &p); // object
  884. request = 1;
  885. }
  886. } else {
  887. ff_rtsp_parse_line(reply, p, rt, method);
  888. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  889. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  890. }
  891. line_count++;
  892. }
  893. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0' && !request)
  894. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  895. content_length = reply->content_length;
  896. if (content_length > 0) {
  897. /* leave some room for a trailing '\0' (useful for simple parsing) */
  898. content = av_malloc(content_length + 1);
  899. ffurl_read_complete(rt->rtsp_hd, content, content_length);
  900. content[content_length] = '\0';
  901. }
  902. if (content_ptr)
  903. *content_ptr = content;
  904. else
  905. av_free(content);
  906. if (request) {
  907. char buf[1024];
  908. char base64buf[AV_BASE64_SIZE(sizeof(buf))];
  909. const char* ptr = buf;
  910. if (!strcmp(reply->reason, "OPTIONS")) {
  911. snprintf(buf, sizeof(buf), "RTSP/1.0 200 OK\r\n");
  912. if (reply->seq)
  913. av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", reply->seq);
  914. if (reply->session_id[0])
  915. av_strlcatf(buf, sizeof(buf), "Session: %s\r\n",
  916. reply->session_id);
  917. } else {
  918. snprintf(buf, sizeof(buf), "RTSP/1.0 501 Not Implemented\r\n");
  919. }
  920. av_strlcat(buf, "\r\n", sizeof(buf));
  921. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  922. av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
  923. ptr = base64buf;
  924. }
  925. ffurl_write(rt->rtsp_hd_out, ptr, strlen(ptr));
  926. rt->last_cmd_time = av_gettime();
  927. /* Even if the request from the server had data, it is not the data
  928. * that the caller wants or expects. The memory could also be leaked
  929. * if the actual following reply has content data. */
  930. if (content_ptr)
  931. av_freep(content_ptr);
  932. /* If method is set, this is called from ff_rtsp_send_cmd,
  933. * where a reply to exactly this request is awaited. For
  934. * callers from within packet receiving, we just want to
  935. * return to the caller and go back to receiving packets. */
  936. if (method)
  937. goto start;
  938. return 0;
  939. }
  940. if (rt->seq != reply->seq) {
  941. av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
  942. rt->seq, reply->seq);
  943. }
  944. /* EOS */
  945. if (reply->notice == 2101 /* End-of-Stream Reached */ ||
  946. reply->notice == 2104 /* Start-of-Stream Reached */ ||
  947. reply->notice == 2306 /* Continuous Feed Terminated */) {
  948. rt->state = RTSP_STATE_IDLE;
  949. } else if (reply->notice >= 4400 && reply->notice < 5500) {
  950. return AVERROR(EIO); /* data or server error */
  951. } else if (reply->notice == 2401 /* Ticket Expired */ ||
  952. (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
  953. return AVERROR(EPERM);
  954. return 0;
  955. }
  956. /**
  957. * Send a command to the RTSP server without waiting for the reply.
  958. *
  959. * @param s RTSP (de)muxer context
  960. * @param method the method for the request
  961. * @param url the target url for the request
  962. * @param headers extra header lines to include in the request
  963. * @param send_content if non-null, the data to send as request body content
  964. * @param send_content_length the length of the send_content data, or 0 if
  965. * send_content is null
  966. *
  967. * @return zero if success, nonzero otherwise
  968. */
  969. static int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
  970. const char *method, const char *url,
  971. const char *headers,
  972. const unsigned char *send_content,
  973. int send_content_length)
  974. {
  975. RTSPState *rt = s->priv_data;
  976. char buf[4096], *out_buf;
  977. char base64buf[AV_BASE64_SIZE(sizeof(buf))];
  978. /* Add in RTSP headers */
  979. out_buf = buf;
  980. rt->seq++;
  981. snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
  982. if (headers)
  983. av_strlcat(buf, headers, sizeof(buf));
  984. av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
  985. if (rt->session_id[0] != '\0' && (!headers ||
  986. !strstr(headers, "\nIf-Match:"))) {
  987. av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
  988. }
  989. if (rt->auth[0]) {
  990. char *str = ff_http_auth_create_response(&rt->auth_state,
  991. rt->auth, url, method);
  992. if (str)
  993. av_strlcat(buf, str, sizeof(buf));
  994. av_free(str);
  995. }
  996. if (send_content_length > 0 && send_content)
  997. av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
  998. av_strlcat(buf, "\r\n", sizeof(buf));
  999. /* base64 encode rtsp if tunneling */
  1000. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1001. av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
  1002. out_buf = base64buf;
  1003. }
  1004. av_dlog(s, "Sending:\n%s--\n", buf);
  1005. ffurl_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
  1006. if (send_content_length > 0 && send_content) {
  1007. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1008. av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
  1009. "with content data not supported\n");
  1010. return AVERROR_PATCHWELCOME;
  1011. }
  1012. ffurl_write(rt->rtsp_hd_out, send_content, send_content_length);
  1013. }
  1014. rt->last_cmd_time = av_gettime();
  1015. return 0;
  1016. }
  1017. int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
  1018. const char *url, const char *headers)
  1019. {
  1020. return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
  1021. }
  1022. int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
  1023. const char *headers, RTSPMessageHeader *reply,
  1024. unsigned char **content_ptr)
  1025. {
  1026. return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
  1027. content_ptr, NULL, 0);
  1028. }
  1029. int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
  1030. const char *method, const char *url,
  1031. const char *header,
  1032. RTSPMessageHeader *reply,
  1033. unsigned char **content_ptr,
  1034. const unsigned char *send_content,
  1035. int send_content_length)
  1036. {
  1037. RTSPState *rt = s->priv_data;
  1038. HTTPAuthType cur_auth_type;
  1039. int ret, attempts = 0;
  1040. retry:
  1041. cur_auth_type = rt->auth_state.auth_type;
  1042. if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
  1043. send_content,
  1044. send_content_length)))
  1045. return ret;
  1046. if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
  1047. return ret;
  1048. attempts++;
  1049. if (reply->status_code == 401 &&
  1050. (cur_auth_type == HTTP_AUTH_NONE || rt->auth_state.stale) &&
  1051. rt->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2)
  1052. goto retry;
  1053. if (reply->status_code > 400){
  1054. av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
  1055. method,
  1056. reply->status_code,
  1057. reply->reason);
  1058. av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
  1059. }
  1060. return 0;
  1061. }
  1062. int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
  1063. int lower_transport, const char *real_challenge)
  1064. {
  1065. RTSPState *rt = s->priv_data;
  1066. int rtx = 0, j, i, err, interleave = 0, port_off;
  1067. RTSPStream *rtsp_st;
  1068. RTSPMessageHeader reply1, *reply = &reply1;
  1069. char cmd[2048];
  1070. const char *trans_pref;
  1071. if (rt->transport == RTSP_TRANSPORT_RDT)
  1072. trans_pref = "x-pn-tng";
  1073. else
  1074. trans_pref = "RTP/AVP";
  1075. /* default timeout: 1 minute */
  1076. rt->timeout = 60;
  1077. /* for each stream, make the setup request */
  1078. /* XXX: we assume the same server is used for the control of each
  1079. * RTSP stream */
  1080. /* Choose a random starting offset within the first half of the
  1081. * port range, to allow for a number of ports to try even if the offset
  1082. * happens to be at the end of the random range. */
  1083. port_off = av_get_random_seed() % ((rt->rtp_port_max - rt->rtp_port_min)/2);
  1084. /* even random offset */
  1085. port_off -= port_off & 0x01;
  1086. for (j = rt->rtp_port_min + port_off, i = 0; i < rt->nb_rtsp_streams; ++i) {
  1087. char transport[2048];
  1088. /*
  1089. * WMS serves all UDP data over a single connection, the RTX, which
  1090. * isn't necessarily the first in the SDP but has to be the first
  1091. * to be set up, else the second/third SETUP will fail with a 461.
  1092. */
  1093. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  1094. rt->server_type == RTSP_SERVER_WMS) {
  1095. if (i == 0) {
  1096. /* rtx first */
  1097. for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
  1098. int len = strlen(rt->rtsp_streams[rtx]->control_url);
  1099. if (len >= 4 &&
  1100. !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
  1101. "/rtx"))
  1102. break;
  1103. }
  1104. if (rtx == rt->nb_rtsp_streams)
  1105. return -1; /* no RTX found */
  1106. rtsp_st = rt->rtsp_streams[rtx];
  1107. } else
  1108. rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
  1109. } else
  1110. rtsp_st = rt->rtsp_streams[i];
  1111. /* RTP/UDP */
  1112. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  1113. char buf[256];
  1114. if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
  1115. port = reply->transports[0].client_port_min;
  1116. goto have_port;
  1117. }
  1118. /* first try in specified port range */
  1119. while (j <= rt->rtp_port_max) {
  1120. ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
  1121. "?localport=%d", j);
  1122. /* we will use two ports per rtp stream (rtp and rtcp) */
  1123. j += 2;
  1124. if (!ffurl_open(&rtsp_st->rtp_handle, buf, AVIO_FLAG_READ_WRITE,
  1125. &s->interrupt_callback, NULL))
  1126. goto rtp_opened;
  1127. }
  1128. av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");
  1129. err = AVERROR(EIO);
  1130. goto fail;
  1131. rtp_opened:
  1132. port = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
  1133. have_port:
  1134. snprintf(transport, sizeof(transport) - 1,
  1135. "%s/UDP;", trans_pref);
  1136. if (rt->server_type != RTSP_SERVER_REAL)
  1137. av_strlcat(transport, "unicast;", sizeof(transport));
  1138. av_strlcatf(transport, sizeof(transport),
  1139. "client_port=%d", port);
  1140. if (rt->transport == RTSP_TRANSPORT_RTP &&
  1141. !(rt->server_type == RTSP_SERVER_WMS && i > 0))
  1142. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  1143. }
  1144. /* RTP/TCP */
  1145. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1146. /* For WMS streams, the application streams are only used for
  1147. * UDP. When trying to set it up for TCP streams, the server
  1148. * will return an error. Therefore, we skip those streams. */
  1149. if (rt->server_type == RTSP_SERVER_WMS &&
  1150. (rtsp_st->stream_index < 0 ||
  1151. s->streams[rtsp_st->stream_index]->codec->codec_type ==
  1152. AVMEDIA_TYPE_DATA))
  1153. continue;
  1154. snprintf(transport, sizeof(transport) - 1,
  1155. "%s/TCP;", trans_pref);
  1156. if (rt->transport != RTSP_TRANSPORT_RDT)
  1157. av_strlcat(transport, "unicast;", sizeof(transport));
  1158. av_strlcatf(transport, sizeof(transport),
  1159. "interleaved=%d-%d",
  1160. interleave, interleave + 1);
  1161. interleave += 2;
  1162. }
  1163. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  1164. snprintf(transport, sizeof(transport) - 1,
  1165. "%s/UDP;multicast", trans_pref);
  1166. }
  1167. if (s->oformat) {
  1168. av_strlcat(transport, ";mode=receive", sizeof(transport));
  1169. } else if (rt->server_type == RTSP_SERVER_REAL ||
  1170. rt->server_type == RTSP_SERVER_WMS)
  1171. av_strlcat(transport, ";mode=play", sizeof(transport));
  1172. snprintf(cmd, sizeof(cmd),
  1173. "Transport: %s\r\n",
  1174. transport);
  1175. if (rt->accept_dynamic_rate)
  1176. av_strlcat(cmd, "x-Dynamic-Rate: 0\r\n", sizeof(cmd));
  1177. if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
  1178. char real_res[41], real_csum[9];
  1179. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  1180. real_challenge);
  1181. av_strlcatf(cmd, sizeof(cmd),
  1182. "If-Match: %s\r\n"
  1183. "RealChallenge2: %s, sd=%s\r\n",
  1184. rt->session_id, real_res, real_csum);
  1185. }
  1186. ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
  1187. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  1188. err = 1;
  1189. goto fail;
  1190. } else if (reply->status_code != RTSP_STATUS_OK ||
  1191. reply->nb_transports != 1) {
  1192. err = AVERROR_INVALIDDATA;
  1193. goto fail;
  1194. }
  1195. /* XXX: same protocol for all streams is required */
  1196. if (i > 0) {
  1197. if (reply->transports[0].lower_transport != rt->lower_transport ||
  1198. reply->transports[0].transport != rt->transport) {
  1199. err = AVERROR_INVALIDDATA;
  1200. goto fail;
  1201. }
  1202. } else {
  1203. rt->lower_transport = reply->transports[0].lower_transport;
  1204. rt->transport = reply->transports[0].transport;
  1205. }
  1206. /* Fail if the server responded with another lower transport mode
  1207. * than what we requested. */
  1208. if (reply->transports[0].lower_transport != lower_transport) {
  1209. av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
  1210. err = AVERROR_INVALIDDATA;
  1211. goto fail;
  1212. }
  1213. switch(reply->transports[0].lower_transport) {
  1214. case RTSP_LOWER_TRANSPORT_TCP:
  1215. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  1216. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  1217. break;
  1218. case RTSP_LOWER_TRANSPORT_UDP: {
  1219. char url[1024], options[30] = "";
  1220. if (rt->rtsp_flags & RTSP_FLAG_FILTER_SRC)
  1221. av_strlcpy(options, "?connect=1", sizeof(options));
  1222. /* Use source address if specified */
  1223. if (reply->transports[0].source[0]) {
  1224. ff_url_join(url, sizeof(url), "rtp", NULL,
  1225. reply->transports[0].source,
  1226. reply->transports[0].server_port_min, "%s", options);
  1227. } else {
  1228. ff_url_join(url, sizeof(url), "rtp", NULL, host,
  1229. reply->transports[0].server_port_min, "%s", options);
  1230. }
  1231. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
  1232. ff_rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  1233. err = AVERROR_INVALIDDATA;
  1234. goto fail;
  1235. }
  1236. /* Try to initialize the connection state in a
  1237. * potential NAT router by sending dummy packets.
  1238. * RTP/RTCP dummy packets are used for RDT, too.
  1239. */
  1240. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
  1241. CONFIG_RTPDEC)
  1242. ff_rtp_send_punch_packets(rtsp_st->rtp_handle);
  1243. break;
  1244. }
  1245. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
  1246. char url[1024], namebuf[50], optbuf[20] = "";
  1247. struct sockaddr_storage addr;
  1248. int port, ttl;
  1249. if (reply->transports[0].destination.ss_family) {
  1250. addr = reply->transports[0].destination;
  1251. port = reply->transports[0].port_min;
  1252. ttl = reply->transports[0].ttl;
  1253. } else {
  1254. addr = rtsp_st->sdp_ip;
  1255. port = rtsp_st->sdp_port;
  1256. ttl = rtsp_st->sdp_ttl;
  1257. }
  1258. if (ttl > 0)
  1259. snprintf(optbuf, sizeof(optbuf), "?ttl=%d", ttl);
  1260. getnameinfo((struct sockaddr*) &addr, sizeof(addr),
  1261. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1262. ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
  1263. port, "%s", optbuf);
  1264. if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
  1265. &s->interrupt_callback, NULL) < 0) {
  1266. err = AVERROR_INVALIDDATA;
  1267. goto fail;
  1268. }
  1269. break;
  1270. }
  1271. }
  1272. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1273. goto fail;
  1274. }
  1275. if (rt->nb_rtsp_streams && reply->timeout > 0)
  1276. rt->timeout = reply->timeout;
  1277. if (rt->server_type == RTSP_SERVER_REAL)
  1278. rt->need_subscription = 1;
  1279. return 0;
  1280. fail:
  1281. ff_rtsp_undo_setup(s);
  1282. return err;
  1283. }
  1284. void ff_rtsp_close_connections(AVFormatContext *s)
  1285. {
  1286. RTSPState *rt = s->priv_data;
  1287. if (rt->rtsp_hd_out != rt->rtsp_hd) ffurl_close(rt->rtsp_hd_out);
  1288. ffurl_close(rt->rtsp_hd);
  1289. rt->rtsp_hd = rt->rtsp_hd_out = NULL;
  1290. }
  1291. int ff_rtsp_connect(AVFormatContext *s)
  1292. {
  1293. RTSPState *rt = s->priv_data;
  1294. char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
  1295. int port, err, tcp_fd;
  1296. RTSPMessageHeader reply1 = {0}, *reply = &reply1;
  1297. int lower_transport_mask = 0;
  1298. char real_challenge[64] = "";
  1299. struct sockaddr_storage peer;
  1300. socklen_t peer_len = sizeof(peer);
  1301. if (rt->rtp_port_max < rt->rtp_port_min) {
  1302. av_log(s, AV_LOG_ERROR, "Invalid UDP port range, max port %d less "
  1303. "than min port %d\n", rt->rtp_port_max,
  1304. rt->rtp_port_min);
  1305. return AVERROR(EINVAL);
  1306. }
  1307. if (!ff_network_init())
  1308. return AVERROR(EIO);
  1309. if (s->max_delay < 0) /* Not set by the caller */
  1310. s->max_delay = s->iformat ? DEFAULT_REORDERING_DELAY : 0;
  1311. rt->control_transport = RTSP_MODE_PLAIN;
  1312. if (rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_HTTP)) {
  1313. rt->lower_transport_mask = 1 << RTSP_LOWER_TRANSPORT_TCP;
  1314. rt->control_transport = RTSP_MODE_TUNNEL;
  1315. }
  1316. /* Only pass through valid flags from here */
  1317. rt->lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1318. redirect:
  1319. lower_transport_mask = rt->lower_transport_mask;
  1320. /* extract hostname and port */
  1321. av_url_split(NULL, 0, auth, sizeof(auth),
  1322. host, sizeof(host), &port, path, sizeof(path), s->filename);
  1323. if (*auth) {
  1324. av_strlcpy(rt->auth, auth, sizeof(rt->auth));
  1325. }
  1326. if (port < 0)
  1327. port = RTSP_DEFAULT_PORT;
  1328. if (!lower_transport_mask)
  1329. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1330. if (s->oformat) {
  1331. /* Only UDP or TCP - UDP multicast isn't supported. */
  1332. lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
  1333. (1 << RTSP_LOWER_TRANSPORT_TCP);
  1334. if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
  1335. av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
  1336. "only UDP and TCP are supported for output.\n");
  1337. err = AVERROR(EINVAL);
  1338. goto fail;
  1339. }
  1340. }
  1341. /* Construct the URI used in request; this is similar to s->filename,
  1342. * but with authentication credentials removed and RTSP specific options
  1343. * stripped out. */
  1344. ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
  1345. host, port, "%s", path);
  1346. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1347. /* set up initial handshake for tunneling */
  1348. char httpname[1024];
  1349. char sessioncookie[17];
  1350. char headers[1024];
  1351. ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
  1352. snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
  1353. av_get_random_seed(), av_get_random_seed());
  1354. /* GET requests */
  1355. if (ffurl_alloc(&rt->rtsp_hd, httpname, AVIO_FLAG_READ,
  1356. &s->interrupt_callback) < 0) {
  1357. err = AVERROR(EIO);
  1358. goto fail;
  1359. }
  1360. /* generate GET headers */
  1361. snprintf(headers, sizeof(headers),
  1362. "x-sessioncookie: %s\r\n"
  1363. "Accept: application/x-rtsp-tunnelled\r\n"
  1364. "Pragma: no-cache\r\n"
  1365. "Cache-Control: no-cache\r\n",
  1366. sessioncookie);
  1367. av_opt_set(rt->rtsp_hd->priv_data, "headers", headers, 0);
  1368. /* complete the connection */
  1369. if (ffurl_connect(rt->rtsp_hd, NULL)) {
  1370. err = AVERROR(EIO);
  1371. goto fail;
  1372. }
  1373. /* POST requests */
  1374. if (ffurl_alloc(&rt->rtsp_hd_out, httpname, AVIO_FLAG_WRITE,
  1375. &s->interrupt_callback) < 0 ) {
  1376. err = AVERROR(EIO);
  1377. goto fail;
  1378. }
  1379. /* generate POST headers */
  1380. snprintf(headers, sizeof(headers),
  1381. "x-sessioncookie: %s\r\n"
  1382. "Content-Type: application/x-rtsp-tunnelled\r\n"
  1383. "Pragma: no-cache\r\n"
  1384. "Cache-Control: no-cache\r\n"
  1385. "Content-Length: 32767\r\n"
  1386. "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
  1387. sessioncookie);
  1388. av_opt_set(rt->rtsp_hd_out->priv_data, "headers", headers, 0);
  1389. av_opt_set(rt->rtsp_hd_out->priv_data, "chunked_post", "0", 0);
  1390. /* Initialize the authentication state for the POST session. The HTTP
  1391. * protocol implementation doesn't properly handle multi-pass
  1392. * authentication for POST requests, since it would require one of
  1393. * the following:
  1394. * - implementing Expect: 100-continue, which many HTTP servers
  1395. * don't support anyway, even less the RTSP servers that do HTTP
  1396. * tunneling
  1397. * - sending the whole POST data until getting a 401 reply specifying
  1398. * what authentication method to use, then resending all that data
  1399. * - waiting for potential 401 replies directly after sending the
  1400. * POST header (waiting for some unspecified time)
  1401. * Therefore, we copy the full auth state, which works for both basic
  1402. * and digest. (For digest, we would have to synchronize the nonce
  1403. * count variable between the two sessions, if we'd do more requests
  1404. * with the original session, though.)
  1405. */
  1406. ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
  1407. /* complete the connection */
  1408. if (ffurl_connect(rt->rtsp_hd_out, NULL)) {
  1409. err = AVERROR(EIO);
  1410. goto fail;
  1411. }
  1412. } else {
  1413. /* open the tcp connection */
  1414. ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
  1415. if (ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
  1416. &s->interrupt_callback, NULL) < 0) {
  1417. err = AVERROR(EIO);
  1418. goto fail;
  1419. }
  1420. rt->rtsp_hd_out = rt->rtsp_hd;
  1421. }
  1422. rt->seq = 0;
  1423. tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
  1424. if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
  1425. getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
  1426. NULL, 0, NI_NUMERICHOST);
  1427. }
  1428. /* request options supported by the server; this also detects server
  1429. * type */
  1430. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1431. cmd[0] = 0;
  1432. if (rt->server_type == RTSP_SERVER_REAL)
  1433. av_strlcat(cmd,
  1434. /*
  1435. * The following entries are required for proper
  1436. * streaming from a Realmedia server. They are
  1437. * interdependent in some way although we currently
  1438. * don't quite understand how. Values were copied
  1439. * from mplayer SVN r23589.
  1440. * ClientChallenge is a 16-byte ID in hex
  1441. * CompanyID is a 16-byte ID in base64
  1442. */
  1443. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1444. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1445. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1446. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1447. sizeof(cmd));
  1448. ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
  1449. if (reply->status_code != RTSP_STATUS_OK) {
  1450. err = AVERROR_INVALIDDATA;
  1451. goto fail;
  1452. }
  1453. /* detect server type if not standard-compliant RTP */
  1454. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1455. rt->server_type = RTSP_SERVER_REAL;
  1456. continue;
  1457. } else if (!av_strncasecmp(reply->server, "WMServer/", 9)) {
  1458. rt->server_type = RTSP_SERVER_WMS;
  1459. } else if (rt->server_type == RTSP_SERVER_REAL)
  1460. strcpy(real_challenge, reply->real_challenge);
  1461. break;
  1462. }
  1463. if (s->iformat && CONFIG_RTSP_DEMUXER)
  1464. err = ff_rtsp_setup_input_streams(s, reply);
  1465. else if (CONFIG_RTSP_MUXER)
  1466. err = ff_rtsp_setup_output_streams(s, host);
  1467. if (err)
  1468. goto fail;
  1469. do {
  1470. int lower_transport = ff_log2_tab[lower_transport_mask &
  1471. ~(lower_transport_mask - 1)];
  1472. err = ff_rtsp_make_setup_request(s, host, port, lower_transport,
  1473. rt->server_type == RTSP_SERVER_REAL ?
  1474. real_challenge : NULL);
  1475. if (err < 0)
  1476. goto fail;
  1477. lower_transport_mask &= ~(1 << lower_transport);
  1478. if (lower_transport_mask == 0 && err == 1) {
  1479. err = AVERROR(EPROTONOSUPPORT);
  1480. goto fail;
  1481. }
  1482. } while (err);
  1483. rt->lower_transport_mask = lower_transport_mask;
  1484. av_strlcpy(rt->real_challenge, real_challenge, sizeof(rt->real_challenge));
  1485. rt->state = RTSP_STATE_IDLE;
  1486. rt->seek_timestamp = 0; /* default is to start stream at position zero */
  1487. return 0;
  1488. fail:
  1489. ff_rtsp_close_streams(s);
  1490. ff_rtsp_close_connections(s);
  1491. if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
  1492. av_strlcpy(s->filename, reply->location, sizeof(s->filename));
  1493. av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
  1494. reply->status_code,
  1495. s->filename);
  1496. goto redirect;
  1497. }
  1498. ff_network_close();
  1499. return err;
  1500. }
  1501. #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
  1502. #if CONFIG_RTPDEC
  1503. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1504. uint8_t *buf, int buf_size, int64_t wait_end)
  1505. {
  1506. RTSPState *rt = s->priv_data;
  1507. RTSPStream *rtsp_st;
  1508. int n, i, ret, tcp_fd, timeout_cnt = 0;
  1509. int max_p = 0;
  1510. struct pollfd *p = rt->p;
  1511. for (;;) {
  1512. if (ff_check_interrupt(&s->interrupt_callback))
  1513. return AVERROR_EXIT;
  1514. if (wait_end && wait_end - av_gettime() < 0)
  1515. return AVERROR(EAGAIN);
  1516. max_p = 0;
  1517. if (rt->rtsp_hd) {
  1518. tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
  1519. p[max_p].fd = tcp_fd;
  1520. p[max_p++].events = POLLIN;
  1521. } else {
  1522. tcp_fd = -1;
  1523. }
  1524. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1525. rtsp_st = rt->rtsp_streams[i];
  1526. if (rtsp_st->rtp_handle) {
  1527. p[max_p].fd = ffurl_get_file_handle(rtsp_st->rtp_handle);
  1528. p[max_p++].events = POLLIN;
  1529. p[max_p].fd = ff_rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
  1530. p[max_p++].events = POLLIN;
  1531. }
  1532. }
  1533. n = poll(p, max_p, POLL_TIMEOUT_MS);
  1534. if (n > 0) {
  1535. int j = 1 - (tcp_fd == -1);
  1536. timeout_cnt = 0;
  1537. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1538. rtsp_st = rt->rtsp_streams[i];
  1539. if (rtsp_st->rtp_handle) {
  1540. if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
  1541. ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
  1542. if (ret > 0) {
  1543. *prtsp_st = rtsp_st;
  1544. return ret;
  1545. }
  1546. }
  1547. j+=2;
  1548. }
  1549. }
  1550. #if CONFIG_RTSP_DEMUXER
  1551. if (tcp_fd != -1 && p[0].revents & POLLIN) {
  1552. RTSPMessageHeader reply;
  1553. ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
  1554. if (ret < 0)
  1555. return ret;
  1556. /* XXX: parse message */
  1557. if (rt->state != RTSP_STATE_STREAMING)
  1558. return 0;
  1559. }
  1560. #endif
  1561. } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
  1562. return AVERROR(ETIMEDOUT);
  1563. } else if (n < 0 && errno != EINTR)
  1564. return AVERROR(errno);
  1565. }
  1566. }
  1567. int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
  1568. {
  1569. RTSPState *rt = s->priv_data;
  1570. int ret, len;
  1571. RTSPStream *rtsp_st, *first_queue_st = NULL;
  1572. int64_t wait_end = 0;
  1573. if (rt->nb_byes == rt->nb_rtsp_streams)
  1574. return AVERROR_EOF;
  1575. /* get next frames from the same RTP packet */
  1576. if (rt->cur_transport_priv) {
  1577. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1578. ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1579. } else
  1580. ret = ff_rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1581. if (ret == 0) {
  1582. rt->cur_transport_priv = NULL;
  1583. return 0;
  1584. } else if (ret == 1) {
  1585. return 0;
  1586. } else
  1587. rt->cur_transport_priv = NULL;
  1588. }
  1589. if (rt->transport == RTSP_TRANSPORT_RTP) {
  1590. int i;
  1591. int64_t first_queue_time = 0;
  1592. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1593. RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
  1594. int64_t queue_time;
  1595. if (!rtpctx)
  1596. continue;
  1597. queue_time = ff_rtp_queued_packet_time(rtpctx);
  1598. if (queue_time && (queue_time - first_queue_time < 0 ||
  1599. !first_queue_time)) {
  1600. first_queue_time = queue_time;
  1601. first_queue_st = rt->rtsp_streams[i];
  1602. }
  1603. }
  1604. if (first_queue_time)
  1605. wait_end = first_queue_time + s->max_delay;
  1606. }
  1607. /* read next RTP packet */
  1608. redo:
  1609. if (!rt->recvbuf) {
  1610. rt->recvbuf = av_malloc(RECVBUF_SIZE);
  1611. if (!rt->recvbuf)
  1612. return AVERROR(ENOMEM);
  1613. }
  1614. switch(rt->lower_transport) {
  1615. default:
  1616. #if CONFIG_RTSP_DEMUXER
  1617. case RTSP_LOWER_TRANSPORT_TCP:
  1618. len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
  1619. break;
  1620. #endif
  1621. case RTSP_LOWER_TRANSPORT_UDP:
  1622. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1623. len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
  1624. if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1625. ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
  1626. break;
  1627. }
  1628. if (len == AVERROR(EAGAIN) && first_queue_st &&
  1629. rt->transport == RTSP_TRANSPORT_RTP) {
  1630. rtsp_st = first_queue_st;
  1631. ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
  1632. goto end;
  1633. }
  1634. if (len < 0)
  1635. return len;
  1636. if (len == 0)
  1637. return AVERROR_EOF;
  1638. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1639. ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1640. } else {
  1641. ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1642. if (ret < 0) {
  1643. /* Either bad packet, or a RTCP packet. Check if the
  1644. * first_rtcp_ntp_time field was initialized. */
  1645. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1646. if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
  1647. /* first_rtcp_ntp_time has been initialized for this stream,
  1648. * copy the same value to all other uninitialized streams,
  1649. * in order to map their timestamp origin to the same ntp time
  1650. * as this one. */
  1651. int i;
  1652. AVStream *st = NULL;
  1653. if (rtsp_st->stream_index >= 0)
  1654. st = s->streams[rtsp_st->stream_index];
  1655. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1656. RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
  1657. AVStream *st2 = NULL;
  1658. if (rt->rtsp_streams[i]->stream_index >= 0)
  1659. st2 = s->streams[rt->rtsp_streams[i]->stream_index];
  1660. if (rtpctx2 && st && st2 &&
  1661. rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
  1662. rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
  1663. rtpctx2->rtcp_ts_offset = av_rescale_q(
  1664. rtpctx->rtcp_ts_offset, st->time_base,
  1665. st2->time_base);
  1666. }
  1667. }
  1668. }
  1669. if (ret == -RTCP_BYE) {
  1670. rt->nb_byes++;
  1671. av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
  1672. rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
  1673. if (rt->nb_byes == rt->nb_rtsp_streams)
  1674. return AVERROR_EOF;
  1675. }
  1676. }
  1677. }
  1678. end:
  1679. if (ret < 0)
  1680. goto redo;
  1681. if (ret == 1)
  1682. /* more packets may follow, so we save the RTP context */
  1683. rt->cur_transport_priv = rtsp_st->transport_priv;
  1684. return ret;
  1685. }
  1686. #endif /* CONFIG_RTPDEC */
  1687. #if CONFIG_SDP_DEMUXER
  1688. static int sdp_probe(AVProbeData *p1)
  1689. {
  1690. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1691. /* we look for a line beginning "c=IN IP" */
  1692. while (p < p_end && *p != '\0') {
  1693. if (p + sizeof("c=IN IP") - 1 < p_end &&
  1694. av_strstart(p, "c=IN IP", NULL))
  1695. return AVPROBE_SCORE_MAX / 2;
  1696. while (p < p_end - 1 && *p != '\n') p++;
  1697. if (++p >= p_end)
  1698. break;
  1699. if (*p == '\r')
  1700. p++;
  1701. }
  1702. return 0;
  1703. }
  1704. static int sdp_read_header(AVFormatContext *s)
  1705. {
  1706. RTSPState *rt = s->priv_data;
  1707. RTSPStream *rtsp_st;
  1708. int size, i, err;
  1709. char *content;
  1710. char url[1024];
  1711. if (!ff_network_init())
  1712. return AVERROR(EIO);
  1713. if (s->max_delay < 0) /* Not set by the caller */
  1714. s->max_delay = DEFAULT_REORDERING_DELAY;
  1715. /* read the whole sdp file */
  1716. /* XXX: better loading */
  1717. content = av_malloc(SDP_MAX_SIZE);
  1718. size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);
  1719. if (size <= 0) {
  1720. av_free(content);
  1721. return AVERROR_INVALIDDATA;
  1722. }
  1723. content[size] ='\0';
  1724. err = ff_sdp_parse(s, content);
  1725. av_free(content);
  1726. if (err) goto fail;
  1727. /* open each RTP stream */
  1728. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1729. char namebuf[50];
  1730. rtsp_st = rt->rtsp_streams[i];
  1731. getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
  1732. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1733. ff_url_join(url, sizeof(url), "rtp", NULL,
  1734. namebuf, rtsp_st->sdp_port,
  1735. "?localport=%d&ttl=%d&connect=%d", rtsp_st->sdp_port,
  1736. rtsp_st->sdp_ttl,
  1737. rt->rtsp_flags & RTSP_FLAG_FILTER_SRC ? 1 : 0);
  1738. if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
  1739. &s->interrupt_callback, NULL) < 0) {
  1740. err = AVERROR_INVALIDDATA;
  1741. goto fail;
  1742. }
  1743. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1744. goto fail;
  1745. }
  1746. return 0;
  1747. fail:
  1748. ff_rtsp_close_streams(s);
  1749. ff_network_close();
  1750. return err;
  1751. }
  1752. static int sdp_read_close(AVFormatContext *s)
  1753. {
  1754. ff_rtsp_close_streams(s);
  1755. ff_network_close();
  1756. return 0;
  1757. }
  1758. static const AVClass sdp_demuxer_class = {
  1759. .class_name = "SDP demuxer",
  1760. .item_name = av_default_item_name,
  1761. .option = sdp_options,
  1762. .version = LIBAVUTIL_VERSION_INT,
  1763. };
  1764. AVInputFormat ff_sdp_demuxer = {
  1765. .name = "sdp",
  1766. .long_name = NULL_IF_CONFIG_SMALL("SDP"),
  1767. .priv_data_size = sizeof(RTSPState),
  1768. .read_probe = sdp_probe,
  1769. .read_header = sdp_read_header,
  1770. .read_packet = ff_rtsp_fetch_packet,
  1771. .read_close = sdp_read_close,
  1772. .priv_class = &sdp_demuxer_class,
  1773. };
  1774. #endif /* CONFIG_SDP_DEMUXER */
  1775. #if CONFIG_RTP_DEMUXER
  1776. static int rtp_probe(AVProbeData *p)
  1777. {
  1778. if (av_strstart(p->filename, "rtp:", NULL))
  1779. return AVPROBE_SCORE_MAX;
  1780. return 0;
  1781. }
  1782. static int rtp_read_header(AVFormatContext *s)
  1783. {
  1784. uint8_t recvbuf[1500];
  1785. char host[500], sdp[500];
  1786. int ret, port;
  1787. URLContext* in = NULL;
  1788. int payload_type;
  1789. AVCodecContext codec = { 0 };
  1790. struct sockaddr_storage addr;
  1791. AVIOContext pb;
  1792. socklen_t addrlen = sizeof(addr);
  1793. RTSPState *rt = s->priv_data;
  1794. if (!ff_network_init())
  1795. return AVERROR(EIO);
  1796. ret = ffurl_open(&in, s->filename, AVIO_FLAG_READ,
  1797. &s->interrupt_callback, NULL);
  1798. if (ret)
  1799. goto fail;
  1800. while (1) {
  1801. ret = ffurl_read(in, recvbuf, sizeof(recvbuf));
  1802. if (ret == AVERROR(EAGAIN))
  1803. continue;
  1804. if (ret < 0)
  1805. goto fail;
  1806. if (ret < 12) {
  1807. av_log(s, AV_LOG_WARNING, "Received too short packet\n");
  1808. continue;
  1809. }
  1810. if ((recvbuf[0] & 0xc0) != 0x80) {
  1811. av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
  1812. "received\n");
  1813. continue;
  1814. }
  1815. if (RTP_PT_IS_RTCP(recvbuf[1]))
  1816. continue;
  1817. payload_type = recvbuf[1] & 0x7f;
  1818. break;
  1819. }
  1820. getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
  1821. ffurl_close(in);
  1822. in = NULL;
  1823. if (ff_rtp_get_codec_info(&codec, payload_type)) {
  1824. av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
  1825. "without an SDP file describing it\n",
  1826. payload_type);
  1827. goto fail;
  1828. }
  1829. if (codec.codec_type != AVMEDIA_TYPE_DATA) {
  1830. av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
  1831. "properly you need an SDP file "
  1832. "describing it\n");
  1833. }
  1834. av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
  1835. NULL, 0, s->filename);
  1836. snprintf(sdp, sizeof(sdp),
  1837. "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
  1838. addr.ss_family == AF_INET ? 4 : 6, host,
  1839. codec.codec_type == AVMEDIA_TYPE_DATA ? "application" :
  1840. codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
  1841. port, payload_type);
  1842. av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
  1843. ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
  1844. s->pb = &pb;
  1845. /* sdp_read_header initializes this again */
  1846. ff_network_close();
  1847. rt->media_type_mask = (1 << (AVMEDIA_TYPE_DATA+1)) - 1;
  1848. ret = sdp_read_header(s);
  1849. s->pb = NULL;
  1850. return ret;
  1851. fail:
  1852. if (in)
  1853. ffurl_close(in);
  1854. ff_network_close();
  1855. return ret;
  1856. }
  1857. static const AVClass rtp_demuxer_class = {
  1858. .class_name = "RTP demuxer",
  1859. .item_name = av_default_item_name,
  1860. .option = rtp_options,
  1861. .version = LIBAVUTIL_VERSION_INT,
  1862. };
  1863. AVInputFormat ff_rtp_demuxer = {
  1864. .name = "rtp",
  1865. .long_name = NULL_IF_CONFIG_SMALL("RTP input format"),
  1866. .priv_data_size = sizeof(RTSPState),
  1867. .read_probe = rtp_probe,
  1868. .read_header = rtp_read_header,
  1869. .read_packet = ff_rtsp_fetch_packet,
  1870. .read_close = sdp_read_close,
  1871. .flags = AVFMT_NOFILE,
  1872. .priv_class = &rtp_demuxer_class,
  1873. };
  1874. #endif /* CONFIG_RTP_DEMUXER */