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  if (sap->ann_fd)
64  ffurl_close(sap->ann_fd);
66  return 0;
67 }
68 
70 {
71  struct SAPState *sap = s->priv_data;
72  char host[1024], path[1024], url[1024], announce_addr[50] = "";
73  char *option_list;
74  int port = 9875, base_port = 5004, i, pos = 0, same_port = 0, ttl = 255;
75  AVFormatContext **contexts = NULL;
76  int ret = 0;
77  struct sockaddr_storage localaddr;
78  socklen_t addrlen = sizeof(localaddr);
79  int udp_fd;
80  AVDictionaryEntry* title = av_dict_get(s->metadata, "title", NULL, 0);
81 
82  if (!ff_network_init())
83  return AVERROR(EIO);
84 
85  /* extract hostname and port */
86  av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &base_port,
87  path, sizeof(path), s->url);
88  if (base_port < 0)
89  base_port = 5004;
90 
91  /* search for options */
92  option_list = strrchr(path, '?');
93  if (option_list) {
94  char buf[50];
95  if (av_find_info_tag(buf, sizeof(buf), "announce_port", option_list)) {
96  port = strtol(buf, NULL, 10);
97  }
98  if (av_find_info_tag(buf, sizeof(buf), "same_port", option_list)) {
99  same_port = strtol(buf, NULL, 10);
100  }
101  if (av_find_info_tag(buf, sizeof(buf), "ttl", option_list)) {
102  ttl = strtol(buf, NULL, 10);
103  }
104  if (av_find_info_tag(buf, sizeof(buf), "announce_addr", option_list)) {
105  av_strlcpy(announce_addr, buf, sizeof(announce_addr));
106  }
107  }
108 
109  if (!announce_addr[0]) {
110  struct addrinfo hints = { 0 }, *ai = NULL;
111  hints.ai_family = AF_UNSPEC;
112  if (getaddrinfo(host, NULL, &hints, &ai)) {
113  av_log(s, AV_LOG_ERROR, "Unable to resolve %s\n", host);
114  ret = AVERROR(EIO);
115  goto fail;
116  }
117  if (ai->ai_family == AF_INET) {
118  /* Also known as sap.mcast.net */
119  av_strlcpy(announce_addr, "224.2.127.254", sizeof(announce_addr));
120 #if HAVE_STRUCT_SOCKADDR_IN6
121  } else if (ai->ai_family == AF_INET6) {
122  /* With IPv6, you can use the same destination in many different
123  * multicast subnets, to choose how far you want it routed.
124  * This one is intended to be routed globally. */
125  av_strlcpy(announce_addr, "ff0e::2:7ffe", sizeof(announce_addr));
126 #endif
127  } else {
128  freeaddrinfo(ai);
129  av_log(s, AV_LOG_ERROR, "Host %s resolved to unsupported "
130  "address family\n", host);
131  ret = AVERROR(EIO);
132  goto fail;
133  }
134  freeaddrinfo(ai);
135  }
136 
137  contexts = av_mallocz_array(s->nb_streams, sizeof(AVFormatContext*));
138  if (!contexts) {
139  ret = AVERROR(ENOMEM);
140  goto fail;
141  }
142 
143  if (s->start_time_realtime == 0 || s->start_time_realtime == AV_NOPTS_VALUE)
144  s->start_time_realtime = av_gettime();
145  for (i = 0; i < s->nb_streams; i++) {
146  URLContext *fd;
147  char *new_url;
148 
149  ff_url_join(url, sizeof(url), "rtp", NULL, host, base_port,
150  "?ttl=%d", ttl);
151  if (!same_port)
152  base_port += 2;
154  &s->interrupt_callback, NULL,
155  s->protocol_whitelist, s->protocol_blacklist, NULL);
156  if (ret) {
157  ret = AVERROR(EIO);
158  goto fail;
159  }
160  ret = ff_rtp_chain_mux_open(&contexts[i], s, s->streams[i], fd, 0, i);
161  if (ret < 0)
162  goto fail;
163  s->streams[i]->priv_data = contexts[i];
164  s->streams[i]->time_base = contexts[i]->streams[0]->time_base;
165  new_url = av_strdup(url);
166  if (!new_url) {
167  ret = AVERROR(ENOMEM);
168  goto fail;
169  }
170  ff_format_set_url(contexts[i], new_url);
171  }
172 
173  if (s->nb_streams > 0 && title)
174  av_dict_set(&contexts[0]->metadata, "title", title->value, 0);
175 
176  ff_url_join(url, sizeof(url), "udp", NULL, announce_addr, port,
177  "?ttl=%d&connect=1", ttl);
179  &s->interrupt_callback, NULL,
180  s->protocol_whitelist, s->protocol_blacklist, NULL);
181  if (ret) {
182  ret = AVERROR(EIO);
183  goto fail;
184  }
185 
186  udp_fd = ffurl_get_file_handle(sap->ann_fd);
187  if (getsockname(udp_fd, (struct sockaddr*) &localaddr, &addrlen)) {
188  ret = AVERROR(EIO);
189  goto fail;
190  }
191  if (localaddr.ss_family != AF_INET
192 #if HAVE_STRUCT_SOCKADDR_IN6
193  && localaddr.ss_family != AF_INET6
194 #endif
195  ) {
196  av_log(s, AV_LOG_ERROR, "Unsupported protocol family\n");
197  ret = AVERROR(EIO);
198  goto fail;
199  }
200  sap->ann_size = 8192;
201  sap->ann = av_mallocz(sap->ann_size);
202  if (!sap->ann) {
203  ret = AVERROR(EIO);
204  goto fail;
205  }
206  sap->ann[pos] = (1 << 5);
207 #if HAVE_STRUCT_SOCKADDR_IN6
208  if (localaddr.ss_family == AF_INET6)
209  sap->ann[pos] |= 0x10;
210 #endif
211  pos++;
212  sap->ann[pos++] = 0; /* Authentication length */
213  AV_WB16(&sap->ann[pos], av_get_random_seed());
214  pos += 2;
215  if (localaddr.ss_family == AF_INET) {
216  memcpy(&sap->ann[pos], &((struct sockaddr_in*)&localaddr)->sin_addr,
217  sizeof(struct in_addr));
218  pos += sizeof(struct in_addr);
219 #if HAVE_STRUCT_SOCKADDR_IN6
220  } else {
221  memcpy(&sap->ann[pos], &((struct sockaddr_in6*)&localaddr)->sin6_addr,
222  sizeof(struct in6_addr));
223  pos += sizeof(struct in6_addr);
224 #endif
225  }
226 
227  av_strlcpy(&sap->ann[pos], "application/sdp", sap->ann_size - pos);
228  pos += strlen(&sap->ann[pos]) + 1;
229 
230  if (av_sdp_create(contexts, s->nb_streams, &sap->ann[pos],
231  sap->ann_size - pos)) {
233  goto fail;
234  }
235  av_freep(&contexts);
236  av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", &sap->ann[pos]);
237  pos += strlen(&sap->ann[pos]);
238  sap->ann_size = pos;
239 
240  if (sap->ann_size > sap->ann_fd->max_packet_size) {
241  av_log(s, AV_LOG_ERROR, "Announcement too large to send in one "
242  "packet\n");
243  goto fail;
244  }
245 
246  return 0;
247 
248 fail:
249  av_free(contexts);
251  return ret;
252 }
253 
255 {
256  AVFormatContext *rtpctx;
257  struct SAPState *sap = s->priv_data;
258  int64_t now = av_gettime_relative();
259 
260  if (!sap->last_time || now - sap->last_time > 5000000) {
261  int ret = ffurl_write(sap->ann_fd, sap->ann, sap->ann_size);
262  /* Don't abort even if we get "Destination unreachable" */
263  if (ret < 0 && ret != AVERROR(ECONNREFUSED))
264  return ret;
265  sap->last_time = now;
266  }
267  rtpctx = s->streams[pkt->stream_index]->priv_data;
268  return ff_write_chained(rtpctx, 0, pkt, s, 0);
269 }
270 
272  .name = "sap",
273  .long_name = NULL_IF_CONFIG_SMALL("SAP output"),
274  .priv_data_size = sizeof(struct SAPState),
275  .audio_codec = AV_CODEC_ID_AAC,
276  .video_codec = AV_CODEC_ID_MPEG4,
277  .write_header = sap_write_header,
278  .write_packet = sap_write_packet,
279  .write_trailer = sap_write_close,
280  .flags = AVFMT_NOFILE | AVFMT_GLOBALHEADER,
281 };
av_gettime_relative
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition: time.c:56
AVOutputFormat::name
const char * name
Definition: avformat.h:496
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
av_find_info_tag
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:751
SAPState::ann_fd
URLContext * ann_fd
Definition: sapdec.c:37
sap_write_packet
static int sap_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: sapenc.c:254
AV_CODEC_ID_MPEG4
@ AV_CODEC_ID_MPEG4
Definition: avcodec.h:230
AVFormatContext::streams
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1410
URLContext::max_packet_size
int max_packet_size
if non zero, the stream is packetized with this max packet size
Definition: url.h:44
SAPState
Definition: sapdec.c:36
av_mallocz_array
void * av_mallocz_array(size_t nmemb, size_t size)
Definition: mem.c:191
AV_LOG_VERBOSE
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
SAPState::ann
uint8_t * ann
Definition: sapenc.c:36
ffurl_close
int ffurl_close(URLContext *h)
Definition: avio.c:470
ff_network_close
void ff_network_close(void)
Definition: network.c:116
os_support.h
sockaddr_storage
Definition: network.h:111
ff_network_init
int ff_network_init(void)
Definition: network.c:58
av_get_random_seed
uint32_t av_get_random_seed(void)
Get a seed to use in conjunction with random functions.
Definition: random_seed.c:120
freeaddrinfo
#define freeaddrinfo
Definition: network.h:218
fail
#define fail()
Definition: checkasm.h:120
rtpenc_chain.h
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
buf
void * buf
Definition: avisynth_c.h:766
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:1318
av_dict_get
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
ffurl_open_whitelist
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:307
intreadwrite.h
s
#define s(width, name)
Definition: cbs_vp9.c:257
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:36
AVIO_FLAG_WRITE
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:655
AVFormatContext
Format I/O context.
Definition: avformat.h:1342
internal.h
AVStream::time_base
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avformat.h:899
NULL
#define NULL
Definition: coverity.c:32
AV_WB16
#define AV_WB16(p, v)
Definition: intreadwrite.h:405
AVFormatContext::pb
AVIOContext * pb
I/O context.
Definition: avformat.h:1384
parseutils.h
time.h
ff_sap_muxer
AVOutputFormat ff_sap_muxer
Definition: sapenc.c:271
AV_CODEC_ID_AAC
@ AV_CODEC_ID_AAC
Definition: avcodec.h:566
addrinfo::ai_family
int ai_family
Definition: network.h:139
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:188
AV_NOPTS_VALUE
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
AVFMT_NOFILE
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:463
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:842
getaddrinfo
#define getaddrinfo
Definition: network.h:217
avio_closep
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:1210
av_write_trailer
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:1254
URLContext
Definition: url.h:38
AVFMT_GLOBALHEADER
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:466
AVOutputFormat
Definition: avformat.h:495
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:259
av_url_split
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:4756
url.h
uint8_t
uint8_t
Definition: audio_convert.c:194
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:236
SAPState::ann_size
int ann_size
Definition: sapenc.c:37
SAPState::last_time
int64_t last_time
Definition: sapenc.c:39
ret
ret
Definition: filter_design.txt:187
avformat.h
ff_rtp_chain_mux_open
int ff_rtp_chain_mux_open(AVFormatContext **out, AVFormatContext *s, AVStream *st, URLContext *handle, int packet_size, int idx)
Definition: rtpenc_chain.c:28
dict.h
ff_format_set_url
void ff_format_set_url(AVFormatContext *s, char *url)
Set AVFormatContext url field to the provided pointer.
Definition: utils.c:5825
network.h
random_seed.h
pkt
static AVPacket pkt
Definition: demuxing_decoding.c:54
sap_write_header
static int sap_write_header(AVFormatContext *s)
Definition: sapenc.c:69
avformat_free_context
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:4414
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:424
AVPacket::stream_index
int stream_index
Definition: avcodec.h:1479
av_gettime
int64_t av_gettime(void)
Get the current time in microseconds.
Definition: time.c:39
av_strdup
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:251
sap_write_close
static int sap_write_close(AVFormatContext *s)
Definition: sapenc.c:42
av_free
#define av_free(p)
Definition: tableprint_vlc.h:34
AVDictionaryEntry
Definition: dict.h:81
AVPacket
This structure stores compressed data.
Definition: avcodec.h:1454
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:35
av_dict_set
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
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:83
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:28
AVERROR_INVALIDDATA
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
AVDictionaryEntry::value
char * value
Definition: dict.h:83
avstring.h
addrinfo
Definition: network.h:137
ffurl_get_file_handle
int ffurl_get_file_handle(URLContext *h)
Return the file descriptor associated with this URL.
Definition: avio.c:629