rtsp.c 67 KB

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