Libav
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 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 "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  const URLProtocol **protocols;
42 };
43 
45 {
46  struct SAPState *sap = s->priv_data;
47  int i;
48 
49  for (i = 0; i < s->nb_streams; i++) {
50  AVFormatContext *rtpctx = s->streams[i]->priv_data;
51  if (!rtpctx)
52  continue;
53  av_write_trailer(rtpctx);
54  avio_close(rtpctx->pb);
55  avformat_free_context(rtpctx);
56  s->streams[i]->priv_data = NULL;
57  }
58 
59  if (sap->last_time && sap->ann && sap->ann_fd) {
60  sap->ann[0] |= 4; /* Session deletion*/
61  ffurl_write(sap->ann_fd, sap->ann, sap->ann_size);
62  }
63 
64  av_freep(&sap->protocols);
65 
66  av_freep(&sap->ann);
67  if (sap->ann_fd)
68  ffurl_close(sap->ann_fd);
70  return 0;
71 }
72 
74 {
75  struct SAPState *sap = s->priv_data;
76  char host[1024], path[1024], url[1024], announce_addr[50] = "";
77  char *option_list;
78  int port = 9875, base_port = 5004, i, pos = 0, same_port = 0, ttl = 255;
79  AVFormatContext **contexts = NULL;
80  int ret = 0;
81  struct sockaddr_storage localaddr;
82  socklen_t addrlen = sizeof(localaddr);
83  int udp_fd;
84  AVDictionaryEntry* title = av_dict_get(s->metadata, "title", NULL, 0);
85 
86  if (!ff_network_init())
87  return AVERROR(EIO);
88 
89  /* extract hostname and port */
90  av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &base_port,
91  path, sizeof(path), s->filename);
92  if (base_port < 0)
93  base_port = 5004;
94 
95  /* search for options */
96  option_list = strrchr(path, '?');
97  if (option_list) {
98  char buf[50];
99  if (av_find_info_tag(buf, sizeof(buf), "announce_port", option_list)) {
100  port = strtol(buf, NULL, 10);
101  }
102  if (av_find_info_tag(buf, sizeof(buf), "same_port", option_list)) {
103  same_port = strtol(buf, NULL, 10);
104  }
105  if (av_find_info_tag(buf, sizeof(buf), "ttl", option_list)) {
106  ttl = strtol(buf, NULL, 10);
107  }
108  if (av_find_info_tag(buf, sizeof(buf), "announce_addr", option_list)) {
109  av_strlcpy(announce_addr, buf, sizeof(announce_addr));
110  }
111  }
112 
113  if (!announce_addr[0]) {
114  struct addrinfo hints = { 0 }, *ai = NULL;
115  hints.ai_family = AF_UNSPEC;
116  if (getaddrinfo(host, NULL, &hints, &ai)) {
117  av_log(s, AV_LOG_ERROR, "Unable to resolve %s\n", host);
118  ret = AVERROR(EIO);
119  goto fail;
120  }
121  if (ai->ai_family == AF_INET) {
122  /* Also known as sap.mcast.net */
123  av_strlcpy(announce_addr, "224.2.127.254", sizeof(announce_addr));
124 #if HAVE_STRUCT_SOCKADDR_IN6
125  } else if (ai->ai_family == AF_INET6) {
126  /* With IPv6, you can use the same destination in many different
127  * multicast subnets, to choose how far you want it routed.
128  * This one is intended to be routed globally. */
129  av_strlcpy(announce_addr, "ff0e::2:7ffe", sizeof(announce_addr));
130 #endif
131  } else {
132  freeaddrinfo(ai);
133  av_log(s, AV_LOG_ERROR, "Host %s resolved to unsupported "
134  "address family\n", host);
135  ret = AVERROR(EIO);
136  goto fail;
137  }
138  freeaddrinfo(ai);
139  }
140 
142  s->protocol_blacklist);
143  if (!sap->protocols) {
144  ret = AVERROR(ENOMEM);
145  goto fail;
146  }
147 
148  contexts = av_mallocz(sizeof(AVFormatContext*) * s->nb_streams);
149  if (!contexts) {
150  ret = AVERROR(ENOMEM);
151  goto fail;
152  }
153 
155  for (i = 0; i < s->nb_streams; i++) {
156  URLContext *fd;
157 
158  ff_url_join(url, sizeof(url), "rtp", NULL, host, base_port,
159  "?ttl=%d", ttl);
160  if (!same_port)
161  base_port += 2;
162  ret = ffurl_open(&fd, url, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL,
163  sap->protocols, NULL);
164  if (ret) {
165  ret = AVERROR(EIO);
166  goto fail;
167  }
168  ret = ff_rtp_chain_mux_open(&contexts[i], s, s->streams[i], fd, 0, i);
169  if (ret < 0)
170  goto fail;
171  s->streams[i]->priv_data = contexts[i];
172  s->streams[i]->time_base = contexts[i]->streams[0]->time_base;
173  av_strlcpy(contexts[i]->filename, url, sizeof(contexts[i]->filename));
174  }
175 
176  if (s->nb_streams > 0 && title)
177  av_dict_set(&contexts[0]->metadata, "title", title->value, 0);
178 
179  ff_url_join(url, sizeof(url), "udp", NULL, announce_addr, port,
180  "?ttl=%d&connect=1", ttl);
181  ret = ffurl_open(&sap->ann_fd, url, AVIO_FLAG_WRITE,
182  &s->interrupt_callback, NULL, sap->protocols, NULL);
183  if (ret) {
184  ret = AVERROR(EIO);
185  goto fail;
186  }
187 
188  udp_fd = ffurl_get_file_handle(sap->ann_fd);
189  if (getsockname(udp_fd, (struct sockaddr*) &localaddr, &addrlen)) {
190  ret = AVERROR(EIO);
191  goto fail;
192  }
193  if (localaddr.ss_family != AF_INET
195  && localaddr.ss_family != AF_INET6
196 #endif
197  ) {
198  av_log(s, AV_LOG_ERROR, "Unsupported protocol family\n");
199  ret = AVERROR(EIO);
200  goto fail;
201  }
202  sap->ann_size = 8192;
203  sap->ann = av_mallocz(sap->ann_size);
204  if (!sap->ann) {
205  ret = AVERROR(EIO);
206  goto fail;
207  }
208  sap->ann[pos] = (1 << 5);
209 #if HAVE_STRUCT_SOCKADDR_IN6
210  if (localaddr.ss_family == AF_INET6)
211  sap->ann[pos] |= 0x10;
212 #endif
213  pos++;
214  sap->ann[pos++] = 0; /* Authentication length */
215  AV_WB16(&sap->ann[pos], av_get_random_seed());
216  pos += 2;
217  if (localaddr.ss_family == AF_INET) {
218  memcpy(&sap->ann[pos], &((struct sockaddr_in*)&localaddr)->sin_addr,
219  sizeof(struct in_addr));
220  pos += sizeof(struct in_addr);
221 #if HAVE_STRUCT_SOCKADDR_IN6
222  } else {
223  memcpy(&sap->ann[pos], &((struct sockaddr_in6*)&localaddr)->sin6_addr,
224  sizeof(struct in6_addr));
225  pos += sizeof(struct in6_addr);
226 #endif
227  }
228 
229  av_strlcpy(&sap->ann[pos], "application/sdp", sap->ann_size - pos);
230  pos += strlen(&sap->ann[pos]) + 1;
231 
232  if (av_sdp_create(contexts, s->nb_streams, &sap->ann[pos],
233  sap->ann_size - pos)) {
234  ret = AVERROR_INVALIDDATA;
235  goto fail;
236  }
237  av_freep(&contexts);
238  av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", &sap->ann[pos]);
239  pos += strlen(&sap->ann[pos]);
240  sap->ann_size = pos;
241 
242  if (sap->ann_size > sap->ann_fd->max_packet_size) {
243  av_log(s, AV_LOG_ERROR, "Announcement too large to send in one "
244  "packet\n");
245  goto fail;
246  }
247 
248  return 0;
249 
250 fail:
251  av_free(contexts);
252  sap_write_close(s);
253  return ret;
254 }
255 
257 {
258  AVFormatContext *rtpctx;
259  struct SAPState *sap = s->priv_data;
260  int64_t now = av_gettime_relative();
261 
262  if (!sap->last_time || now - sap->last_time > 5000000) {
263  int ret = ffurl_write(sap->ann_fd, sap->ann, sap->ann_size);
264  /* Don't abort even if we get "Destination unreachable" */
265  if (ret < 0 && ret != AVERROR(ECONNREFUSED))
266  return ret;
267  sap->last_time = now;
268  }
269  rtpctx = s->streams[pkt->stream_index]->priv_data;
270  return ff_write_chained(rtpctx, 0, pkt, s);
271 }
272 
274  .name = "sap",
275  .long_name = NULL_IF_CONFIG_SMALL("SAP output"),
276  .priv_data_size = sizeof(struct SAPState),
277  .audio_codec = AV_CODEC_ID_AAC,
278  .video_codec = AV_CODEC_ID_MPEG4,
279  .write_header = sap_write_header,
280  .write_packet = sap_write_packet,
281  .write_trailer = sap_write_close,
282  .flags = AVFMT_NOFILE | AVFMT_GLOBALHEADER,
283 };
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:2870
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:54
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:1156
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1181
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:257
int64_t last_time
Definition: sapenc.c:39
av_log(ac->avr, AV_LOG_TRACE, "%d samples - audio_convert: %s to %s (%s)\, len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt), use_generic ? ac->func_descr_generic :ac->func_descr)
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:369
void ff_network_close(void)
Definition: network.c:77
void * priv_data
Definition: avformat.h:720
#define freeaddrinfo
Definition: network.h:187
AVOutputFormat ff_sap_muxer
Definition: sapenc.c:273
void av_freep(void *arg)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:202
Format I/O context.
Definition: avformat.h:940
static int sap_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: sapenc.c:256
Public dictionary API.
uint8_t
int ff_network_init(void)
Definition: network.c:50
miscellaneous OS support macros and functions.
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1008
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:38
char * protocol_whitelist
A comma-separated list of protocol names that can be used internally by libavformat.
Definition: avformat.h:1294
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:140
int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size)
Generate an SDP for an RTP session.
Definition: sdp.c:805
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:619
int ffurl_open(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options, const URLProtocol **protocols, URLContext *parent)
Create an URLContext for accessing to the resource indicated by url, and open it. ...
Definition: avio.c:175
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:124
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1148
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:190
#define AVERROR(e)
Definition: error.h:43
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:148
int avio_close(AVIOContext *s)
Close the resource accessed by the AVIOContext s and free it.
Definition: aviobuf.c:983
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:81
#define fail()
Definition: checkasm.h:80
#define HAVE_STRUCT_SOCKADDR_IN6
Definition: config.h:308
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:996
char filename[1024]
input or output filename
Definition: avformat.h:1016
URLContext * ann_fd
Definition: sapdec.c:36
uint8_t * ann
Definition: sapenc.c:36
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:419
const char * name
Definition: avformat.h:450
static int sap_write_close(AVFormatContext *s)
Definition: sapenc.c:44
int ffurl_get_file_handle(URLContext *h)
Return the file descriptor associated with this URL.
Definition: avio.c:345
int64_t av_gettime(void)
Get the current time in microseconds.
Definition: time.c:40
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:36
NULL
Definition: eval.c:55
static int sap_write_header(AVFormatContext *s)
Definition: sapenc.c:73
const URLProtocol ** protocols
Definition: sapdec.c:43
int ann_size
Definition: sapenc.c:37
AVIOContext * pb
I/O context.
Definition: avformat.h:982
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:68
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:2594
misc parsing utilities
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition: time.c:57
int ffurl_close(URLContext *h)
Close the resource accessed by the URLContext h, and free the memory used by it.
Definition: avio.c:280
#define getaddrinfo
Definition: network.h:186
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:29
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:412
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.
Definition: mux.c:755
char * value
Definition: dict.h:74
void * priv_data
Format private data.
Definition: avformat.h:968
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:714
char * protocol_blacklist
A comma-separated list of protocol names that will not be used internally by libavformat.
Definition: avformat.h:1285
int max_packet_size
if non zero, the stream is packetized with this max packet size
Definition: url.h:48
unbuffered private I/O API
uint32_t av_get_random_seed(void)
Get random data.
Definition: random_seed.c:95
int stream_index
Definition: avcodec.h:1348
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:742
#define AV_WB16(p, val)
Definition: intreadwrite.h:218
const URLProtocol ** ffurl_get_protocols(const char *whitelist, const char *blacklist)
Construct a list of protocols matching a given whitelist and/or blacklist.
Definition: protocols.c:98
This structure stores compressed data.
Definition: avcodec.h:1323
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:211
int ai_family
Definition: network.h:108