rtsp: Move rtsp_read_close
[ffmpeg.git] / libavformat / rtspdec.c
1 /*
2  * RTSP demuxer
3  * Copyright (c) 2002 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavutil/avstring.h"
23 #include "libavutil/intreadwrite.h"
24 #include "libavutil/mathematics.h"
25 #include "avformat.h"
26
27 #include "internal.h"
28 #include "network.h"
29 #include "os_support.h"
30 #include "rtsp.h"
31 #include "rdt.h"
32 #include "url.h"
33
34 static int rtsp_read_close(AVFormatContext *s)
35 {
36     RTSPState *rt = s->priv_data;
37
38     ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
39
40     ff_rtsp_close_streams(s);
41     ff_rtsp_close_connections(s);
42     ff_network_close();
43     rt->real_setup = NULL;
44     av_freep(&rt->real_setup_cache);
45     return 0;
46 }
47
48 static int rtsp_read_play(AVFormatContext *s)
49 {
50     RTSPState *rt = s->priv_data;
51     RTSPMessageHeader reply1, *reply = &reply1;
52     int i;
53     char cmd[1024];
54
55     av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
56     rt->nb_byes = 0;
57
58     if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
59         if (rt->transport == RTSP_TRANSPORT_RTP) {
60             for (i = 0; i < rt->nb_rtsp_streams; i++) {
61                 RTSPStream *rtsp_st = rt->rtsp_streams[i];
62                 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
63                 if (!rtpctx)
64                     continue;
65                 ff_rtp_reset_packet_queue(rtpctx);
66                 rtpctx->last_rtcp_ntp_time  = AV_NOPTS_VALUE;
67                 rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
68                 rtpctx->base_timestamp      = 0;
69                 rtpctx->timestamp           = 0;
70                 rtpctx->unwrapped_timestamp = 0;
71                 rtpctx->rtcp_ts_offset      = 0;
72             }
73         }
74         if (rt->state == RTSP_STATE_PAUSED) {
75             cmd[0] = 0;
76         } else {
77             snprintf(cmd, sizeof(cmd),
78                      "Range: npt=%"PRId64".%03"PRId64"-\r\n",
79                      rt->seek_timestamp / AV_TIME_BASE,
80                      rt->seek_timestamp / (AV_TIME_BASE / 1000) % 1000);
81         }
82         ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
83         if (reply->status_code != RTSP_STATUS_OK) {
84             return -1;
85         }
86         if (rt->transport == RTSP_TRANSPORT_RTP &&
87             reply->range_start != AV_NOPTS_VALUE) {
88             for (i = 0; i < rt->nb_rtsp_streams; i++) {
89                 RTSPStream *rtsp_st = rt->rtsp_streams[i];
90                 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
91                 AVStream *st = NULL;
92                 if (!rtpctx || rtsp_st->stream_index < 0)
93                     continue;
94                 st = s->streams[rtsp_st->stream_index];
95                 rtpctx->range_start_offset =
96                     av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
97                                  st->time_base);
98             }
99         }
100     }
101     rt->state = RTSP_STATE_STREAMING;
102     return 0;
103 }
104
105 /* pause the stream */
106 static int rtsp_read_pause(AVFormatContext *s)
107 {
108     RTSPState *rt = s->priv_data;
109     RTSPMessageHeader reply1, *reply = &reply1;
110
111     if (rt->state != RTSP_STATE_STREAMING)
112         return 0;
113     else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
114         ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
115         if (reply->status_code != RTSP_STATUS_OK) {
116             return -1;
117         }
118     }
119     rt->state = RTSP_STATE_PAUSED;
120     return 0;
121 }
122
123 int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
124 {
125     RTSPState *rt = s->priv_data;
126     char cmd[1024];
127     unsigned char *content = NULL;
128     int ret;
129
130     /* describe the stream */
131     snprintf(cmd, sizeof(cmd),
132              "Accept: application/sdp\r\n");
133     if (rt->server_type == RTSP_SERVER_REAL) {
134         /**
135          * The Require: attribute is needed for proper streaming from
136          * Realmedia servers.
137          */
138         av_strlcat(cmd,
139                    "Require: com.real.retain-entity-for-setup\r\n",
140                    sizeof(cmd));
141     }
142     ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
143     if (!content)
144         return AVERROR_INVALIDDATA;
145     if (reply->status_code != RTSP_STATUS_OK) {
146         av_freep(&content);
147         return AVERROR_INVALIDDATA;
148     }
149
150     av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
151     /* now we got the SDP description, we parse it */
152     ret = ff_sdp_parse(s, (const char *)content);
153     av_freep(&content);
154     if (ret < 0)
155         return ret;
156
157     return 0;
158 }
159
160 static int rtsp_probe(AVProbeData *p)
161 {
162     if (av_strstart(p->filename, "rtsp:", NULL))
163         return AVPROBE_SCORE_MAX;
164     return 0;
165 }
166
167 static int rtsp_read_header(AVFormatContext *s)
168 {
169     RTSPState *rt = s->priv_data;
170     int ret;
171
172     ret = ff_rtsp_connect(s);
173     if (ret)
174         return ret;
175
176     rt->real_setup_cache = !s->nb_streams ? NULL :
177                            av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
178     if (!rt->real_setup_cache && s->nb_streams)
179         return AVERROR(ENOMEM);
180     rt->real_setup = rt->real_setup_cache + s->nb_streams;
181
182     if (rt->initial_pause) {
183          /* do not start immediately */
184     } else {
185          if (rtsp_read_play(s) < 0) {
186             ff_rtsp_close_streams(s);
187             ff_rtsp_close_connections(s);
188             return AVERROR_INVALIDDATA;
189         }
190     }
191
192     return 0;
193 }
194
195 int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
196                             uint8_t *buf, int buf_size)
197 {
198     RTSPState *rt = s->priv_data;
199     int id, len, i, ret;
200     RTSPStream *rtsp_st;
201
202     av_dlog(s, "tcp_read_packet:\n");
203 redo:
204     for (;;) {
205         RTSPMessageHeader reply;
206
207         ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
208         if (ret < 0)
209             return ret;
210         if (ret == 1) /* received '$' */
211             break;
212         /* XXX: parse message */
213         if (rt->state != RTSP_STATE_STREAMING)
214             return 0;
215     }
216     ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
217     if (ret != 3)
218         return -1;
219     id  = buf[0];
220     len = AV_RB16(buf + 1);
221     av_dlog(s, "id=%d len=%d\n", id, len);
222     if (len > buf_size || len < 12)
223         goto redo;
224     /* get the data */
225     ret = ffurl_read_complete(rt->rtsp_hd, buf, len);
226     if (ret != len)
227         return -1;
228     if (rt->transport == RTSP_TRANSPORT_RDT &&
229         ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
230         return -1;
231
232     /* find the matching stream */
233     for (i = 0; i < rt->nb_rtsp_streams; i++) {
234         rtsp_st = rt->rtsp_streams[i];
235         if (id >= rtsp_st->interleaved_min &&
236             id <= rtsp_st->interleaved_max)
237             goto found;
238     }
239     goto redo;
240 found:
241     *prtsp_st = rtsp_st;
242     return len;
243 }
244
245 static int resetup_tcp(AVFormatContext *s)
246 {
247     RTSPState *rt = s->priv_data;
248     char host[1024];
249     int port;
250
251     av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0,
252                  s->filename);
253     ff_rtsp_undo_setup(s);
254     return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP,
255                                       rt->real_challenge);
256 }
257
258 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
259 {
260     RTSPState *rt = s->priv_data;
261     int ret;
262     RTSPMessageHeader reply1, *reply = &reply1;
263     char cmd[1024];
264
265 retry:
266     if (rt->server_type == RTSP_SERVER_REAL) {
267         int i;
268
269         for (i = 0; i < s->nb_streams; i++)
270             rt->real_setup[i] = s->streams[i]->discard;
271
272         if (!rt->need_subscription) {
273             if (memcmp (rt->real_setup, rt->real_setup_cache,
274                         sizeof(enum AVDiscard) * s->nb_streams)) {
275                 snprintf(cmd, sizeof(cmd),
276                          "Unsubscribe: %s\r\n",
277                          rt->last_subscription);
278                 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
279                                  cmd, reply, NULL);
280                 if (reply->status_code != RTSP_STATUS_OK)
281                     return AVERROR_INVALIDDATA;
282                 rt->need_subscription = 1;
283             }
284         }
285
286         if (rt->need_subscription) {
287             int r, rule_nr, first = 1;
288
289             memcpy(rt->real_setup_cache, rt->real_setup,
290                    sizeof(enum AVDiscard) * s->nb_streams);
291             rt->last_subscription[0] = 0;
292
293             snprintf(cmd, sizeof(cmd),
294                      "Subscribe: ");
295             for (i = 0; i < rt->nb_rtsp_streams; i++) {
296                 rule_nr = 0;
297                 for (r = 0; r < s->nb_streams; r++) {
298                     if (s->streams[r]->id == i) {
299                         if (s->streams[r]->discard != AVDISCARD_ALL) {
300                             if (!first)
301                                 av_strlcat(rt->last_subscription, ",",
302                                            sizeof(rt->last_subscription));
303                             ff_rdt_subscribe_rule(
304                                 rt->last_subscription,
305                                 sizeof(rt->last_subscription), i, rule_nr);
306                             first = 0;
307                         }
308                         rule_nr++;
309                     }
310                 }
311             }
312             av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
313             ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
314                              cmd, reply, NULL);
315             if (reply->status_code != RTSP_STATUS_OK)
316                 return AVERROR_INVALIDDATA;
317             rt->need_subscription = 0;
318
319             if (rt->state == RTSP_STATE_STREAMING)
320                 rtsp_read_play (s);
321         }
322     }
323
324     ret = ff_rtsp_fetch_packet(s, pkt);
325     if (ret < 0) {
326         if (ret == AVERROR(ETIMEDOUT) && !rt->packets) {
327             if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
328                 rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) {
329                 RTSPMessageHeader reply1, *reply = &reply1;
330                 av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n");
331                 if (rtsp_read_pause(s) != 0)
332                     return -1;
333                 // TEARDOWN is required on Real-RTSP, but might make
334                 // other servers close the connection.
335                 if (rt->server_type == RTSP_SERVER_REAL)
336                     ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL,
337                                      reply, NULL);
338                 rt->session_id[0] = '\0';
339                 if (resetup_tcp(s) == 0) {
340                     rt->state = RTSP_STATE_IDLE;
341                     rt->need_subscription = 1;
342                     if (rtsp_read_play(s) != 0)
343                         return -1;
344                     goto retry;
345                 }
346             }
347         }
348         return ret;
349     }
350     rt->packets++;
351
352     /* send dummy request to keep TCP connection alive */
353     if ((av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2 ||
354          rt->auth_state.stale) {
355         if (rt->server_type == RTSP_SERVER_WMS ||
356            (rt->server_type != RTSP_SERVER_REAL &&
357             rt->get_parameter_supported)) {
358             ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
359         } else {
360             ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
361         }
362         /* The stale flag should be reset when creating the auth response in
363          * ff_rtsp_send_cmd_async, but reset it here just in case we never
364          * called the auth code (if we didn't have any credentials set). */
365         rt->auth_state.stale = 0;
366     }
367
368     return 0;
369 }
370
371 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
372                           int64_t timestamp, int flags)
373 {
374     RTSPState *rt = s->priv_data;
375
376     rt->seek_timestamp = av_rescale_q(timestamp,
377                                       s->streams[stream_index]->time_base,
378                                       AV_TIME_BASE_Q);
379     switch(rt->state) {
380     default:
381     case RTSP_STATE_IDLE:
382         break;
383     case RTSP_STATE_STREAMING:
384         if (rtsp_read_pause(s) != 0)
385             return -1;
386         rt->state = RTSP_STATE_SEEKING;
387         if (rtsp_read_play(s) != 0)
388             return -1;
389         break;
390     case RTSP_STATE_PAUSED:
391         rt->state = RTSP_STATE_IDLE;
392         break;
393     }
394     return 0;
395 }
396
397 static const AVClass rtsp_demuxer_class = {
398     .class_name     = "RTSP demuxer",
399     .item_name      = av_default_item_name,
400     .option         = ff_rtsp_options,
401     .version        = LIBAVUTIL_VERSION_INT,
402 };
403
404 AVInputFormat ff_rtsp_demuxer = {
405     .name           = "rtsp",
406     .long_name      = NULL_IF_CONFIG_SMALL("RTSP input format"),
407     .priv_data_size = sizeof(RTSPState),
408     .read_probe     = rtsp_probe,
409     .read_header    = rtsp_read_header,
410     .read_packet    = rtsp_read_packet,
411     .read_close     = rtsp_read_close,
412     .read_seek      = rtsp_read_seek,
413     .flags          = AVFMT_NOFILE,
414     .read_play      = rtsp_read_play,
415     .read_pause     = rtsp_read_pause,
416     .priv_class     = &rtsp_demuxer_class,
417 };