]> git.sesse.net Git - ffmpeg/blob - libavformat/rtspenc.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavformat / rtspenc.c
1 /*
2  * RTSP muxer
3  * Copyright (c) 2010 Martin Storsjo
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 "avformat.h"
23
24 #include <sys/time.h>
25 #if HAVE_POLL_H
26 #include <poll.h>
27 #endif
28 #include "network.h"
29 #include "os_support.h"
30 #include "rtsp.h"
31 #include "internal.h"
32 #include "avio_internal.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavutil/avstring.h"
35 #include "url.h"
36 #include "libavutil/opt.h"
37 #include "rtpenc.h"
38
39 #define SDP_MAX_SIZE 16384
40
41 static const AVOption options[] = {
42     FF_RTP_FLAG_OPTS(RTSPState, rtp_muxer_flags),
43     { NULL },
44 };
45
46 static const AVClass rtsp_muxer_class = {
47     .class_name = "RTSP muxer",
48     .item_name  = av_default_item_name,
49     .option     = options,
50     .version    = LIBAVUTIL_VERSION_INT,
51 };
52
53 int ff_rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
54 {
55     RTSPState *rt = s->priv_data;
56     RTSPMessageHeader reply1, *reply = &reply1;
57     int i;
58     char *sdp;
59     AVFormatContext sdp_ctx, *ctx_array[1];
60
61     s->start_time_realtime = av_gettime();
62
63     /* Announce the stream */
64     sdp = av_mallocz(SDP_MAX_SIZE);
65     if (sdp == NULL)
66         return AVERROR(ENOMEM);
67     /* We create the SDP based on the RTSP AVFormatContext where we
68      * aren't allowed to change the filename field. (We create the SDP
69      * based on the RTSP context since the contexts for the RTP streams
70      * don't exist yet.) In order to specify a custom URL with the actual
71      * peer IP instead of the originally specified hostname, we create
72      * a temporary copy of the AVFormatContext, where the custom URL is set.
73      *
74      * FIXME: Create the SDP without copying the AVFormatContext.
75      * This either requires setting up the RTP stream AVFormatContexts
76      * already here (complicating things immensely) or getting a more
77      * flexible SDP creation interface.
78      */
79     sdp_ctx = *s;
80     ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
81                 "rtsp", NULL, addr, -1, NULL);
82     ctx_array[0] = &sdp_ctx;
83     if (av_sdp_create(ctx_array, 1, sdp, SDP_MAX_SIZE)) {
84         av_free(sdp);
85         return AVERROR_INVALIDDATA;
86     }
87     av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
88     ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
89                                   "Content-Type: application/sdp\r\n",
90                                   reply, NULL, sdp, strlen(sdp));
91     av_free(sdp);
92     if (reply->status_code != RTSP_STATUS_OK)
93         return AVERROR_INVALIDDATA;
94
95     /* Set up the RTSPStreams for each AVStream */
96     for (i = 0; i < s->nb_streams; i++) {
97         RTSPStream *rtsp_st;
98
99         rtsp_st = av_mallocz(sizeof(RTSPStream));
100         if (!rtsp_st)
101             return AVERROR(ENOMEM);
102         dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
103
104         rtsp_st->stream_index = i;
105
106         av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
107         /* Note, this must match the relative uri set in the sdp content */
108         av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
109                     "/streamid=%d", i);
110     }
111
112     return 0;
113 }
114
115 static int rtsp_write_record(AVFormatContext *s)
116 {
117     RTSPState *rt = s->priv_data;
118     RTSPMessageHeader reply1, *reply = &reply1;
119     char cmd[1024];
120
121     snprintf(cmd, sizeof(cmd),
122              "Range: npt=0.000-\r\n");
123     ff_rtsp_send_cmd(s, "RECORD", rt->control_uri, cmd, reply, NULL);
124     if (reply->status_code != RTSP_STATUS_OK)
125         return -1;
126     rt->state = RTSP_STATE_STREAMING;
127     return 0;
128 }
129
130 static int rtsp_write_header(AVFormatContext *s)
131 {
132     int ret;
133
134     ret = ff_rtsp_connect(s);
135     if (ret)
136         return ret;
137
138     if (rtsp_write_record(s) < 0) {
139         ff_rtsp_close_streams(s);
140         ff_rtsp_close_connections(s);
141         return AVERROR_INVALIDDATA;
142     }
143     return 0;
144 }
145
146 static int tcp_write_packet(AVFormatContext *s, RTSPStream *rtsp_st)
147 {
148     RTSPState *rt = s->priv_data;
149     AVFormatContext *rtpctx = rtsp_st->transport_priv;
150     uint8_t *buf, *ptr;
151     int size;
152     uint8_t *interleave_header, *interleaved_packet;
153
154     size = avio_close_dyn_buf(rtpctx->pb, &buf);
155     ptr = buf;
156     while (size > 4) {
157         uint32_t packet_len = AV_RB32(ptr);
158         int id;
159         /* The interleaving header is exactly 4 bytes, which happens to be
160          * the same size as the packet length header from
161          * ffio_open_dyn_packet_buf. So by writing the interleaving header
162          * over these bytes, we get a consecutive interleaved packet
163          * that can be written in one call. */
164         interleaved_packet = interleave_header = ptr;
165         ptr += 4;
166         size -= 4;
167         if (packet_len > size || packet_len < 2)
168             break;
169         if (ptr[1] >= RTCP_SR && ptr[1] <= RTCP_APP)
170             id = rtsp_st->interleaved_max; /* RTCP */
171         else
172             id = rtsp_st->interleaved_min; /* RTP */
173         interleave_header[0] = '$';
174         interleave_header[1] = id;
175         AV_WB16(interleave_header + 2, packet_len);
176         ffurl_write(rt->rtsp_hd_out, interleaved_packet, 4 + packet_len);
177         ptr += packet_len;
178         size -= packet_len;
179     }
180     av_free(buf);
181     ffio_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE);
182     return 0;
183 }
184
185 static int rtsp_write_packet(AVFormatContext *s, AVPacket *pkt)
186 {
187     RTSPState *rt = s->priv_data;
188     RTSPStream *rtsp_st;
189     int n;
190     struct pollfd p = {ffurl_get_file_handle(rt->rtsp_hd), POLLIN, 0};
191     AVFormatContext *rtpctx;
192     int ret;
193
194     while (1) {
195         n = poll(&p, 1, 0);
196         if (n <= 0)
197             break;
198         if (p.revents & POLLIN) {
199             RTSPMessageHeader reply;
200
201             /* Don't let ff_rtsp_read_reply handle interleaved packets,
202              * since it would block and wait for an RTSP reply on the socket
203              * (which may not be coming any time soon) if it handles
204              * interleaved packets internally. */
205             ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
206             if (ret < 0)
207                 return AVERROR(EPIPE);
208             if (ret == 1)
209                 ff_rtsp_skip_packet(s);
210             /* XXX: parse message */
211             if (rt->state != RTSP_STATE_STREAMING)
212                 return AVERROR(EPIPE);
213         }
214     }
215
216     if (pkt->stream_index < 0 || pkt->stream_index >= rt->nb_rtsp_streams)
217         return AVERROR_INVALIDDATA;
218     rtsp_st = rt->rtsp_streams[pkt->stream_index];
219     rtpctx = rtsp_st->transport_priv;
220
221     ret = ff_write_chained(rtpctx, 0, pkt, s);
222     /* ff_write_chained does all the RTP packetization. If using TCP as
223      * transport, rtpctx->pb is only a dyn_packet_buf that queues up the
224      * packets, so we need to send them out on the TCP connection separately.
225      */
226     if (!ret && rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP)
227         ret = tcp_write_packet(s, rtsp_st);
228     return ret;
229 }
230
231 static int rtsp_write_close(AVFormatContext *s)
232 {
233     RTSPState *rt = s->priv_data;
234
235     ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
236
237     ff_rtsp_close_streams(s);
238     ff_rtsp_close_connections(s);
239     ff_network_close();
240     return 0;
241 }
242
243 AVOutputFormat ff_rtsp_muxer = {
244     .name              = "rtsp",
245     .long_name         = NULL_IF_CONFIG_SMALL("RTSP output format"),
246     .priv_data_size    = sizeof(RTSPState),
247     .audio_codec       = CODEC_ID_AAC,
248     .video_codec       = CODEC_ID_MPEG4,
249     .write_header      = rtsp_write_header,
250     .write_packet      = rtsp_write_packet,
251     .write_trailer     = rtsp_write_close,
252     .flags = AVFMT_NOFILE | AVFMT_GLOBALHEADER,
253     .priv_class = &rtsp_muxer_class,
254 };
255