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