rtspenc.c
Go to the documentation of this file.
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 #if HAVE_POLL_H
25 #include <poll.h>
26 #endif
27 #include "network.h"
28 #include "os_support.h"
29 #include "rtsp.h"
30 #include "internal.h"
31 #include "avio_internal.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/time.h"
35 #include "url.h"
36 
37 #define SDP_MAX_SIZE 16384
38 
39 static const AVClass rtsp_muxer_class = {
40  .class_name = "RTSP muxer",
41  .item_name = av_default_item_name,
42  .option = ff_rtsp_options,
43  .version = LIBAVUTIL_VERSION_INT,
44 };
45 
47 {
48  RTSPState *rt = s->priv_data;
49  RTSPMessageHeader reply1, *reply = &reply1;
50  int i;
51  char *sdp;
52  AVFormatContext sdp_ctx, *ctx_array[1];
53 
55 
56  /* Announce the stream */
57  sdp = av_mallocz(SDP_MAX_SIZE);
58  if (sdp == NULL)
59  return AVERROR(ENOMEM);
60  /* We create the SDP based on the RTSP AVFormatContext where we
61  * aren't allowed to change the filename field. (We create the SDP
62  * based on the RTSP context since the contexts for the RTP streams
63  * don't exist yet.) In order to specify a custom URL with the actual
64  * peer IP instead of the originally specified hostname, we create
65  * a temporary copy of the AVFormatContext, where the custom URL is set.
66  *
67  * FIXME: Create the SDP without copying the AVFormatContext.
68  * This either requires setting up the RTP stream AVFormatContexts
69  * already here (complicating things immensely) or getting a more
70  * flexible SDP creation interface.
71  */
72  sdp_ctx = *s;
73  ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),
74  "rtsp", NULL, addr, -1, NULL);
75  ctx_array[0] = &sdp_ctx;
76  if (av_sdp_create(ctx_array, 1, sdp, SDP_MAX_SIZE)) {
77  av_free(sdp);
78  return AVERROR_INVALIDDATA;
79  }
80  av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
81  ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,
82  "Content-Type: application/sdp\r\n",
83  reply, NULL, sdp, strlen(sdp));
84  av_free(sdp);
85  if (reply->status_code != RTSP_STATUS_OK)
86  return AVERROR_INVALIDDATA;
87 
88  /* Set up the RTSPStreams for each AVStream */
89  for (i = 0; i < s->nb_streams; i++) {
90  RTSPStream *rtsp_st;
91 
92  rtsp_st = av_mallocz(sizeof(RTSPStream));
93  if (!rtsp_st)
94  return AVERROR(ENOMEM);
95  dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
96 
97  rtsp_st->stream_index = i;
98 
99  av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
100  /* Note, this must match the relative uri set in the sdp content */
101  av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
102  "/streamid=%d", i);
103  }
104 
105  return 0;
106 }
107 
109 {
110  RTSPState *rt = s->priv_data;
111  RTSPMessageHeader reply1, *reply = &reply1;
112  char cmd[1024];
113 
114  snprintf(cmd, sizeof(cmd),
115  "Range: npt=0.000-\r\n");
116  ff_rtsp_send_cmd(s, "RECORD", rt->control_uri, cmd, reply, NULL);
117  if (reply->status_code != RTSP_STATUS_OK)
118  return -1;
120  return 0;
121 }
122 
124 {
125  int ret;
126 
127  ret = ff_rtsp_connect(s);
128  if (ret)
129  return ret;
130 
131  if (rtsp_write_record(s) < 0) {
134  return AVERROR_INVALIDDATA;
135  }
136  return 0;
137 }
138 
140 {
141  RTSPState *rt = s->priv_data;
142  AVFormatContext *rtpctx = rtsp_st->transport_priv;
143  uint8_t *buf, *ptr;
144  int size;
145  uint8_t *interleave_header, *interleaved_packet;
146 
147  size = avio_close_dyn_buf(rtpctx->pb, &buf);
148  ptr = buf;
149  while (size > 4) {
150  uint32_t packet_len = AV_RB32(ptr);
151  int id;
152  /* The interleaving header is exactly 4 bytes, which happens to be
153  * the same size as the packet length header from
154  * ffio_open_dyn_packet_buf. So by writing the interleaving header
155  * over these bytes, we get a consecutive interleaved packet
156  * that can be written in one call. */
157  interleaved_packet = interleave_header = ptr;
158  ptr += 4;
159  size -= 4;
160  if (packet_len > size || packet_len < 2)
161  break;
162  if (RTP_PT_IS_RTCP(ptr[1]))
163  id = rtsp_st->interleaved_max; /* RTCP */
164  else
165  id = rtsp_st->interleaved_min; /* RTP */
166  interleave_header[0] = '$';
167  interleave_header[1] = id;
168  AV_WB16(interleave_header + 2, packet_len);
169  ffurl_write(rt->rtsp_hd_out, interleaved_packet, 4 + packet_len);
170  ptr += packet_len;
171  size -= packet_len;
172  }
173  av_free(buf);
175  return 0;
176 }
177 
179 {
180  RTSPState *rt = s->priv_data;
181  RTSPStream *rtsp_st;
182  int n;
183  struct pollfd p = {ffurl_get_file_handle(rt->rtsp_hd), POLLIN, 0};
184  AVFormatContext *rtpctx;
185  int ret;
186 
187  while (1) {
188  n = poll(&p, 1, 0);
189  if (n <= 0)
190  break;
191  if (p.revents & POLLIN) {
192  RTSPMessageHeader reply;
193 
194  /* Don't let ff_rtsp_read_reply handle interleaved packets,
195  * since it would block and wait for an RTSP reply on the socket
196  * (which may not be coming any time soon) if it handles
197  * interleaved packets internally. */
198  ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
199  if (ret < 0)
200  return AVERROR(EPIPE);
201  if (ret == 1)
203  /* XXX: parse message */
204  if (rt->state != RTSP_STATE_STREAMING)
205  return AVERROR(EPIPE);
206  }
207  }
208 
209  if (pkt->stream_index < 0 || pkt->stream_index >= rt->nb_rtsp_streams)
210  return AVERROR_INVALIDDATA;
211  rtsp_st = rt->rtsp_streams[pkt->stream_index];
212  rtpctx = rtsp_st->transport_priv;
213 
214  ret = ff_write_chained(rtpctx, 0, pkt, s);
215  /* ff_write_chained does all the RTP packetization. If using TCP as
216  * transport, rtpctx->pb is only a dyn_packet_buf that queues up the
217  * packets, so we need to send them out on the TCP connection separately.
218  */
219  if (!ret && rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP)
220  ret = tcp_write_packet(s, rtsp_st);
221  return ret;
222 }
223 
225 {
226  RTSPState *rt = s->priv_data;
227 
228  ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
229 
233  return 0;
234 }
235 
237  .name = "rtsp",
238  .long_name = NULL_IF_CONFIG_SMALL("RTSP output"),
239  .priv_data_size = sizeof(RTSPState),
240  .audio_codec = AV_CODEC_ID_AAC,
241  .video_codec = AV_CODEC_ID_MPEG4,
246  .priv_class = &rtsp_muxer_class,
247 };
void ff_rtsp_skip_packet(AVFormatContext *s)
Skip a RTP/TCP interleaved packet.
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:205
const char * s
Definition: avisynth_c.h:668
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
int64_t start_time_realtime
Start time of the stream in real world time, in microseconds since the unix epoch (00:00 1st January ...
Definition: avformat.h:1101
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:988
enum AVCodecID id
Definition: mxfenc.c:89
av_default_item_name
char control_uri[1024]
some MS RTSP streams contain a URL in the SDP that we need to use for all subsequent RTSP requests...
Definition: rtsp.h:316
int ffurl_write(URLContext *h, const unsigned char *buf, int size)
Write size bytes from buf to the resource accessed by h.
Definition: avio.c:317
static int write_packet(AVFormatContext *s, AVPacket *pkt)
void ff_network_close(void)
Definition: network.c:173
initialized and sending/receiving data
Definition: rtsp.h:196
int ff_url_join(char *str, int size, const char *proto, const char *authorization, const char *hostname, int port, const char *fmt,...) av_printf_format(7
Assemble a URL string from components.
This describes the server response to each RTSP command.
Definition: rtsp.h:126
Format I/O context.
Definition: avformat.h:944
int ff_rtsp_connect(AVFormatContext *s)
Connect to the RTSP server and set up the individual media streams.
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:55
uint8_t
miscellaneous OS support macros and functions.
#define AV_RB32
static AVPacket pkt
Definition: demuxing.c:56
URLContext * rtsp_hd_out
Additional output handle, used when input and output are done separately, eg for HTTP tunneling...
Definition: rtsp.h:327
Describe a single stream, as identified by a single m= line block in the SDP content.
Definition: rtsp.h:418
enum RTSPStatusCode status_code
response code from server
Definition: rtsp.h:130
int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size)
Generate an SDP for an RTP session.
Definition: sdp.c:703
int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url, const char *headers, RTSPMessageHeader *reply, unsigned char **content_ptr)
Send a command to the RTSP server and wait for the reply.
static int write_trailer(AVFormatContext *s)
Private data for the RTSP demuxer.
Definition: rtsp.h:217
AVOutputFormat ff_rtsp_muxer
Definition: rtspenc.c:236
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:183
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
const AVOption ff_rtsp_options[]
Definition: rtsp.c:81
URLContext * rtsp_hd
Definition: rtsp.h:219
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:246
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition: avstring.c:82
struct RTSPStream ** rtsp_streams
streams in this session
Definition: rtsp.h:224
int size
int stream_index
corresponding stream index, if any.
Definition: rtsp.h:423
static int rtsp_write_close(AVFormatContext *s)
Definition: rtspenc.c:224
static int rtsp_write_header(AVFormatContext *s)
Definition: rtspenc.c:123
unsigned int nb_streams
A list of all streams in the file.
Definition: avformat.h:991
#define AV_LOG_VERBOSE
Definition: log.h:157
#define dynarray_add(tab, nb_ptr, elem)
char filename[1024]
input or output filename
Definition: avformat.h:994
int nb_rtsp_streams
number of items in the &#39;rtsp_streams&#39; variable
Definition: rtsp.h:222
ret
Definition: avfilter.c:821
int ffio_open_dyn_packet_buf(AVIOContext **s, int max_packet_size)
Open a write only packetized memory stream with a maximum packet size of &#39;max_packet_size&#39;.
Definition: aviobuf.c:981
#define RTSP_TCP_MAX_PACKET_SIZE
Definition: rtsp.h:74
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:351
const char * name
Definition: avformat.h:378
static int rtsp_write_record(AVFormatContext *s)
Definition: rtspenc.c:108
static int tcp_write_packet(AVFormatContext *s, RTSPStream *rtsp_st)
Definition: rtspenc.c:139
int ffurl_get_file_handle(URLContext *h)
Return the file descriptor associated with this URL.
Definition: avio.c:399
LIBAVUTIL_VERSION_INT
Definition: eval.c:55
#define SDP_MAX_SIZE
Definition: rtspenc.c:37
int64_t av_gettime(void)
Get the current time in microseconds.
Definition: time.c:39
enum RTSPLowerTransport lower_transport
the negotiated network layer transport protocol; e.g.
Definition: rtsp.h:261
NULL
Definition: eval.c:55
AVIOContext * pb
I/O context.
Definition: avformat.h:977
void * buf
Definition: avisynth_c.h:594
Describe the class of an AVClass context structure.
Definition: log.h:50
synthesis window for stochastic i
#define AV_WB16(p, darg)
Definition: intreadwrite.h:237
struct RTSPState RTSPState
Private data for the RTSP demuxer.
size_t av_strlcatf(char *dst, size_t size, const char *fmt,...)
Definition: avstring.c:100
void ff_rtsp_close_streams(AVFormatContext *s)
Close and free all streams within the RTSP (de)muxer.
Definition: rtsp.c:603
#define snprintf
Definition: snprintf.h:34
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFilterBuffer structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later.That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another.Buffer references ownership and permissions
#define RTP_PT_IS_RTCP(x)
Definition: rtp.h:109
static int flags
Definition: cpu.c:23
enum RTSPClientState state
indicator of whether we are currently receiving data from the server.
Definition: rtsp.h:230
int ff_rtsp_send_cmd_with_content(AVFormatContext *s, const char *method, const char *url, const char *headers, RTSPMessageHeader *reply, unsigned char **content_ptr, const unsigned char *send_content, int send_content_length)
Send a command to the RTSP server and wait for the reply.
Main libavformat public API header.
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:345
int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt, AVFormatContext *src)
Write a packet to another muxer than the one the user originally intended.
int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply, unsigned char **content_ptr, int return_on_interleaved_data, const char *method)
Read a RTSP message from the server, or prepare to read data packets if we&#39;re reading data interleave...
int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method, const char *url, const char *headers)
Send a command to the RTSP server without waiting for the reply.
TCP; interleaved in RTSP.
Definition: rtsp.h:39
int ff_rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
Announce the stream to the server and set up the RTSPStream child objects for each media stream...
Definition: rtspenc.c:46
char control_url[1024]
url for this stream (from SDP)
Definition: rtsp.h:429
void * priv_data
Format private data.
Definition: avformat.h:964
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:470
static int rtsp_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: rtspenc.c:178
unbuffered private I/O API
int interleaved_max
Definition: rtsp.h:427
static const AVClass rtsp_muxer_class
Definition: rtspenc.c:39
int interleaved_min
interleave IDs; copies of RTSPTransportField->interleaved_min/max for the selected transport...
Definition: rtsp.h:427
This structure stores compressed data.
void ff_rtsp_close_connections(AVFormatContext *s)
Close all connection handles within the RTSP (de)muxer.
void * transport_priv
RTP/RDT parse context if input, RTP AVFormatContext if output.
Definition: rtsp.h:420