FFmpeg
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 "mux.h"
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 "libavutil/time.h"
36 #include "url.h"
37 
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  char url[MAX_URL_SIZE];
54 
55  if (s->start_time_realtime == 0 || s->start_time_realtime == AV_NOPTS_VALUE)
56  s->start_time_realtime = av_gettime();
57 
58  /* Announce the stream */
59  sdp = av_mallocz(SDP_MAX_SIZE);
60  if (!sdp)
61  return AVERROR(ENOMEM);
62  /* We create the SDP based on the RTSP AVFormatContext where we
63  * aren't allowed to change the filename field. (We create the SDP
64  * based on the RTSP context since the contexts for the RTP streams
65  * don't exist yet.) In order to specify a custom URL with the actual
66  * peer IP instead of the originally specified hostname, we create
67  * a temporary copy of the AVFormatContext, where the custom URL is set.
68  *
69  * FIXME: Create the SDP without copying the AVFormatContext.
70  * This either requires setting up the RTP stream AVFormatContexts
71  * already here (complicating things immensely) or getting a more
72  * flexible SDP creation interface.
73  */
74  sdp_ctx = *s;
75  sdp_ctx.url = url;
76  ff_url_join(url, sizeof(url),
77  "rtsp", NULL, addr, -1, NULL);
78  ctx_array[0] = &sdp_ctx;
79  if (av_sdp_create(ctx_array, 1, sdp, SDP_MAX_SIZE)) {
80  av_free(sdp);
81  return AVERROR_INVALIDDATA;
82  }
83  av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
85  "Content-Type: application/sdp\r\n",
86  reply, NULL, sdp, strlen(sdp));
87  av_free(sdp);
88  if (reply->status_code != RTSP_STATUS_OK)
90 
91  /* Set up the RTSPStreams for each AVStream */
92  for (i = 0; i < s->nb_streams; i++) {
93  RTSPStream *rtsp_st;
94 
95  rtsp_st = av_mallocz(sizeof(RTSPStream));
96  if (!rtsp_st)
97  return AVERROR(ENOMEM);
98  dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
99 
100  rtsp_st->stream_index = i;
101 
102  av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));
103  /* Note, this must match the relative uri set in the sdp content */
104  av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
105  "/streamid=%d", i);
106  }
107 
108  return 0;
109 }
110 
112 {
113  RTSPState *rt = s->priv_data;
114  RTSPMessageHeader reply1, *reply = &reply1;
115  char cmd[MAX_URL_SIZE];
116 
117  snprintf(cmd, sizeof(cmd),
118  "Range: npt=0.000-\r\n");
119  ff_rtsp_send_cmd(s, "RECORD", rt->control_uri, cmd, reply, NULL);
120  if (reply->status_code != RTSP_STATUS_OK)
121  return ff_rtsp_averror(reply->status_code, -1);
123  return 0;
124 }
125 
127 {
128  int ret;
129 
130  ret = ff_rtsp_connect(s);
131  if (ret)
132  return ret;
133 
134  if (rtsp_write_record(s) < 0) {
137  return AVERROR_INVALIDDATA;
138  }
139  return 0;
140 }
141 
143 {
144  RTSPState *rt = s->priv_data;
145  AVFormatContext *rtpctx = rtsp_st->transport_priv;
146  uint8_t *buf, *ptr;
147  int size;
148  uint8_t *interleave_header, *interleaved_packet;
149 
150  size = avio_close_dyn_buf(rtpctx->pb, &buf);
151  rtpctx->pb = NULL;
152  ptr = buf;
153  while (size > 4) {
154  uint32_t packet_len = AV_RB32(ptr);
155  int id;
156  /* The interleaving header is exactly 4 bytes, which happens to be
157  * the same size as the packet length header from
158  * ffio_open_dyn_packet_buf. So by writing the interleaving header
159  * over these bytes, we get a consecutive interleaved packet
160  * that can be written in one call. */
161  interleaved_packet = interleave_header = ptr;
162  ptr += 4;
163  size -= 4;
164  if (packet_len > size || packet_len < 2)
165  break;
166  if (RTP_PT_IS_RTCP(ptr[1]))
167  id = rtsp_st->interleaved_max; /* RTCP */
168  else
169  id = rtsp_st->interleaved_min; /* RTP */
170  interleave_header[0] = '$';
171  interleave_header[1] = id;
172  AV_WB16(interleave_header + 2, packet_len);
173  ffurl_write(rt->rtsp_hd_out, interleaved_packet, 4 + packet_len);
174  ptr += packet_len;
175  size -= packet_len;
176  }
177  av_free(buf);
178  return ffio_open_dyn_packet_buf(&rtpctx->pb, rt->pkt_size);
179 }
180 
182 {
183  RTSPState *rt = s->priv_data;
184  RTSPStream *rtsp_st;
185  int n;
186  struct pollfd p = {ffurl_get_file_handle(rt->rtsp_hd), POLLIN, 0};
187  AVFormatContext *rtpctx;
188  int ret;
189 
190  while (1) {
191  n = poll(&p, 1, 0);
192  if (n <= 0)
193  break;
194  if (p.revents & POLLIN) {
195  RTSPMessageHeader reply;
196 
197  /* Don't let ff_rtsp_read_reply handle interleaved packets,
198  * since it would block and wait for an RTSP reply on the socket
199  * (which may not be coming any time soon) if it handles
200  * interleaved packets internally. */
201  ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
202  if (ret < 0)
203  return AVERROR(EPIPE);
204  if (ret == 1) {
206  if (ret < 0)
207  return ret;
208  }
209  /* XXX: parse message */
210  if (rt->state != RTSP_STATE_STREAMING)
211  return AVERROR(EPIPE);
212  }
213  }
214 
215  if (pkt->stream_index < 0 || pkt->stream_index >= rt->nb_rtsp_streams)
216  return AVERROR_INVALIDDATA;
217  rtsp_st = rt->rtsp_streams[pkt->stream_index];
218  rtpctx = rtsp_st->transport_priv;
219 
220  ret = ff_write_chained(rtpctx, 0, pkt, s, 0);
221  /* ff_write_chained does all the RTP packetization. If using TCP as
222  * transport, rtpctx->pb is only a dyn_packet_buf that queues up the
223  * packets, so we need to send them out on the TCP connection separately.
224  */
226  ret = ff_rtsp_tcp_write_packet(s, rtsp_st);
227  return ret;
228 }
229 
231 {
232  RTSPState *rt = s->priv_data;
233 
234  // If we want to send RTCP_BYE packets, these are sent by av_write_trailer.
235  // Thus call this on all streams before doing the teardown. This is
236  // done within ff_rtsp_undo_setup.
237  ff_rtsp_undo_setup(s, 1);
238 
239  ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
240 
244  return 0;
245 }
246 
248  .p.name = "rtsp",
249  .p.long_name = NULL_IF_CONFIG_SMALL("RTSP output"),
250  .priv_data_size = sizeof(RTSPState),
251  .p.audio_codec = AV_CODEC_ID_AAC,
252  .p.video_codec = AV_CODEC_ID_MPEG4,
253  .write_header = rtsp_write_header,
254  .write_packet = rtsp_write_packet,
255  .write_trailer = rtsp_write_close,
256  .p.flags = AVFMT_NOFILE | AVFMT_GLOBALHEADER,
257  .p.priv_class = &rtsp_muxer_class,
258 };
ff_rtsp_read_reply
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're reading data interleave...
ff_rtsp_close_streams
void ff_rtsp_close_streams(AVFormatContext *s)
Close and free all streams within the RTSP (de)muxer.
Definition: rtsp.c:790
rtsp_muxer_class
static const AVClass rtsp_muxer_class
Definition: rtspenc.c:39
AVOutputFormat::name
const char * name
Definition: avformat.h:508
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame 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. Frame references ownership and permissions
RTSPStream::transport_priv
void * transport_priv
RTP/RDT parse context if input, RTP AVFormatContext if output.
Definition: rtsp.h:445
ff_rtsp_send_cmd_with_content
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.
RTSPMessageHeader::status_code
enum RTSPStatusCode status_code
response code from server
Definition: rtsp.h:132
ff_rtsp_send_cmd
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.
ff_rtsp_averror
static int ff_rtsp_averror(enum RTSPStatusCode status_code, int default_averror)
Definition: rtspcodes.h:144
AV_CODEC_ID_MPEG4
@ AV_CODEC_ID_MPEG4
Definition: codec_id.h:64
RTSPStream::interleaved_min
int interleaved_min
interleave IDs; copies of RTSPTransportField->interleaved_min/max for the selected transport.
Definition: rtsp.h:452
RTSPStream
Describe a single stream, as identified by a single m= line block in the SDP content.
Definition: rtsp.h:443
AV_LOG_VERBOSE
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:196
ff_rtsp_send_cmd_async
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.
ff_network_close
void ff_network_close(void)
Definition: network.c:116
av_strlcatf
size_t av_strlcatf(char *dst, size_t size, const char *fmt,...)
Definition: avstring.c:104
os_support.h
FFOutputFormat::p
AVOutputFormat p
The public AVOutputFormat.
Definition: mux.h:34
RTSPState::pkt_size
int pkt_size
Definition: rtsp.h:419
RTSPState::nb_rtsp_streams
int nb_rtsp_streams
number of items in the 'rtsp_streams' variable
Definition: rtsp.h:230
dynarray_add
#define dynarray_add(tab, nb_ptr, elem)
Definition: internal.h:424
RTSP_STATE_STREAMING
@ RTSP_STATE_STREAMING
initialized and sending/receiving data
Definition: rtsp.h:203
rtsp.h
RTSPStream::stream_index
int stream_index
corresponding stream index, if any.
Definition: rtsp.h:448
avio_close_dyn_buf
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:1520
RTSPState::rtsp_hd_out
URLContext * rtsp_hd_out
Additional output handle, used when input and output are done separately, eg for HTTP tunneling.
Definition: rtsp.h:335
ff_rtsp_muxer
const FFOutputFormat ff_rtsp_muxer
Definition: rtspenc.c:247
pkt
AVPacket * pkt
Definition: movenc.c:59
intreadwrite.h
s
#define s(width, name)
Definition: cbs_vp9.c:256
RTSPState::control_uri
char control_uri[MAX_URL_SIZE]
some MS RTSP streams contain a URL in the SDP that we need to use for all subsequent RTSP requests,...
Definition: rtsp.h:324
ff_url_join
int ff_url_join(char *str, int size, const char *proto, const char *authorization, const char *hostname, int port, const char *fmt,...)
Definition: url.c:38
ff_rtsp_undo_setup
void ff_rtsp_undo_setup(AVFormatContext *s, int send_packets)
Undo the effect of ff_rtsp_make_setup_request, close the transport_priv and rtp_handle fields.
Definition: rtsp.c:758
AVFormatContext
Format I/O context.
Definition: avformat.h:1104
internal.h
LIBAVUTIL_VERSION_INT
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
RTSP_STATUS_OK
@ RTSP_STATUS_OK
Definition: rtspcodes.h:33
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:66
NULL
#define NULL
Definition: coverity.c:32
RTSPState::rtsp_hd
URLContext * rtsp_hd
Definition: rtsp.h:227
ff_rtsp_tcp_write_packet
int ff_rtsp_tcp_write_packet(AVFormatContext *s, RTSPStream *rtsp_st)
Send buffered packets over TCP.
Definition: rtspenc.c:142
AV_WB16
#define AV_WB16(p, v)
Definition: intreadwrite.h:405
av_default_item_name
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:237
AVFormatContext::pb
AVIOContext * pb
I/O context.
Definition: avformat.h:1146
FFOutputFormat
Definition: mux.h:30
SDP_MAX_SIZE
#define SDP_MAX_SIZE
Definition: rtsp.h:80
time.h
RTSPState::state
enum RTSPClientState state
indicator of whether we are currently receiving data from the server.
Definition: rtsp.h:238
rtsp_write_record
static int rtsp_write_record(AVFormatContext *s)
Definition: rtspenc.c:111
rtsp_write_header
static int rtsp_write_header(AVFormatContext *s)
Definition: rtspenc.c:126
rtsp_write_close
static int rtsp_write_close(AVFormatContext *s)
Definition: rtspenc.c:230
AV_CODEC_ID_AAC
@ AV_CODEC_ID_AAC
Definition: codec_id.h:440
RTP_PT_IS_RTCP
#define RTP_PT_IS_RTCP(x)
Definition: rtp.h:112
NULL_IF_CONFIG_SMALL
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:115
ff_rtsp_options
const AVOption ff_rtsp_options[]
Definition: rtsp.c:84
ff_rtsp_close_connections
void ff_rtsp_close_connections(AVFormatContext *s)
Close all connection handles within the RTSP (de)muxer.
RTSPState
Private data for the RTSP demuxer.
Definition: rtsp.h:225
RTSPState::lower_transport
enum RTSPLowerTransport lower_transport
the negotiated network layer transport protocol; e.g.
Definition: rtsp.h:269
AVFormatContext::url
char * url
input or output URL.
Definition: avformat.h:1187
size
int size
Definition: twinvq_data.h:10344
RTSPState::rtsp_streams
struct RTSPStream ** rtsp_streams
streams in this session
Definition: rtsp.h:232
AV_NOPTS_VALUE
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
AV_RB32
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_RB32
Definition: bytestream.h:96
ff_rtsp_skip_packet
int ff_rtsp_skip_packet(AVFormatContext *s)
Skip a RTP/TCP interleaved packet.
AVFMT_NOFILE
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:468
ffio_open_dyn_packet_buf
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 'max_packet_size'.
Definition: aviobuf.c:1480
av_sdp_create
int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size)
Generate an SDP for an RTP session.
Definition: sdp.c:911
AVFMT_GLOBALHEADER
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:478
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:269
avio_internal.h
url.h
av_mallocz
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:254
RTSP_LOWER_TRANSPORT_TCP
@ RTSP_LOWER_TRANSPORT_TCP
TCP; interleaved in RTSP.
Definition: rtsp.h:40
ret
ret
Definition: filter_design.txt:187
AVClass::class_name
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:71
avformat.h
network.h
id
enum AVCodecID id
Definition: dts2pts_bsf.c:364
MAX_URL_SIZE
#define MAX_URL_SIZE
Definition: internal.h:31
RTSPStream::control_url
char control_url[MAX_URL_SIZE]
url for this stream (from SDP)
Definition: rtsp.h:454
RTSPStream::interleaved_max
int interleaved_max
Definition: rtsp.h:452
ffurl_write
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:415
RTSPMessageHeader
This describes the server response to each RTSP command.
Definition: rtsp.h:128
AVPacket::stream_index
int stream_index
Definition: packet.h:376
ff_rtsp_setup_output_streams
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
av_gettime
int64_t av_gettime(void)
Get the current time in microseconds.
Definition: time.c:39
rtsp_write_packet
static int rtsp_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: rtspenc.c:181
av_free
#define av_free(p)
Definition: tableprint_vlc.h:33
AVPacket
This structure stores compressed data.
Definition: packet.h:351
av_strlcpy
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:86
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
AVERROR_INVALIDDATA
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:61
avstring.h
ff_rtsp_connect
int ff_rtsp_connect(AVFormatContext *s)
Connect to the RTSP server and set up the individual media streams.
snprintf
#define snprintf
Definition: snprintf.h:34
ffurl_get_file_handle
int ffurl_get_file_handle(URLContext *h)
Return the file descriptor associated with this URL.
Definition: avio.c:626
mux.h
ff_write_chained
int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt, AVFormatContext *src, int interleave)
Write a packet to another muxer than the one the user originally intended.
Definition: mux.c:1355