rtsp.c 67 KB

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