FFmpeg
sapenc.c
Go to the documentation of this file.
1 /*
2  * Session Announcement Protocol (RFC 2974) 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 #include "libavutil/parseutils.h"
24 #include "libavutil/random_seed.h"
25 #include "libavutil/avstring.h"
26 #include "libavutil/dict.h"
27 #include "libavutil/intreadwrite.h"
28 #include "libavutil/time.h"
29 #include "internal.h"
30 #include "network.h"
31 #include "os_support.h"
32 #include "rtpenc_chain.h"
33 #include "url.h"
34 
35 struct SAPState {
37  int ann_size;
39  int64_t last_time;
40 };
41 
43 {
44  struct SAPState *sap = s->priv_data;
45  int i;
46 
47  for (i = 0; i < s->nb_streams; i++) {
48  AVFormatContext *rtpctx = s->streams[i]->priv_data;
49  if (!rtpctx)
50  continue;
51  av_write_trailer(rtpctx);
52  avio_closep(&rtpctx->pb);
53  avformat_free_context(rtpctx);
54  s->streams[i]->priv_data = NULL;
55  }
56 
57  if (sap->last_time && sap->ann && sap->ann_fd) {
58  sap->ann[0] |= 4; /* Session deletion*/
59  ffurl_write(sap->ann_fd, sap->ann, sap->ann_size);
60  }
61 
62  av_freep(&sap->ann);
63  ffurl_closep(&sap->ann_fd);
65  return 0;
66 }
67 
69 {
70  struct SAPState *sap = s->priv_data;
71  char host[1024], path[1024], url[1024], announce_addr[50] = "";
72  char *option_list;
73  int port = 9875, base_port = 5004, i, pos = 0, same_port = 0, ttl = 255;
74  AVFormatContext **contexts = NULL;
75  int ret = 0;
76  struct sockaddr_storage localaddr;
77  socklen_t addrlen = sizeof(localaddr);
78  int udp_fd;
79  AVDictionaryEntry* title = av_dict_get(s->metadata, "title", NULL, 0);
80 
81  if (!ff_network_init())
82  return AVERROR(EIO);
83 
84  /* extract hostname and port */
85  av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &base_port,
86  path, sizeof(path), s->url);
87  if (base_port < 0)
88  base_port = 5004;
89 
90  /* search for options */
91  option_list = strrchr(path, '?');
92  if (option_list) {
93  char buf[50];
94  if (av_find_info_tag(buf, sizeof(buf), "announce_port", option_list)) {
95  port = strtol(buf, NULL, 10);
96  }
97  if (av_find_info_tag(buf, sizeof(buf), "same_port", option_list)) {
98  same_port = strtol(buf, NULL, 10);
99  }
100  if (av_find_info_tag(buf, sizeof(buf), "ttl", option_list)) {
101  ttl = strtol(buf, NULL, 10);
102  }
103  if (av_find_info_tag(buf, sizeof(buf), "announce_addr", option_list)) {
104  av_strlcpy(announce_addr, buf, sizeof(announce_addr));
105  }
106  }
107 
108  if (!announce_addr[0]) {
109  struct addrinfo hints = { 0 }, *ai = NULL;
110  hints.ai_family = AF_UNSPEC;
111  if (getaddrinfo(host, NULL, &hints, &ai)) {
112  av_log(s, AV_LOG_ERROR, "Unable to resolve %s\n", host);
113  ret = AVERROR(EIO);
114  goto fail;
115  }
116  if (ai->ai_family == AF_INET) {
117  /* Also known as sap.mcast.net */
118  av_strlcpy(announce_addr, "224.2.127.254", sizeof(announce_addr));
119 #if HAVE_STRUCT_SOCKADDR_IN6
120  } else if (ai->ai_family == AF_INET6) {
121  /* With IPv6, you can use the same destination in many different
122  * multicast subnets, to choose how far you want it routed.
123  * This one is intended to be routed globally. */
124  av_strlcpy(announce_addr, "ff0e::2:7ffe", sizeof(announce_addr));
125 #endif
126  } else {
127  freeaddrinfo(ai);
128  av_log(s, AV_LOG_ERROR, "Host %s resolved to unsupported "
129  "address family\n", host);
130  ret = AVERROR(EIO);
131  goto fail;
132  }
133  freeaddrinfo(ai);
134  }
135 
136  contexts = av_mallocz_array(s->nb_streams, sizeof(AVFormatContext*));
137  if (!contexts) {
138  ret = AVERROR(ENOMEM);
139  goto fail;
140  }
141 
144  for (i = 0; i < s->nb_streams; i++) {
145  URLContext *fd;
146  char *new_url;
147 
148  ff_url_join(url, sizeof(url), "rtp", NULL, host, base_port,
149  "?ttl=%d", ttl);
150  if (!same_port)
151  base_port += 2;
152  ret = ffurl_open_whitelist(&fd, url, AVIO_FLAG_WRITE,
155  if (ret) {
156  ret = AVERROR(EIO);
157  goto fail;
158  }
159  ret = ff_rtp_chain_mux_open(&contexts[i], s, s->streams[i], fd, 0, i);
160  if (ret < 0)
161  goto fail;
162  s->streams[i]->priv_data = contexts[i];
163  s->streams[i]->time_base = contexts[i]->streams[0]->time_base;
164  new_url = av_strdup(url);
165  if (!new_url) {
166  ret = AVERROR(ENOMEM);
167  goto fail;
168  }
169  ff_format_set_url(contexts[i], new_url);
170  }
171 
172  if (s->nb_streams > 0 && title)
173  av_dict_set(&contexts[0]->metadata, "title", title->value, 0);
174 
175  ff_url_join(url, sizeof(url), "udp", NULL, announce_addr, port,
176  "?ttl=%d&connect=1", ttl);
177  ret = ffurl_open_whitelist(&sap->ann_fd, url, AVIO_FLAG_WRITE,
180  if (ret) {
181  ret = AVERROR(EIO);
182  goto fail;
183  }
184 
185  udp_fd = ffurl_get_file_handle(sap->ann_fd);
186  if (getsockname(udp_fd, (struct sockaddr*) &localaddr, &addrlen)) {
187  ret = AVERROR(EIO);
188  goto fail;
189  }
190  if (localaddr.ss_family != AF_INET
191 #if HAVE_STRUCT_SOCKADDR_IN6
192  && localaddr.ss_family != AF_INET6
193 #endif
194  ) {
195  av_log(s, AV_LOG_ERROR, "Unsupported protocol family\n");
196  ret = AVERROR(EIO);
197  goto fail;
198  }
199  sap->ann_size = 8192;
200  sap->ann = av_mallocz(sap->ann_size);
201  if (!sap->ann) {
202  ret = AVERROR(EIO);
203  goto fail;
204  }
205  sap->ann[pos] = (1 << 5);
206 #if HAVE_STRUCT_SOCKADDR_IN6
207  if (localaddr.ss_family == AF_INET6)
208  sap->ann[pos] |= 0x10;
209 #endif
210  pos++;
211  sap->ann[pos++] = 0; /* Authentication length */
212  AV_WB16(&sap->ann[pos], av_get_random_seed());
213  pos += 2;
214  if (localaddr.ss_family == AF_INET) {
215  memcpy(&sap->ann[pos], &((struct sockaddr_in*)&localaddr)->sin_addr,
216  sizeof(struct in_addr));
217  pos += sizeof(struct in_addr);
218 #if HAVE_STRUCT_SOCKADDR_IN6
219  } else {
220  memcpy(&sap->ann[pos], &((struct sockaddr_in6*)&localaddr)->sin6_addr,
221  sizeof(struct in6_addr));
222  pos += sizeof(struct in6_addr);
223 #endif
224  }
225 
226  av_strlcpy(&sap->ann[pos], "application/sdp", sap->ann_size - pos);
227  pos += strlen(&sap->ann[pos]) + 1;
228 
229  if (av_sdp_create(contexts, s->nb_streams, &sap->ann[pos],
230  sap->ann_size - pos)) {
231  ret = AVERROR_INVALIDDATA;
232  goto fail;
233  }
234  av_freep(&contexts);
235  av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", &sap->ann[pos]);
236  pos += strlen(&sap->ann[pos]);
237  sap->ann_size = pos;
238 
239  if (sap->ann_size > sap->ann_fd->max_packet_size) {
240  av_log(s, AV_LOG_ERROR, "Announcement too large to send in one "
241  "packet\n");
242  goto fail;
243  }
244 
245  return 0;
246 
247 fail:
248  av_free(contexts);
249  sap_write_close(s);
250  return ret;
251 }
252 
254 {
255  AVFormatContext *rtpctx;
256  struct SAPState *sap = s->priv_data;
257  int64_t now = av_gettime_relative();
258 
259  if (!sap->last_time || now - sap->last_time > 5000000) {
260  int ret = ffurl_write(sap->ann_fd, sap->ann, sap->ann_size);
261  /* Don't abort even if we get "Destination unreachable" */
262  if (ret < 0 && ret != AVERROR(ECONNREFUSED))
263  return ret;
264  sap->last_time = now;
265  }
266  rtpctx = s->streams[pkt->stream_index]->priv_data;
267  return ff_write_chained(rtpctx, 0, pkt, s, 0);
268 }
269 
271  .name = "sap",
272  .long_name = NULL_IF_CONFIG_SMALL("SAP output"),
273  .priv_data_size = sizeof(struct SAPState),
274  .audio_codec = AV_CODEC_ID_AAC,
275  .video_codec = AV_CODEC_ID_MPEG4,
276  .write_header = sap_write_header,
277  .write_packet = sap_write_packet,
278  .write_trailer = sap_write_close,
279  .flags = AVFMT_NOFILE | AVFMT_GLOBALHEADER,
280 };
void av_url_split(char *proto, int proto_size, char *authorization, int authorization_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url)
Split a URL string into components.
Definition: utils.c:4722
#define NULL
Definition: coverity.c:32
#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:1608
int ffurl_open_whitelist(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options, const char *whitelist, const char *blacklist, URLContext *parent)
Create an URLContext for accessing to the resource indicated by url, and open it. ...
Definition: avio.c:310
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1633
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:423
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:1305
int64_t last_time
Definition: sapenc.c:39
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:675
void ff_network_close(void)
Definition: network.c:116
void * priv_data
Definition: avformat.h:895
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:237
#define freeaddrinfo
Definition: network.h:218
static AVPacket pkt
AVOutputFormat ff_sap_muxer
Definition: sapenc.c:270
Format I/O context.
Definition: avformat.h:1355
static int sap_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: sapenc.c:253
Public dictionary API.
uint8_t
int ff_network_init(void)
Definition: network.c:58
miscellaneous OS support macros and functions.
uint16_t ss_family
Definition: network.h:116
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1423
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:40
char * protocol_whitelist
&#39;,&#39; separated list of allowed protocols.
Definition: avformat.h:1915
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:210
int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size)
Generate an SDP for an RTP session.
Definition: sdp.c:846
int av_find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
Attempt to find a specific tag in a URL.
Definition: parseutils.c:749
#define AV_WB16(p, v)
Definition: intreadwrite.h:405
#define av_log(a,...)
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:194
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1595
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:153
char * url
input or output URL.
Definition: avformat.h:1451
unsigned int pos
Definition: spdifenc.c:410
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:83
#define fail()
Definition: checkasm.h:123
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1411
URLContext * ann_fd
Definition: sapdec.c:37
uint8_t * ann
Definition: sapenc.c:36
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:461
const char * name
Definition: avformat.h:500
static int sap_write_close(AVFormatContext *s)
Definition: sapenc.c:42
#define s(width, name)
Definition: cbs_vp9.c:257
void ff_format_set_url(AVFormatContext *s, char *url)
Set AVFormatContext url field to the provided pointer.
Definition: utils.c:5785
int ffurl_get_file_handle(URLContext *h)
Return the file descriptor associated with this URL.
Definition: avio.c:628
int ffurl_closep(URLContext **hh)
Close the resource accessed by the URLContext h, and free the memory used by it.
Definition: avio.c:446
int64_t av_gettime(void)
Get the current time in microseconds.
Definition: time.c:39
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
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:253
static int sap_write_header(AVFormatContext *s)
Definition: sapenc.c:68
int ann_size
Definition: sapenc.c:37
AVIOContext * pb
I/O context.
Definition: avformat.h:1397
Definition: url.h:38
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:70
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:4378
misc parsing utilities
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition: time.c:56
#define getaddrinfo
Definition: network.h:217
Main libavformat public API header.
int ff_rtp_chain_mux_open(AVFormatContext **out, AVFormatContext *s, AVStream *st, URLContext *handle, int packet_size, int idx)
Definition: rtpenc_chain.c:28
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:458
#define av_free(p)
char * value
Definition: dict.h:87
void * priv_data
Format private data.
Definition: avformat.h:1383
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:1251
char * protocol_blacklist
&#39;,&#39; separated list of disallowed protocols.
Definition: avformat.h:1950
int max_packet_size
if non zero, the stream is packetized with this max packet size
Definition: url.h:44
#define av_freep(p)
unbuffered private I/O API
uint32_t av_get_random_seed(void)
Get a seed to use in conjunction with random functions.
Definition: random_seed.c:120
int stream_index
Definition: packet.h:365
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:909
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
This structure stores compressed data.
Definition: packet.h:340
int avio_closep(AVIOContext **s)
Close the resource accessed by the AVIOContext *s, free it and set the pointer pointing to it to NULL...
Definition: aviobuf.c:1194
int i
Definition: input.c:407
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
void * av_mallocz_array(size_t nmemb, size_t size)
Definition: mem.c:190
int ai_family
Definition: network.h:139