rtsp.c 67 KB

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