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