]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_channelmap.c
af_channelmap: free old extended_data on reallocation
[ffmpeg] / libavfilter / af_channelmap.c
1 /*
2  * Copyright (c) 2012 Google, Inc.
3  *
4  * This file is part of Libav.
5  *
6  * Libav is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * Libav is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with Libav; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * audio channel mapping filter
24  */
25
26 #include <ctype.h>
27
28 #include "libavutil/audioconvert.h"
29 #include "libavutil/avstring.h"
30 #include "libavutil/common.h"
31 #include "libavutil/mathematics.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/samplefmt.h"
34
35 #include "audio.h"
36 #include "avfilter.h"
37 #include "formats.h"
38 #include "internal.h"
39
40 struct ChannelMap {
41     uint64_t in_channel;
42     uint64_t out_channel;
43     int in_channel_idx;
44     int out_channel_idx;
45 };
46
47 enum MappingMode {
48     MAP_NONE,
49     MAP_ONE_INT,
50     MAP_ONE_STR,
51     MAP_PAIR_INT_INT,
52     MAP_PAIR_INT_STR,
53     MAP_PAIR_STR_INT,
54     MAP_PAIR_STR_STR
55 };
56
57 #define MAX_CH 64
58 typedef struct ChannelMapContext {
59     const AVClass *class;
60     AVFilterChannelLayouts *channel_layouts;
61     char *mapping_str;
62     char *channel_layout_str;
63     uint64_t output_layout;
64     struct ChannelMap map[MAX_CH];
65     int nch;
66     enum MappingMode mode;
67 } ChannelMapContext;
68
69 #define OFFSET(x) offsetof(ChannelMapContext, x)
70 #define A AV_OPT_FLAG_AUDIO_PARAM
71 static const AVOption options[] = {
72     { "map", "A comma-separated list of input channel numbers in output order.",
73           OFFSET(mapping_str),        AV_OPT_TYPE_STRING, .flags = A },
74     { "channel_layout", "Output channel layout.",
75           OFFSET(channel_layout_str), AV_OPT_TYPE_STRING, .flags = A },
76     { NULL },
77 };
78
79 static const AVClass channelmap_class = {
80     .class_name = "channel map filter",
81     .item_name  = av_default_item_name,
82     .option     = options,
83     .version    = LIBAVUTIL_VERSION_INT,
84 };
85
86 static char* split(char *message, char delim) {
87     char *next = strchr(message, delim);
88     if (next)
89       *next++ = '\0';
90     return next;
91 }
92
93 static int get_channel_idx(char **map, int *ch, char delim, int max_ch)
94 {
95     char *next = split(*map, delim);
96     int len;
97     int n = 0;
98     if (!next && delim == '-')
99         return AVERROR(EINVAL);
100     len = strlen(*map);
101     sscanf(*map, "%d%n", ch, &n);
102     if (n != len)
103         return AVERROR(EINVAL);
104     if (*ch < 0 || *ch > max_ch)
105         return AVERROR(EINVAL);
106     *map = next;
107     return 0;
108 }
109
110 static int get_channel(char **map, uint64_t *ch, char delim)
111 {
112     char *next = split(*map, delim);
113     if (!next && delim == '-')
114         return AVERROR(EINVAL);
115     *ch = av_get_channel_layout(*map);
116     if (av_get_channel_layout_nb_channels(*ch) != 1)
117         return AVERROR(EINVAL);
118     *map = next;
119     return 0;
120 }
121
122 static av_cold int channelmap_init(AVFilterContext *ctx, const char *args)
123 {
124     ChannelMapContext *s = ctx->priv;
125     int ret;
126     char *mapping;
127     enum mode;
128     int map_entries = 0;
129     char buf[256];
130     enum MappingMode mode;
131     uint64_t out_ch_mask = 0;
132     int i;
133
134     if (!args) {
135         av_log(ctx, AV_LOG_ERROR, "No parameters supplied.\n");
136         return AVERROR(EINVAL);
137     }
138
139     s->class = &channelmap_class;
140     av_opt_set_defaults(s);
141
142     if ((ret = av_set_options_string(s, args, "=", ":")) < 0) {
143         av_log(ctx, AV_LOG_ERROR, "Error parsing options string '%s'.\n", args);
144         return ret;
145     }
146
147     mapping = s->mapping_str;
148
149     if (!mapping) {
150         mode = MAP_NONE;
151     } else {
152         char *dash = strchr(mapping, '-');
153         if (!dash) {  // short mapping
154             if (isdigit(*mapping))
155                 mode = MAP_ONE_INT;
156             else
157                 mode = MAP_ONE_STR;
158         } else if (isdigit(*mapping)) {
159             if (isdigit(*(dash+1)))
160                 mode = MAP_PAIR_INT_INT;
161             else
162                 mode = MAP_PAIR_INT_STR;
163         } else {
164             if (isdigit(*(dash+1)))
165                 mode = MAP_PAIR_STR_INT;
166             else
167                 mode = MAP_PAIR_STR_STR;
168         }
169     }
170
171     if (mode != MAP_NONE) {
172         char *comma = mapping;
173         map_entries = 1;
174         while ((comma = strchr(comma, ','))) {
175             if (*++comma)  // Allow trailing comma
176                 map_entries++;
177         }
178     }
179
180     if (map_entries > MAX_CH) {
181         av_log(ctx, AV_LOG_ERROR, "Too many channels mapped: '%d'.\n", map_entries);
182         ret = AVERROR(EINVAL);
183         goto fail;
184     }
185
186     for (i = 0; i < map_entries; i++) {
187         int in_ch_idx = -1, out_ch_idx = -1;
188         uint64_t in_ch = 0, out_ch = 0;
189         static const char err[] = "Failed to parse channel map\n";
190         switch (mode) {
191         case MAP_ONE_INT:
192             if (get_channel_idx(&mapping, &in_ch_idx, ',', MAX_CH) < 0) {
193                 ret = AVERROR(EINVAL);
194                 av_log(ctx, AV_LOG_ERROR, err);
195                 goto fail;
196             }
197             s->map[i].in_channel_idx  = in_ch_idx;
198             s->map[i].out_channel_idx = i;
199             break;
200         case MAP_ONE_STR:
201             if (!get_channel(&mapping, &in_ch, ',')) {
202                 av_log(ctx, AV_LOG_ERROR, err);
203                 ret = AVERROR(EINVAL);
204                 goto fail;
205             }
206             s->map[i].in_channel      = in_ch;
207             s->map[i].out_channel_idx = i;
208             break;
209         case MAP_PAIR_INT_INT:
210             if (get_channel_idx(&mapping, &in_ch_idx, '-', MAX_CH) < 0 ||
211                 get_channel_idx(&mapping, &out_ch_idx, ',', MAX_CH) < 0) {
212                 av_log(ctx, AV_LOG_ERROR, err);
213                 ret = AVERROR(EINVAL);
214                 goto fail;
215             }
216             s->map[i].in_channel_idx  = in_ch_idx;
217             s->map[i].out_channel_idx = out_ch_idx;
218             break;
219         case MAP_PAIR_INT_STR:
220             if (get_channel_idx(&mapping, &in_ch_idx, '-', MAX_CH) < 0 ||
221                 get_channel(&mapping, &out_ch, ',') < 0 ||
222                 out_ch & out_ch_mask) {
223                 av_log(ctx, AV_LOG_ERROR, err);
224                 ret = AVERROR(EINVAL);
225                 goto fail;
226             }
227             s->map[i].in_channel_idx  = in_ch_idx;
228             s->map[i].out_channel     = out_ch;
229             out_ch_mask |= out_ch;
230             break;
231         case MAP_PAIR_STR_INT:
232             if (get_channel(&mapping, &in_ch, '-') < 0 ||
233                 get_channel_idx(&mapping, &out_ch_idx, ',', MAX_CH) < 0) {
234                 av_log(ctx, AV_LOG_ERROR, err);
235                 ret = AVERROR(EINVAL);
236                 goto fail;
237             }
238             s->map[i].in_channel      = in_ch;
239             s->map[i].out_channel_idx = out_ch_idx;
240             break;
241         case MAP_PAIR_STR_STR:
242             if (get_channel(&mapping, &in_ch, '-') < 0 ||
243                 get_channel(&mapping, &out_ch, ',') < 0 ||
244                 out_ch & out_ch_mask) {
245                 av_log(ctx, AV_LOG_ERROR, err);
246                 ret = AVERROR(EINVAL);
247                 goto fail;
248             }
249             s->map[i].in_channel = in_ch;
250             s->map[i].out_channel = out_ch;
251             out_ch_mask |= out_ch;
252             break;
253         }
254     }
255     s->mode          = mode;
256     s->nch           = map_entries;
257     s->output_layout = out_ch_mask ? out_ch_mask :
258                        av_get_default_channel_layout(map_entries);
259
260     if (s->channel_layout_str) {
261         uint64_t fmt;
262         if ((fmt = av_get_channel_layout(s->channel_layout_str)) == 0) {
263             av_log(ctx, AV_LOG_ERROR, "Error parsing channel layout: '%s'.\n",
264                    s->channel_layout_str);
265             ret = AVERROR(EINVAL);
266             goto fail;
267         }
268         if (mode == MAP_NONE) {
269             int i;
270             s->nch = av_get_channel_layout_nb_channels(fmt);
271             for (i = 0; i < s->nch; i++) {
272                 s->map[i].in_channel_idx  = i;
273                 s->map[i].out_channel_idx = i;
274             }
275         } else if (out_ch_mask && out_ch_mask != fmt) {
276             av_get_channel_layout_string(buf, sizeof(buf), 0, out_ch_mask);
277             av_log(ctx, AV_LOG_ERROR,
278                    "Output channel layout '%s' does not match the list of channel mapped: '%s'.\n",
279                    s->channel_layout_str, buf);
280             ret = AVERROR(EINVAL);
281             goto fail;
282         } else if (s->nch != av_get_channel_layout_nb_channels(fmt)) {
283             av_log(ctx, AV_LOG_ERROR,
284                    "Output channel layout %s does not match the number of channels mapped %d.\n",
285                    s->channel_layout_str, s->nch);
286             ret = AVERROR(EINVAL);
287             goto fail;
288         }
289         s->output_layout = fmt;
290     }
291     ff_add_channel_layout(&s->channel_layouts, s->output_layout);
292
293     if (mode == MAP_PAIR_INT_STR || mode == MAP_PAIR_STR_STR) {
294         for (i = 0; i < s->nch; i++) {
295             s->map[i].out_channel_idx = av_get_channel_layout_channel_index(
296                 s->output_layout, s->map[i].out_channel);
297         }
298     }
299
300 fail:
301     av_opt_free(s);
302     return ret;
303 }
304
305 static int channelmap_query_formats(AVFilterContext *ctx)
306 {
307     ChannelMapContext *s = ctx->priv;
308
309     ff_set_common_formats(ctx, ff_planar_sample_fmts());
310     ff_set_common_samplerates(ctx, ff_all_samplerates());
311     ff_channel_layouts_ref(ff_all_channel_layouts(), &ctx->inputs[0]->out_channel_layouts);
312     ff_channel_layouts_ref(s->channel_layouts,       &ctx->outputs[0]->in_channel_layouts);
313
314     return 0;
315 }
316
317 static int channelmap_filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
318 {
319     AVFilterContext  *ctx = inlink->dst;
320     AVFilterLink *outlink = ctx->outputs[0];
321     const ChannelMapContext *s = ctx->priv;
322     const int nch_in = av_get_channel_layout_nb_channels(inlink->channel_layout);
323     const int nch_out = s->nch;
324     int ch;
325     uint8_t *source_planes[MAX_CH];
326
327     memcpy(source_planes, buf->extended_data,
328            nch_in * sizeof(source_planes[0]));
329
330     if (nch_out > nch_in) {
331         if (nch_out > FF_ARRAY_ELEMS(buf->data)) {
332             uint8_t **new_extended_data =
333                 av_mallocz(nch_out * sizeof(*buf->extended_data));
334             if (!new_extended_data) {
335                 avfilter_unref_buffer(buf);
336                 return AVERROR(ENOMEM);
337             }
338             if (buf->extended_data == buf->data) {
339                 buf->extended_data = new_extended_data;
340             } else {
341                 av_free(buf->extended_data);
342                 buf->extended_data = new_extended_data;
343             }
344         } else if (buf->extended_data != buf->data) {
345             av_free(buf->extended_data);
346             buf->extended_data = buf->data;
347         }
348     }
349
350     for (ch = 0; ch < nch_out; ch++) {
351         buf->extended_data[s->map[ch].out_channel_idx] =
352             source_planes[s->map[ch].in_channel_idx];
353     }
354
355     if (buf->data != buf->extended_data)
356         memcpy(buf->data, buf->extended_data,
357            FFMIN(FF_ARRAY_ELEMS(buf->data), nch_out) * sizeof(buf->data[0]));
358
359     return ff_filter_samples(outlink, buf);
360 }
361
362 static int channelmap_config_input(AVFilterLink *inlink)
363 {
364     AVFilterContext *ctx = inlink->dst;
365     ChannelMapContext *s = ctx->priv;
366     int i, err = 0;
367     const char *channel_name;
368     char layout_name[256];
369
370     if (s->mode == MAP_PAIR_STR_INT || s->mode == MAP_PAIR_STR_STR) {
371         for (i = 0; i < s->nch; i++) {
372             s->map[i].in_channel_idx = av_get_channel_layout_channel_index(
373                 inlink->channel_layout, s->map[i].in_channel);
374             if (s->map[i].in_channel_idx < 0) {
375                 channel_name = av_get_channel_name(s->map[i].in_channel);
376                 av_get_channel_layout_string(layout_name, sizeof(layout_name),
377                                              0, inlink->channel_layout);
378                 av_log(ctx, AV_LOG_ERROR,
379                        "input channel '%s' not available from input layout '%s'\n",
380                        channel_name, layout_name);
381                 err = AVERROR(EINVAL);
382             }
383         }
384     }
385
386     return err;
387 }
388
389 AVFilter avfilter_af_channelmap = {
390     .name          = "channelmap",
391     .description   = NULL_IF_CONFIG_SMALL("Remap audio channels."),
392     .init          = channelmap_init,
393     .query_formats = channelmap_query_formats,
394     .priv_size     = sizeof(ChannelMapContext),
395
396     .inputs        = (const AVFilterPad[]) {{ .name            = "default",
397                                               .type            = AVMEDIA_TYPE_AUDIO,
398                                               .filter_samples  = channelmap_filter_samples,
399                                               .config_props    = channelmap_config_input },
400                                             { .name = NULL }},
401     .outputs       = (const AVFilterPad[]) {{ .name            = "default",
402                                               .type            = AVMEDIA_TYPE_AUDIO },
403                                             { .name = NULL }},
404 };