]> git.sesse.net Git - ffmpeg/blob - libavformat/rtspdec.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavformat / rtspdec.c
1 /*
2  * RTSP demuxer
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
22 #include "libavutil/avstring.h"
23 #include "libavutil/intreadwrite.h"
24 #include "libavutil/mathematics.h"
25 #include "libavutil/random_seed.h"
26 #include "avformat.h"
27
28 #include "internal.h"
29 #include "network.h"
30 #include "os_support.h"
31 #include "rtsp.h"
32 #include "rdt.h"
33 #include "url.h"
34
35 static const struct RTSPStatusMessage {
36     enum RTSPStatusCode code;
37     const char *message;
38 } status_messages[] = {
39     { RTSP_STATUS_OK,             "OK"                               },
40     { RTSP_STATUS_METHOD,         "Method Not Allowed"               },
41     { RTSP_STATUS_BANDWIDTH,      "Not Enough Bandwidth"             },
42     { RTSP_STATUS_SESSION,        "Session Not Found"                },
43     { RTSP_STATUS_STATE,          "Method Not Valid in This State"   },
44     { RTSP_STATUS_AGGREGATE,      "Aggregate operation not allowed"  },
45     { RTSP_STATUS_ONLY_AGGREGATE, "Only aggregate operation allowed" },
46     { RTSP_STATUS_TRANSPORT,      "Unsupported transport"            },
47     { RTSP_STATUS_INTERNAL,       "Internal Server Error"            },
48     { RTSP_STATUS_SERVICE,        "Service Unavailable"              },
49     { RTSP_STATUS_VERSION,        "RTSP Version not supported"       },
50     { 0,                          "NULL"                             }
51 };
52
53 static int rtsp_read_close(AVFormatContext *s)
54 {
55     RTSPState *rt = s->priv_data;
56
57     if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN))
58         ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
59
60     ff_rtsp_close_streams(s);
61     ff_rtsp_close_connections(s);
62     ff_network_close();
63     rt->real_setup = NULL;
64     av_freep(&rt->real_setup_cache);
65     return 0;
66 }
67
68 static inline int read_line(AVFormatContext *s, char *rbuf, const int rbufsize,
69                             int *rbuflen)
70 {
71     RTSPState *rt = s->priv_data;
72     int idx       = 0;
73     int ret       = 0;
74     *rbuflen      = 0;
75
76     do {
77         ret = ffurl_read_complete(rt->rtsp_hd, rbuf + idx, 1);
78         if (ret < 0)
79             return ret;
80         if (rbuf[idx] == '\r') {
81             /* Ignore */
82         } else if (rbuf[idx] == '\n') {
83             rbuf[idx] = '\0';
84             *rbuflen  = idx;
85             return 0;
86         } else
87             idx++;
88     } while (idx < rbufsize);
89     av_log(s, AV_LOG_ERROR, "Message too long\n");
90     return AVERROR(EIO);
91 }
92
93 static int rtsp_send_reply(AVFormatContext *s, enum RTSPStatusCode code,
94                            const char *extracontent, uint16_t seq)
95 {
96     RTSPState *rt = s->priv_data;
97     char message[4096];
98     int index = 0;
99     while (status_messages[index].code) {
100         if (status_messages[index].code == code) {
101             snprintf(message, sizeof(message), "RTSP/1.0 %d %s\r\n",
102                      code, status_messages[index].message);
103             break;
104         }
105         index++;
106     }
107     if (!status_messages[index].code)
108         return AVERROR(EINVAL);
109     av_strlcatf(message, sizeof(message), "CSeq: %d\r\n", seq);
110     av_strlcatf(message, sizeof(message), "Server: %s\r\n", LIBAVFORMAT_IDENT);
111     if (extracontent)
112         av_strlcat(message, extracontent, sizeof(message));
113     av_strlcat(message, "\r\n", sizeof(message));
114     av_dlog(s, "Sending response:\n%s", message);
115     ffurl_write(rt->rtsp_hd, message, strlen(message));
116
117     return 0;
118 }
119
120 static inline int check_sessionid(AVFormatContext *s,
121                                   RTSPMessageHeader *request)
122 {
123     RTSPState *rt = s->priv_data;
124     unsigned char *session_id = rt->session_id;
125     if (!session_id[0]) {
126         av_log(s, AV_LOG_WARNING, "There is no session-id at the moment\n");
127         return 0;
128     }
129     if (strcmp(session_id, request->session_id)) {
130         av_log(s, AV_LOG_ERROR, "Unexpected session-id %s\n",
131                request->session_id);
132         rtsp_send_reply(s, RTSP_STATUS_SESSION, NULL, request->seq);
133         return AVERROR_STREAM_NOT_FOUND;
134     }
135     return 0;
136 }
137
138 static inline int rtsp_read_request(AVFormatContext *s,
139                                     RTSPMessageHeader *request,
140                                     const char *method)
141 {
142     RTSPState *rt = s->priv_data;
143     char rbuf[1024];
144     int rbuflen, ret;
145     do {
146         ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
147         if (ret)
148             return ret;
149         if (rbuflen > 1) {
150             av_dlog(s, "Parsing[%d]: %s\n", rbuflen, rbuf);
151             ff_rtsp_parse_line(request, rbuf, rt, method);
152         }
153     } while (rbuflen > 0);
154     if (request->seq != rt->seq + 1) {
155         av_log(s, AV_LOG_ERROR, "Unexpected Sequence number %d\n",
156                request->seq);
157         return AVERROR(EINVAL);
158     }
159     if (rt->session_id[0] && strcmp(method, "OPTIONS")) {
160         ret = check_sessionid(s, request);
161         if (ret)
162             return ret;
163     }
164
165     return 0;
166 }
167
168 static int rtsp_read_announce(AVFormatContext *s)
169 {
170     RTSPState *rt             = s->priv_data;
171     RTSPMessageHeader request = { 0 };
172     char sdp[4096];
173     int  ret;
174
175     ret = rtsp_read_request(s, &request, "ANNOUNCE");
176     if (ret)
177         return ret;
178     rt->seq++;
179     if (strcmp(request.content_type, "application/sdp")) {
180         av_log(s, AV_LOG_ERROR, "Unexpected content type %s\n",
181                request.content_type);
182         rtsp_send_reply(s, RTSP_STATUS_SERVICE, NULL, request.seq);
183         return AVERROR_OPTION_NOT_FOUND;
184     }
185     if (request.content_length && request.content_length < sizeof(sdp) - 1) {
186         /* Read SDP */
187         if (ffurl_read_complete(rt->rtsp_hd, sdp, request.content_length)
188             < request.content_length) {
189             av_log(s, AV_LOG_ERROR,
190                    "Unable to get complete SDP Description in ANNOUNCE\n");
191             rtsp_send_reply(s, RTSP_STATUS_INTERNAL, NULL, request.seq);
192             return AVERROR(EIO);
193         }
194         sdp[request.content_length] = '\0';
195         av_log(s, AV_LOG_VERBOSE, "SDP: %s\n", sdp);
196         ret = ff_sdp_parse(s, sdp);
197         if (ret)
198             return ret;
199         rtsp_send_reply(s, RTSP_STATUS_OK, NULL, request.seq);
200         return 0;
201     }
202     av_log(s, AV_LOG_ERROR,
203            "Content-Length header value exceeds sdp allocated buffer (4KB)\n");
204     rtsp_send_reply(s, RTSP_STATUS_INTERNAL,
205                     "Content-Length exceeds buffer size", request.seq);
206     return AVERROR(EIO);
207 }
208
209 static int rtsp_read_options(AVFormatContext *s)
210 {
211     RTSPState *rt             = s->priv_data;
212     RTSPMessageHeader request = { 0 };
213     int ret                   = 0;
214
215     /* Parsing headers */
216     ret = rtsp_read_request(s, &request, "OPTIONS");
217     if (ret)
218         return ret;
219     rt->seq++;
220     /* Send Reply */
221     rtsp_send_reply(s, RTSP_STATUS_OK,
222                     "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, RECORD\r\n",
223                     request.seq);
224     return 0;
225 }
226
227 static int rtsp_read_setup(AVFormatContext *s, char* host, char *controlurl)
228 {
229     RTSPState *rt             = s->priv_data;
230     RTSPMessageHeader request = { 0 };
231     int ret                   = 0;
232     char url[1024];
233     RTSPStream *rtsp_st;
234     char responseheaders[1024];
235     int localport    = -1;
236     int transportidx = 0;
237     int streamid     = 0;
238
239     ret = rtsp_read_request(s, &request, "SETUP");
240     if (ret)
241         return ret;
242     rt->seq++;
243     if (!request.nb_transports) {
244         av_log(s, AV_LOG_ERROR, "No transport defined in SETUP\n");
245         return AVERROR_INVALIDDATA;
246     }
247     for (transportidx = 0; transportidx < request.nb_transports;
248          transportidx++) {
249         if (!request.transports[transportidx].mode_record ||
250             (request.transports[transportidx].lower_transport !=
251              RTSP_LOWER_TRANSPORT_UDP &&
252              request.transports[transportidx].lower_transport !=
253              RTSP_LOWER_TRANSPORT_TCP)) {
254             av_log(s, AV_LOG_ERROR, "mode=record/receive not set or transport"
255                    " protocol not supported (yet)\n");
256             return AVERROR_INVALIDDATA;
257         }
258     }
259     if (request.nb_transports > 1)
260         av_log(s, AV_LOG_WARNING, "More than one transport not supported, "
261                "using first of all\n");
262     for (streamid = 0; streamid < rt->nb_rtsp_streams; streamid++) {
263         if (!strcmp(rt->rtsp_streams[streamid]->control_url,
264                     controlurl))
265             break;
266     }
267     if (streamid == rt->nb_rtsp_streams) {
268         av_log(s, AV_LOG_ERROR, "Unable to find requested track\n");
269         return AVERROR_STREAM_NOT_FOUND;
270     }
271     rtsp_st   = rt->rtsp_streams[streamid];
272     localport = rt->rtp_port_min;
273
274     if (request.transports[0].lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
275         rt->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
276         if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) {
277             rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
278             return ret;
279         }
280         rtsp_st->interleaved_min = request.transports[0].interleaved_min;
281         rtsp_st->interleaved_max = request.transports[0].interleaved_max;
282         snprintf(responseheaders, sizeof(responseheaders), "Transport: "
283                  "RTP/AVP/TCP;unicast;mode=receive;interleaved=%d-%d"
284                  "\r\n", request.transports[0].interleaved_min,
285                  request.transports[0].interleaved_max);
286     } else {
287         do {
288             ff_url_join(url, sizeof(url), "rtp", NULL, host, localport, NULL);
289             av_dlog(s, "Opening: %s", url);
290             ret = ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
291                              &s->interrupt_callback, NULL);
292             if (ret)
293                 localport += 2;
294         } while (ret || localport > rt->rtp_port_max);
295         if (localport > rt->rtp_port_max) {
296             rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
297             return ret;
298         }
299
300         av_dlog(s, "Listening on: %d",
301                 ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle));
302         if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) {
303             rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
304             return ret;
305         }
306
307         localport = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
308         snprintf(responseheaders, sizeof(responseheaders), "Transport: "
309                  "RTP/AVP/UDP;unicast;mode=receive;source=%s;"
310                  "client_port=%d-%d;server_port=%d-%d\r\n",
311                  host, request.transports[0].client_port_min,
312                  request.transports[0].client_port_max, localport,
313                  localport + 1);
314     }
315
316     /* Establish sessionid if not previously set */
317     /* Put this in a function? */
318     /* RFC 2326: session id must be at least 8 digits */
319     while (strlen(rt->session_id) < 8)
320         av_strlcatf(rt->session_id, 512, "%u", av_get_random_seed());
321
322     av_strlcatf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
323                 rt->session_id);
324     /* Send Reply */
325     rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
326
327     rt->state = RTSP_STATE_PAUSED;
328     return 0;
329 }
330
331 static int rtsp_read_record(AVFormatContext *s)
332 {
333     RTSPState *rt             = s->priv_data;
334     RTSPMessageHeader request = { 0 };
335     int ret                   = 0;
336     char responseheaders[1024];
337
338     ret = rtsp_read_request(s, &request, "RECORD");
339     if (ret)
340         return ret;
341     ret = check_sessionid(s, &request);
342     if (ret)
343         return ret;
344     rt->seq++;
345     snprintf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
346              rt->session_id);
347     rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
348
349     rt->state = RTSP_STATE_STREAMING;
350     return 0;
351 }
352
353 static inline int parse_command_line(AVFormatContext *s, const char *line,
354                                      int linelen, char *uri, int urisize,
355                                      char *method, int methodsize,
356                                      enum RTSPMethod *methodcode)
357 {
358     RTSPState *rt = s->priv_data;
359     const char *linept, *searchlinept;
360     linept = strchr(line, ' ');
361     if (linept - line > methodsize - 1) {
362         av_log(s, AV_LOG_ERROR, "Method string too long\n");
363         return AVERROR(EIO);
364     }
365     memcpy(method, line, linept - line);
366     method[linept - line] = '\0';
367     linept++;
368     if (!strcmp(method, "ANNOUNCE"))
369         *methodcode = ANNOUNCE;
370     else if (!strcmp(method, "OPTIONS"))
371         *methodcode = OPTIONS;
372     else if (!strcmp(method, "RECORD"))
373         *methodcode = RECORD;
374     else if (!strcmp(method, "SETUP"))
375         *methodcode = SETUP;
376     else if (!strcmp(method, "PAUSE"))
377         *methodcode = PAUSE;
378     else if (!strcmp(method, "TEARDOWN"))
379         *methodcode = TEARDOWN;
380     else
381         *methodcode = UNKNOWN;
382     /* Check method with the state  */
383     if (rt->state == RTSP_STATE_IDLE) {
384         if ((*methodcode != ANNOUNCE) && (*methodcode != OPTIONS)) {
385             av_log(s, AV_LOG_ERROR, "Unexpected command in Idle State %s\n",
386                    line);
387             return AVERROR_PROTOCOL_NOT_FOUND;
388         }
389     } else if (rt->state == RTSP_STATE_PAUSED) {
390         if ((*methodcode != OPTIONS) && (*methodcode != RECORD)
391             && (*methodcode != SETUP)) {
392             av_log(s, AV_LOG_ERROR, "Unexpected command in Paused State %s\n",
393                    line);
394             return AVERROR_PROTOCOL_NOT_FOUND;
395         }
396     } else if (rt->state == RTSP_STATE_STREAMING) {
397         if ((*methodcode != PAUSE) && (*methodcode != OPTIONS)
398             && (*methodcode != TEARDOWN)) {
399             av_log(s, AV_LOG_ERROR, "Unexpected command in Streaming State"
400                    " %s\n", line);
401             return AVERROR_PROTOCOL_NOT_FOUND;
402         }
403     } else {
404         av_log(s, AV_LOG_ERROR, "Unexpected State [%d]\n", rt->state);
405         return AVERROR_BUG;
406     }
407
408     searchlinept = strchr(linept, ' ');
409     if (searchlinept == NULL) {
410         av_log(s, AV_LOG_ERROR, "Error parsing message URI\n");
411         return AVERROR_INVALIDDATA;
412     }
413     if (searchlinept - linept > urisize - 1) {
414         av_log(s, AV_LOG_ERROR, "uri string length exceeded buffer size\n");
415         return AVERROR(EIO);
416     }
417     memcpy(uri, linept, searchlinept - linept);
418     uri[searchlinept - linept] = '\0';
419     if (strcmp(rt->control_uri, uri)) {
420         char host[128], path[512], auth[128];
421         int port;
422         char ctl_host[128], ctl_path[512], ctl_auth[128];
423         int ctl_port;
424         av_url_split(NULL, 0, auth, sizeof(auth), host, sizeof(host), &port,
425                      path, sizeof(path), uri);
426         av_url_split(NULL, 0, ctl_auth, sizeof(ctl_auth), ctl_host,
427                      sizeof(ctl_host), &ctl_port, ctl_path, sizeof(ctl_path),
428                      rt->control_uri);
429         if (strcmp(host, ctl_host))
430             av_log(s, AV_LOG_INFO, "Host %s differs from expected %s\n",
431                    host, ctl_host);
432         if (strcmp(path, ctl_path) && *methodcode != SETUP)
433             av_log(s, AV_LOG_WARNING, "WARNING: Path %s differs from expected"
434                    " %s\n", path, ctl_path);
435         if (*methodcode == ANNOUNCE) {
436             av_log(s, AV_LOG_INFO,
437                    "Updating control URI to %s\n", uri);
438             strcpy(rt->control_uri, uri);
439         }
440     }
441
442     linept = searchlinept + 1;
443     if (!av_strstart(linept, "RTSP/1.0", NULL)) {
444         av_log(s, AV_LOG_ERROR, "Error parsing protocol or version\n");
445         return AVERROR_PROTOCOL_NOT_FOUND;
446     }
447     return 0;
448 }
449
450 int ff_rtsp_parse_streaming_commands(AVFormatContext *s)
451 {
452     RTSPState *rt = s->priv_data;
453     unsigned char rbuf[4096];
454     unsigned char method[10];
455     char uri[500];
456     int ret;
457     int rbuflen               = 0;
458     RTSPMessageHeader request = { 0 };
459     enum RTSPMethod methodcode;
460
461     ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
462     if (ret < 0)
463         return ret;
464     ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
465                              sizeof(method), &methodcode);
466     if (ret) {
467         av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
468         return ret;
469     }
470
471     ret = rtsp_read_request(s, &request, method);
472     if (ret)
473         return ret;
474     rt->seq++;
475     if (methodcode == PAUSE) {
476         rt->state = RTSP_STATE_PAUSED;
477         ret       = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
478         // TODO: Missing date header in response
479     } else if (methodcode == OPTIONS) {
480         ret = rtsp_send_reply(s, RTSP_STATUS_OK,
481                               "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, "
482                               "RECORD\r\n", request.seq);
483     } else if (methodcode == TEARDOWN) {
484         rt->state = RTSP_STATE_IDLE;
485         ret       = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
486         return 0;
487     }
488     return ret;
489 }
490
491 static int rtsp_read_play(AVFormatContext *s)
492 {
493     RTSPState *rt = s->priv_data;
494     RTSPMessageHeader reply1, *reply = &reply1;
495     int i;
496     char cmd[1024];
497
498     av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
499     rt->nb_byes = 0;
500
501     if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
502         if (rt->transport == RTSP_TRANSPORT_RTP) {
503             for (i = 0; i < rt->nb_rtsp_streams; i++) {
504                 RTSPStream *rtsp_st = rt->rtsp_streams[i];
505                 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
506                 if (!rtpctx)
507                     continue;
508                 ff_rtp_reset_packet_queue(rtpctx);
509                 rtpctx->last_rtcp_ntp_time  = AV_NOPTS_VALUE;
510                 rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
511                 rtpctx->base_timestamp      = 0;
512                 rtpctx->timestamp           = 0;
513                 rtpctx->unwrapped_timestamp = 0;
514                 rtpctx->rtcp_ts_offset      = 0;
515             }
516         }
517         if (rt->state == RTSP_STATE_PAUSED) {
518             cmd[0] = 0;
519         } else {
520             snprintf(cmd, sizeof(cmd),
521                      "Range: npt=%"PRId64".%03"PRId64"-\r\n",
522                      rt->seek_timestamp / AV_TIME_BASE,
523                      rt->seek_timestamp / (AV_TIME_BASE / 1000) % 1000);
524         }
525         ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
526         if (reply->status_code != RTSP_STATUS_OK) {
527             return -1;
528         }
529         if (rt->transport == RTSP_TRANSPORT_RTP &&
530             reply->range_start != AV_NOPTS_VALUE) {
531             for (i = 0; i < rt->nb_rtsp_streams; i++) {
532                 RTSPStream *rtsp_st = rt->rtsp_streams[i];
533                 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
534                 AVStream *st = NULL;
535                 if (!rtpctx || rtsp_st->stream_index < 0)
536                     continue;
537                 st = s->streams[rtsp_st->stream_index];
538                 rtpctx->range_start_offset =
539                     av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
540                                  st->time_base);
541             }
542         }
543     }
544     rt->state = RTSP_STATE_STREAMING;
545     return 0;
546 }
547
548 /* pause the stream */
549 static int rtsp_read_pause(AVFormatContext *s)
550 {
551     RTSPState *rt = s->priv_data;
552     RTSPMessageHeader reply1, *reply = &reply1;
553
554     if (rt->state != RTSP_STATE_STREAMING)
555         return 0;
556     else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
557         ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
558         if (reply->status_code != RTSP_STATUS_OK) {
559             return -1;
560         }
561     }
562     rt->state = RTSP_STATE_PAUSED;
563     return 0;
564 }
565
566 int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
567 {
568     RTSPState *rt = s->priv_data;
569     char cmd[1024];
570     unsigned char *content = NULL;
571     int ret;
572
573     /* describe the stream */
574     snprintf(cmd, sizeof(cmd),
575              "Accept: application/sdp\r\n");
576     if (rt->server_type == RTSP_SERVER_REAL) {
577         /**
578          * The Require: attribute is needed for proper streaming from
579          * Realmedia servers.
580          */
581         av_strlcat(cmd,
582                    "Require: com.real.retain-entity-for-setup\r\n",
583                    sizeof(cmd));
584     }
585     ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
586     if (!content)
587         return AVERROR_INVALIDDATA;
588     if (reply->status_code != RTSP_STATUS_OK) {
589         av_freep(&content);
590         return AVERROR_INVALIDDATA;
591     }
592
593     av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
594     /* now we got the SDP description, we parse it */
595     ret = ff_sdp_parse(s, (const char *)content);
596     av_freep(&content);
597     if (ret < 0)
598         return ret;
599
600     return 0;
601 }
602
603 static int rtsp_listen(AVFormatContext *s)
604 {
605     RTSPState *rt = s->priv_data;
606     char host[128], path[512], auth[128];
607     char uri[500];
608     int port;
609     char tcpname[500];
610     unsigned char rbuf[4096];
611     unsigned char method[10];
612     int rbuflen = 0;
613     int ret;
614     enum RTSPMethod methodcode;
615
616     /* extract hostname and port */
617     av_url_split(NULL, 0, auth, sizeof(auth), host, sizeof(host), &port,
618                  path, sizeof(path), s->filename);
619
620     /* ff_url_join. No authorization by now (NULL) */
621     ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL, host,
622                 port, "%s", path);
623     /* Create TCP connection */
624     ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port,
625                 "?listen&listen_timeout=%d", rt->initial_timeout * 1000);
626
627     if (ret = ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
628                          &s->interrupt_callback, NULL)) {
629         av_log(s, AV_LOG_ERROR, "Unable to open RTSP for listening\n");
630         return ret;
631     }
632     rt->state       = RTSP_STATE_IDLE;
633     rt->rtsp_hd_out = rt->rtsp_hd;
634     for (;;) { /* Wait for incoming RTSP messages */
635         ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
636         if (ret < 0)
637             return ret;
638         ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
639                                  sizeof(method), &methodcode);
640         if (ret) {
641             av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
642             return ret;
643         }
644
645         if (methodcode == ANNOUNCE) {
646             ret       = rtsp_read_announce(s);
647             rt->state = RTSP_STATE_PAUSED;
648         } else if (methodcode == OPTIONS) {
649             ret = rtsp_read_options(s);
650         } else if (methodcode == RECORD) {
651             ret = rtsp_read_record(s);
652             if (!ret)
653                 return 0; // We are ready for streaming
654         } else if (methodcode == SETUP)
655             ret = rtsp_read_setup(s, host, uri);
656         if (ret) {
657             ffurl_close(rt->rtsp_hd);
658             return AVERROR_INVALIDDATA;
659         }
660     }
661     return 0;
662 }
663
664 static int rtsp_probe(AVProbeData *p)
665 {
666     if (av_strstart(p->filename, "rtsp:", NULL))
667         return AVPROBE_SCORE_MAX;
668     return 0;
669 }
670
671 static int rtsp_read_header(AVFormatContext *s)
672 {
673     RTSPState *rt = s->priv_data;
674     int ret;
675
676     if (rt->initial_timeout > 0)
677         rt->rtsp_flags |= RTSP_FLAG_LISTEN;
678
679     if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
680         ret = rtsp_listen(s);
681         if (ret)
682             return ret;
683     } else {
684         ret = ff_rtsp_connect(s);
685         if (ret)
686             return ret;
687
688         rt->real_setup_cache = !s->nb_streams ? NULL :
689             av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
690         if (!rt->real_setup_cache && s->nb_streams)
691             return AVERROR(ENOMEM);
692         rt->real_setup = rt->real_setup_cache + s->nb_streams;
693
694         if (rt->initial_pause) {
695             /* do not start immediately */
696         } else {
697             if (rtsp_read_play(s) < 0) {
698                 ff_rtsp_close_streams(s);
699                 ff_rtsp_close_connections(s);
700                 return AVERROR_INVALIDDATA;
701             }
702         }
703     }
704
705     return 0;
706 }
707
708 int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
709                             uint8_t *buf, int buf_size)
710 {
711     RTSPState *rt = s->priv_data;
712     int id, len, i, ret;
713     RTSPStream *rtsp_st;
714
715     av_dlog(s, "tcp_read_packet:\n");
716 redo:
717     for (;;) {
718         RTSPMessageHeader reply;
719
720         ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
721         if (ret < 0)
722             return ret;
723         if (ret == 1) /* received '$' */
724             break;
725         /* XXX: parse message */
726         if (rt->state != RTSP_STATE_STREAMING)
727             return 0;
728     }
729     ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
730     if (ret != 3)
731         return -1;
732     id  = buf[0];
733     len = AV_RB16(buf + 1);
734     av_dlog(s, "id=%d len=%d\n", id, len);
735     if (len > buf_size || len < 8)
736         goto redo;
737     /* get the data */
738     ret = ffurl_read_complete(rt->rtsp_hd, buf, len);
739     if (ret != len)
740         return -1;
741     if (rt->transport == RTSP_TRANSPORT_RDT &&
742         ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
743         return -1;
744
745     /* find the matching stream */
746     for (i = 0; i < rt->nb_rtsp_streams; i++) {
747         rtsp_st = rt->rtsp_streams[i];
748         if (id >= rtsp_st->interleaved_min &&
749             id <= rtsp_st->interleaved_max)
750             goto found;
751     }
752     goto redo;
753 found:
754     *prtsp_st = rtsp_st;
755     return len;
756 }
757
758 static int resetup_tcp(AVFormatContext *s)
759 {
760     RTSPState *rt = s->priv_data;
761     char host[1024];
762     int port;
763
764     av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0,
765                  s->filename);
766     ff_rtsp_undo_setup(s);
767     return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP,
768                                       rt->real_challenge);
769 }
770
771 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
772 {
773     RTSPState *rt = s->priv_data;
774     int ret;
775     RTSPMessageHeader reply1, *reply = &reply1;
776     char cmd[1024];
777
778 retry:
779     if (rt->server_type == RTSP_SERVER_REAL) {
780         int i;
781
782         for (i = 0; i < s->nb_streams; i++)
783             rt->real_setup[i] = s->streams[i]->discard;
784
785         if (!rt->need_subscription) {
786             if (memcmp (rt->real_setup, rt->real_setup_cache,
787                         sizeof(enum AVDiscard) * s->nb_streams)) {
788                 snprintf(cmd, sizeof(cmd),
789                          "Unsubscribe: %s\r\n",
790                          rt->last_subscription);
791                 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
792                                  cmd, reply, NULL);
793                 if (reply->status_code != RTSP_STATUS_OK)
794                     return AVERROR_INVALIDDATA;
795                 rt->need_subscription = 1;
796             }
797         }
798
799         if (rt->need_subscription) {
800             int r, rule_nr, first = 1;
801
802             memcpy(rt->real_setup_cache, rt->real_setup,
803                    sizeof(enum AVDiscard) * s->nb_streams);
804             rt->last_subscription[0] = 0;
805
806             snprintf(cmd, sizeof(cmd),
807                      "Subscribe: ");
808             for (i = 0; i < rt->nb_rtsp_streams; i++) {
809                 rule_nr = 0;
810                 for (r = 0; r < s->nb_streams; r++) {
811                     if (s->streams[r]->id == i) {
812                         if (s->streams[r]->discard != AVDISCARD_ALL) {
813                             if (!first)
814                                 av_strlcat(rt->last_subscription, ",",
815                                            sizeof(rt->last_subscription));
816                             ff_rdt_subscribe_rule(
817                                 rt->last_subscription,
818                                 sizeof(rt->last_subscription), i, rule_nr);
819                             first = 0;
820                         }
821                         rule_nr++;
822                     }
823                 }
824             }
825             av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
826             ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
827                              cmd, reply, NULL);
828             if (reply->status_code != RTSP_STATUS_OK)
829                 return AVERROR_INVALIDDATA;
830             rt->need_subscription = 0;
831
832             if (rt->state == RTSP_STATE_STREAMING)
833                 rtsp_read_play (s);
834         }
835     }
836
837     ret = ff_rtsp_fetch_packet(s, pkt);
838     if (ret < 0) {
839         if (ret == AVERROR(ETIMEDOUT) && !rt->packets) {
840             if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
841                 rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) {
842                 RTSPMessageHeader reply1, *reply = &reply1;
843                 av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n");
844                 if (rtsp_read_pause(s) != 0)
845                     return -1;
846                 // TEARDOWN is required on Real-RTSP, but might make
847                 // other servers close the connection.
848                 if (rt->server_type == RTSP_SERVER_REAL)
849                     ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL,
850                                      reply, NULL);
851                 rt->session_id[0] = '\0';
852                 if (resetup_tcp(s) == 0) {
853                     rt->state = RTSP_STATE_IDLE;
854                     rt->need_subscription = 1;
855                     if (rtsp_read_play(s) != 0)
856                         return -1;
857                     goto retry;
858                 }
859             }
860         }
861         return ret;
862     }
863     rt->packets++;
864
865     if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN)) {
866         /* send dummy request to keep TCP connection alive */
867         if ((av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2 ||
868             rt->auth_state.stale) {
869             if (rt->server_type == RTSP_SERVER_WMS ||
870                 (rt->server_type != RTSP_SERVER_REAL &&
871                  rt->get_parameter_supported)) {
872                 ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
873             } else {
874                 ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
875             }
876             /* The stale flag should be reset when creating the auth response in
877              * ff_rtsp_send_cmd_async, but reset it here just in case we never
878              * called the auth code (if we didn't have any credentials set). */
879             rt->auth_state.stale = 0;
880         }
881     }
882
883     return 0;
884 }
885
886 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
887                           int64_t timestamp, int flags)
888 {
889     RTSPState *rt = s->priv_data;
890
891     rt->seek_timestamp = av_rescale_q(timestamp,
892                                       s->streams[stream_index]->time_base,
893                                       AV_TIME_BASE_Q);
894     switch(rt->state) {
895     default:
896     case RTSP_STATE_IDLE:
897         break;
898     case RTSP_STATE_STREAMING:
899         if (rtsp_read_pause(s) != 0)
900             return -1;
901         rt->state = RTSP_STATE_SEEKING;
902         if (rtsp_read_play(s) != 0)
903             return -1;
904         break;
905     case RTSP_STATE_PAUSED:
906         rt->state = RTSP_STATE_IDLE;
907         break;
908     }
909     return 0;
910 }
911
912 static const AVClass rtsp_demuxer_class = {
913     .class_name     = "RTSP demuxer",
914     .item_name      = av_default_item_name,
915     .option         = ff_rtsp_options,
916     .version        = LIBAVUTIL_VERSION_INT,
917 };
918
919 AVInputFormat ff_rtsp_demuxer = {
920     .name           = "rtsp",
921     .long_name      = NULL_IF_CONFIG_SMALL("RTSP input format"),
922     .priv_data_size = sizeof(RTSPState),
923     .read_probe     = rtsp_probe,
924     .read_header    = rtsp_read_header,
925     .read_packet    = rtsp_read_packet,
926     .read_close     = rtsp_read_close,
927     .read_seek      = rtsp_read_seek,
928     .flags          = AVFMT_NOFILE,
929     .read_play      = rtsp_read_play,
930     .read_pause     = rtsp_read_pause,
931     .priv_class     = &rtsp_demuxer_class,
932 };