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