Replace some nonstandard DEBUG_* preprocessor directives by plain DEBUG.
[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 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 FF_API_FORMAT_PARAMETERS
167     if (ap->initial_pause)
168         rt->initial_pause = ap->initial_pause;
169 #endif
170
171     if (rt->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     av_dlog(s, "tcp_read_packet:\n");
192 redo:
193     for (;;) {
194         RTSPMessageHeader reply;
195
196         ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
197         if (ret < 0)
198             return ret;
199         if (ret == 1) /* received '$' */
200             break;
201         /* XXX: parse message */
202         if (rt->state != RTSP_STATE_STREAMING)
203             return 0;
204     }
205     ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
206     if (ret != 3)
207         return -1;
208     id  = buf[0];
209     len = AV_RB16(buf + 1);
210     av_dlog(s, "id=%d len=%d\n", id, len);
211     if (len > buf_size || len < 12)
212         goto redo;
213     /* get the data */
214     ret = ffurl_read_complete(rt->rtsp_hd, buf, len);
215     if (ret != len)
216         return -1;
217     if (rt->transport == RTSP_TRANSPORT_RDT &&
218         ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
219         return -1;
220
221     /* find the matching stream */
222     for (i = 0; i < rt->nb_rtsp_streams; i++) {
223         rtsp_st = rt->rtsp_streams[i];
224         if (id >= rtsp_st->interleaved_min &&
225             id <= rtsp_st->interleaved_max)
226             goto found;
227     }
228     goto redo;
229 found:
230     *prtsp_st = rtsp_st;
231     return len;
232 }
233
234 static int resetup_tcp(AVFormatContext *s)
235 {
236     RTSPState *rt = s->priv_data;
237     char host[1024];
238     int port;
239
240     av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0,
241                  s->filename);
242     ff_rtsp_undo_setup(s);
243     return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP,
244                                       rt->real_challenge);
245 }
246
247 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
248 {
249     RTSPState *rt = s->priv_data;
250     int ret;
251     RTSPMessageHeader reply1, *reply = &reply1;
252     char cmd[1024];
253
254 retry:
255     if (rt->server_type == RTSP_SERVER_REAL) {
256         int i;
257
258         for (i = 0; i < s->nb_streams; i++)
259             rt->real_setup[i] = s->streams[i]->discard;
260
261         if (!rt->need_subscription) {
262             if (memcmp (rt->real_setup, rt->real_setup_cache,
263                         sizeof(enum AVDiscard) * s->nb_streams)) {
264                 snprintf(cmd, sizeof(cmd),
265                          "Unsubscribe: %s\r\n",
266                          rt->last_subscription);
267                 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
268                                  cmd, reply, NULL);
269                 if (reply->status_code != RTSP_STATUS_OK)
270                     return AVERROR_INVALIDDATA;
271                 rt->need_subscription = 1;
272             }
273         }
274
275         if (rt->need_subscription) {
276             int r, rule_nr, first = 1;
277
278             memcpy(rt->real_setup_cache, rt->real_setup,
279                    sizeof(enum AVDiscard) * s->nb_streams);
280             rt->last_subscription[0] = 0;
281
282             snprintf(cmd, sizeof(cmd),
283                      "Subscribe: ");
284             for (i = 0; i < rt->nb_rtsp_streams; i++) {
285                 rule_nr = 0;
286                 for (r = 0; r < s->nb_streams; r++) {
287                     if (s->streams[r]->id == i) {
288                         if (s->streams[r]->discard != AVDISCARD_ALL) {
289                             if (!first)
290                                 av_strlcat(rt->last_subscription, ",",
291                                            sizeof(rt->last_subscription));
292                             ff_rdt_subscribe_rule(
293                                 rt->last_subscription,
294                                 sizeof(rt->last_subscription), i, rule_nr);
295                             first = 0;
296                         }
297                         rule_nr++;
298                     }
299                 }
300             }
301             av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
302             ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
303                              cmd, reply, NULL);
304             if (reply->status_code != RTSP_STATUS_OK)
305                 return AVERROR_INVALIDDATA;
306             rt->need_subscription = 0;
307
308             if (rt->state == RTSP_STATE_STREAMING)
309                 rtsp_read_play (s);
310         }
311     }
312
313     ret = ff_rtsp_fetch_packet(s, pkt);
314     if (ret < 0) {
315         if (ret == AVERROR(ETIMEDOUT) && !rt->packets) {
316             if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
317                 rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) {
318                 RTSPMessageHeader reply1, *reply = &reply1;
319                 av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n");
320                 if (rtsp_read_pause(s) != 0)
321                     return -1;
322                 // TEARDOWN is required on Real-RTSP, but might make
323                 // other servers close the connection.
324                 if (rt->server_type == RTSP_SERVER_REAL)
325                     ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL,
326                                      reply, NULL);
327                 rt->session_id[0] = '\0';
328                 if (resetup_tcp(s) == 0) {
329                     rt->state = RTSP_STATE_IDLE;
330                     rt->need_subscription = 1;
331                     if (rtsp_read_play(s) != 0)
332                         return -1;
333                     goto retry;
334                 }
335             }
336         }
337         return ret;
338     }
339     rt->packets++;
340
341     /* send dummy request to keep TCP connection alive */
342     if ((av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
343         if (rt->server_type == RTSP_SERVER_WMS ||
344            (rt->server_type != RTSP_SERVER_REAL &&
345             rt->get_parameter_supported)) {
346             ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
347         } else {
348             ff_rtsp_send_cmd_async(s, "OPTIONS", "*", NULL);
349         }
350     }
351
352     return 0;
353 }
354
355 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
356                           int64_t timestamp, int flags)
357 {
358     RTSPState *rt = s->priv_data;
359
360     rt->seek_timestamp = av_rescale_q(timestamp,
361                                       s->streams[stream_index]->time_base,
362                                       AV_TIME_BASE_Q);
363     switch(rt->state) {
364     default:
365     case RTSP_STATE_IDLE:
366         break;
367     case RTSP_STATE_STREAMING:
368         if (rtsp_read_pause(s) != 0)
369             return -1;
370         rt->state = RTSP_STATE_SEEKING;
371         if (rtsp_read_play(s) != 0)
372             return -1;
373         break;
374     case RTSP_STATE_PAUSED:
375         rt->state = RTSP_STATE_IDLE;
376         break;
377     }
378     return 0;
379 }
380
381 static int rtsp_read_close(AVFormatContext *s)
382 {
383     RTSPState *rt = s->priv_data;
384
385 #if 0
386     /* NOTE: it is valid to flush the buffer here */
387     if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
388         avio_close(&rt->rtsp_gb);
389     }
390 #endif
391     ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
392
393     ff_rtsp_close_streams(s);
394     ff_rtsp_close_connections(s);
395     ff_network_close();
396     rt->real_setup = NULL;
397     av_freep(&rt->real_setup_cache);
398     return 0;
399 }
400
401 static const AVOption options[] = {
402     { "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 },
403     { NULL },
404 };
405
406 const AVClass rtsp_demuxer_class = {
407     .class_name     = "RTSP demuxer",
408     .item_name      = av_default_item_name,
409     .option         = options,
410     .version        = LIBAVUTIL_VERSION_INT,
411 };
412
413 AVInputFormat ff_rtsp_demuxer = {
414     "rtsp",
415     NULL_IF_CONFIG_SMALL("RTSP input format"),
416     sizeof(RTSPState),
417     rtsp_probe,
418     rtsp_read_header,
419     rtsp_read_packet,
420     rtsp_read_close,
421     rtsp_read_seek,
422     .flags = AVFMT_NOFILE,
423     .read_play = rtsp_read_play,
424     .read_pause = rtsp_read_pause,
425     .priv_class = &rtsp_demuxer_class,
426 };