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