fa6bc0551766224f04352ee997d5387346d04347
[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/opt.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 //#define DEBUG
35 //#define DEBUG_RTP_TCP
36
37 static int rtsp_read_play(AVFormatContext *s)
38 {
39     RTSPState *rt = s->priv_data;
40     RTSPMessageHeader reply1, *reply = &reply1;
41     int i;
42     char cmd[1024];
43
44     av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
45     rt->nb_byes = 0;
46
47     if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
48         if (rt->transport == RTSP_TRANSPORT_RTP) {
49             for (i = 0; i < rt->nb_rtsp_streams; i++) {
50                 RTSPStream *rtsp_st = rt->rtsp_streams[i];
51                 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
52                 if (!rtpctx)
53                     continue;
54                 ff_rtp_reset_packet_queue(rtpctx);
55                 rtpctx->last_rtcp_ntp_time  = AV_NOPTS_VALUE;
56                 rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
57                 rtpctx->base_timestamp      = 0;
58                 rtpctx->rtcp_ts_offset      = 0;
59             }
60         }
61         if (rt->state == RTSP_STATE_PAUSED) {
62             cmd[0] = 0;
63         } else {
64             snprintf(cmd, sizeof(cmd),
65                      "Range: npt=%"PRId64".%03"PRId64"-\r\n",
66                      rt->seek_timestamp / AV_TIME_BASE,
67                      rt->seek_timestamp / (AV_TIME_BASE / 1000) % 1000);
68         }
69         ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
70         if (reply->status_code != RTSP_STATUS_OK) {
71             return -1;
72         }
73         if (rt->transport == RTSP_TRANSPORT_RTP &&
74             reply->range_start != AV_NOPTS_VALUE) {
75             for (i = 0; i < rt->nb_rtsp_streams; i++) {
76                 RTSPStream *rtsp_st = rt->rtsp_streams[i];
77                 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
78                 AVStream *st = NULL;
79                 if (!rtpctx || rtsp_st->stream_index < 0)
80                     continue;
81                 st = s->streams[rtsp_st->stream_index];
82                 rtpctx->range_start_offset =
83                     av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
84                                  st->time_base);
85             }
86         }
87     }
88     rt->state = RTSP_STATE_STREAMING;
89     return 0;
90 }
91
92 /* pause the stream */
93 static int rtsp_read_pause(AVFormatContext *s)
94 {
95     RTSPState *rt = s->priv_data;
96     RTSPMessageHeader reply1, *reply = &reply1;
97
98     if (rt->state != RTSP_STATE_STREAMING)
99         return 0;
100     else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
101         ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
102         if (reply->status_code != RTSP_STATUS_OK) {
103             return -1;
104         }
105     }
106     rt->state = RTSP_STATE_PAUSED;
107     return 0;
108 }
109
110 int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
111 {
112     RTSPState *rt = s->priv_data;
113     char cmd[1024];
114     unsigned char *content = NULL;
115     int ret;
116
117     /* describe the stream */
118     snprintf(cmd, sizeof(cmd),
119              "Accept: application/sdp\r\n");
120     if (rt->server_type == RTSP_SERVER_REAL) {
121         /**
122          * The Require: attribute is needed for proper streaming from
123          * Realmedia servers.
124          */
125         av_strlcat(cmd,
126                    "Require: com.real.retain-entity-for-setup\r\n",
127                    sizeof(cmd));
128     }
129     ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
130     if (!content)
131         return AVERROR_INVALIDDATA;
132     if (reply->status_code != RTSP_STATUS_OK) {
133         av_freep(&content);
134         return AVERROR_INVALIDDATA;
135     }
136
137     av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
138     /* now we got the SDP description, we parse it */
139     ret = ff_sdp_parse(s, (const char *)content);
140     av_freep(&content);
141     if (ret < 0)
142         return ret;
143
144     return 0;
145 }
146
147 static int rtsp_probe(AVProbeData *p)
148 {
149     if (av_strstart(p->filename, "rtsp:", NULL))
150         return AVPROBE_SCORE_MAX;
151     return 0;
152 }
153
154 static int rtsp_read_header(AVFormatContext *s,
155                             AVFormatParameters *ap)
156 {
157     RTSPState *rt = s->priv_data;
158     int ret;
159
160     ret = ff_rtsp_connect(s);
161     if (ret)
162         return ret;
163
164     rt->real_setup_cache = av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));
165     if (!rt->real_setup_cache)
166         return AVERROR(ENOMEM);
167     rt->real_setup = rt->real_setup_cache + s->nb_streams;
168
169 #if FF_API_FORMAT_PARAMETERS
170     if (ap->initial_pause)
171         rt->initial_pause = ap->initial_pause;
172 #endif
173
174     if (rt->initial_pause) {
175          /* do not start immediately */
176     } else {
177          if (rtsp_read_play(s) < 0) {
178             ff_rtsp_close_streams(s);
179             ff_rtsp_close_connections(s);
180             return AVERROR_INVALIDDATA;
181         }
182     }
183
184     return 0;
185 }
186
187 int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
188                             uint8_t *buf, int buf_size)
189 {
190     RTSPState *rt = s->priv_data;
191     int id, len, i, ret;
192     RTSPStream *rtsp_st;
193
194 #ifdef DEBUG_RTP_TCP
195     av_dlog(s, "tcp_read_packet:\n");
196 #endif
197 redo:
198     for (;;) {
199         RTSPMessageHeader reply;
200
201         ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
202         if (ret < 0)
203             return ret;
204         if (ret == 1) /* received '$' */
205             break;
206         /* XXX: parse message */
207         if (rt->state != RTSP_STATE_STREAMING)
208             return 0;
209     }
210     ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
211     if (ret != 3)
212         return -1;
213     id  = buf[0];
214     len = AV_RB16(buf + 1);
215 #ifdef DEBUG_RTP_TCP
216     av_dlog(s, "id=%d len=%d\n", id, len);
217 #endif
218     if (len > buf_size || len < 12)
219         goto redo;
220     /* get the data */
221     ret = ffurl_read_complete(rt->rtsp_hd, buf, len);
222     if (ret != len)
223         return -1;
224     if (rt->transport == RTSP_TRANSPORT_RDT &&
225         ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
226         return -1;
227
228     /* find the matching stream */
229     for (i = 0; i < rt->nb_rtsp_streams; i++) {
230         rtsp_st = rt->rtsp_streams[i];
231         if (id >= rtsp_st->interleaved_min &&
232             id <= rtsp_st->interleaved_max)
233             goto found;
234     }
235     goto redo;
236 found:
237     *prtsp_st = rtsp_st;
238     return len;
239 }
240
241 static int resetup_tcp(AVFormatContext *s)
242 {
243     RTSPState *rt = s->priv_data;
244     char host[1024];
245     int port;
246
247     av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0,
248                  s->filename);
249     ff_rtsp_undo_setup(s);
250     return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP,
251                                       rt->real_challenge);
252 }
253
254 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
255 {
256     RTSPState *rt = s->priv_data;
257     int ret;
258     RTSPMessageHeader reply1, *reply = &reply1;
259     char cmd[1024];
260
261 retry:
262     if (rt->server_type == RTSP_SERVER_REAL) {
263         int i;
264
265         for (i = 0; i < s->nb_streams; i++)
266             rt->real_setup[i] = s->streams[i]->discard;
267
268         if (!rt->need_subscription) {
269             if (memcmp (rt->real_setup, rt->real_setup_cache,
270                         sizeof(enum AVDiscard) * s->nb_streams)) {
271                 snprintf(cmd, sizeof(cmd),
272                          "Unsubscribe: %s\r\n",
273                          rt->last_subscription);
274                 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
275                                  cmd, reply, NULL);
276                 if (reply->status_code != RTSP_STATUS_OK)
277                     return AVERROR_INVALIDDATA;
278                 rt->need_subscription = 1;
279             }
280         }
281
282         if (rt->need_subscription) {
283             int r, rule_nr, first = 1;
284
285             memcpy(rt->real_setup_cache, rt->real_setup,
286                    sizeof(enum AVDiscard) * s->nb_streams);
287             rt->last_subscription[0] = 0;
288
289             snprintf(cmd, sizeof(cmd),
290                      "Subscribe: ");
291             for (i = 0; i < rt->nb_rtsp_streams; i++) {
292                 rule_nr = 0;
293                 for (r = 0; r < s->nb_streams; r++) {
294                     if (s->streams[r]->id == i) {
295                         if (s->streams[r]->discard != AVDISCARD_ALL) {
296                             if (!first)
297                                 av_strlcat(rt->last_subscription, ",",
298                                            sizeof(rt->last_subscription));
299                             ff_rdt_subscribe_rule(
300                                 rt->last_subscription,
301                                 sizeof(rt->last_subscription), i, rule_nr);
302                             first = 0;
303                         }
304                         rule_nr++;
305                     }
306                 }
307             }
308             av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
309             ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
310                              cmd, reply, NULL);
311             if (reply->status_code != RTSP_STATUS_OK)
312                 return AVERROR_INVALIDDATA;
313             rt->need_subscription = 0;
314
315             if (rt->state == RTSP_STATE_STREAMING)
316                 rtsp_read_play (s);
317         }
318     }
319
320     ret = ff_rtsp_fetch_packet(s, pkt);
321     if (ret < 0) {
322         if (ret == AVERROR(ETIMEDOUT) && !rt->packets) {
323             if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
324                 rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) {
325                 RTSPMessageHeader reply1, *reply = &reply1;
326                 av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n");
327                 if (rtsp_read_pause(s) != 0)
328                     return -1;
329                 // TEARDOWN is required on Real-RTSP, but might make
330                 // other servers close the connection.
331                 if (rt->server_type == RTSP_SERVER_REAL)
332                     ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL,
333                                      reply, NULL);
334                 rt->session_id[0] = '\0';
335                 if (resetup_tcp(s) == 0) {
336                     rt->state = RTSP_STATE_IDLE;
337                     rt->need_subscription = 1;
338                     if (rtsp_read_play(s) != 0)
339                         return -1;
340                     goto retry;
341                 }
342             }
343         }
344         return ret;
345     }
346     rt->packets++;
347
348     /* send dummy request to keep TCP connection alive */
349     if ((av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
350         if (rt->server_type == RTSP_SERVER_WMS ||
351            (rt->server_type != RTSP_SERVER_REAL &&
352             rt->get_parameter_supported)) {
353             ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
354         } else {
355             ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
356         }
357     }
358
359     return 0;
360 }
361
362 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
363                           int64_t timestamp, int flags)
364 {
365     RTSPState *rt = s->priv_data;
366
367     rt->seek_timestamp = av_rescale_q(timestamp,
368                                       s->streams[stream_index]->time_base,
369                                       AV_TIME_BASE_Q);
370     switch(rt->state) {
371     default:
372     case RTSP_STATE_IDLE:
373         break;
374     case RTSP_STATE_STREAMING:
375         if (rtsp_read_pause(s) != 0)
376             return -1;
377         rt->state = RTSP_STATE_SEEKING;
378         if (rtsp_read_play(s) != 0)
379             return -1;
380         break;
381     case RTSP_STATE_PAUSED:
382         rt->state = RTSP_STATE_IDLE;
383         break;
384     }
385     return 0;
386 }
387
388 static int rtsp_read_close(AVFormatContext *s)
389 {
390     RTSPState *rt = s->priv_data;
391
392 #if 0
393     /* NOTE: it is valid to flush the buffer here */
394     if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
395         avio_close(&rt->rtsp_gb);
396     }
397 #endif
398     ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
399
400     ff_rtsp_close_streams(s);
401     ff_rtsp_close_connections(s);
402     ff_network_close();
403     rt->real_setup = NULL;
404     av_freep(&rt->real_setup_cache);
405     return 0;
406 }
407
408 static const AVOption options[] = {
409     { "initial_pause",  "Don't start playing the stream immediately", offsetof(RTSPState, initial_pause),  FF_OPT_TYPE_INT, {.dbl = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
410     { NULL },
411 };
412
413 const AVClass rtsp_demuxer_class = {
414     .class_name     = "RTSP demuxer",
415     .item_name      = av_default_item_name,
416     .option         = options,
417     .version        = LIBAVUTIL_VERSION_INT,
418 };
419
420 AVInputFormat ff_rtsp_demuxer = {
421     "rtsp",
422     NULL_IF_CONFIG_SMALL("RTSP input format"),
423     sizeof(RTSPState),
424     rtsp_probe,
425     rtsp_read_header,
426     rtsp_read_packet,
427     rtsp_read_close,
428     rtsp_read_seek,
429     .flags = AVFMT_NOFILE,
430     .read_play = rtsp_read_play,
431     .read_pause = rtsp_read_pause,
432     .priv_class = &rtsp_demuxer_class,
433 };