1/*
2 * Copyright (c) 2012 Google, Inc.
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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/avstring.h"
29#include "libavutil/channel_layout.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
40struct ChannelMap {
41    uint64_t in_channel;
42    uint64_t out_channel;
43    int in_channel_idx;
44    int out_channel_idx;
45};
46
47enum 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
58typedef 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#define F AV_OPT_FLAG_FILTERING_PARAM
72static const AVOption channelmap_options[] = {
73    { "map", "A comma-separated list of input channel numbers in output order.",
74          OFFSET(mapping_str),        AV_OPT_TYPE_STRING, .flags = A|F },
75    { "channel_layout", "Output channel layout.",
76          OFFSET(channel_layout_str), AV_OPT_TYPE_STRING, .flags = A|F },
77    { NULL }
78};
79
80AVFILTER_DEFINE_CLASS(channelmap);
81
82static char* split(char *message, char delim) {
83    char *next = strchr(message, delim);
84    if (next)
85      *next++ = '\0';
86    return next;
87}
88
89static int get_channel_idx(char **map, int *ch, char delim, int max_ch)
90{
91    char *next = split(*map, delim);
92    int len;
93    int n = 0;
94    if (!next && delim == '-')
95        return AVERROR(EINVAL);
96    len = strlen(*map);
97    sscanf(*map, "%d%n", ch, &n);
98    if (n != len)
99        return AVERROR(EINVAL);
100    if (*ch < 0 || *ch > max_ch)
101        return AVERROR(EINVAL);
102    *map = next;
103    return 0;
104}
105
106static int get_channel(char **map, uint64_t *ch, char delim)
107{
108    char *next = split(*map, delim);
109    if (!next && delim == '-')
110        return AVERROR(EINVAL);
111    *ch = av_get_channel_layout(*map);
112    if (av_get_channel_layout_nb_channels(*ch) != 1)
113        return AVERROR(EINVAL);
114    *map = next;
115    return 0;
116}
117
118static av_cold int channelmap_init(AVFilterContext *ctx)
119{
120    ChannelMapContext *s = ctx->priv;
121    char *mapping, separator = '|';
122    int map_entries = 0;
123    char buf[256];
124    enum MappingMode mode;
125    uint64_t out_ch_mask = 0;
126    int i;
127
128    mapping = s->mapping_str;
129
130    if (!mapping) {
131        mode = MAP_NONE;
132    } else {
133        char *dash = strchr(mapping, '-');
134        if (!dash) {  // short mapping
135            if (av_isdigit(*mapping))
136                mode = MAP_ONE_INT;
137            else
138                mode = MAP_ONE_STR;
139        } else if (av_isdigit(*mapping)) {
140            if (av_isdigit(*(dash+1)))
141                mode = MAP_PAIR_INT_INT;
142            else
143                mode = MAP_PAIR_INT_STR;
144        } else {
145            if (av_isdigit(*(dash+1)))
146                mode = MAP_PAIR_STR_INT;
147            else
148                mode = MAP_PAIR_STR_STR;
149        }
150#if FF_API_OLD_FILTER_OPTS
151        if (strchr(mapping, ',')) {
152            av_log(ctx, AV_LOG_WARNING, "This syntax is deprecated, use "
153                   "'|' to separate the mappings.\n");
154            separator = ',';
155        }
156#endif
157    }
158
159    if (mode != MAP_NONE) {
160        char *sep = mapping;
161        map_entries = 1;
162        while ((sep = strchr(sep, separator))) {
163            if (*++sep)  // Allow trailing comma
164                map_entries++;
165        }
166    }
167
168    if (map_entries > MAX_CH) {
169        av_log(ctx, AV_LOG_ERROR, "Too many channels mapped: '%d'.\n", map_entries);
170        return AVERROR(EINVAL);
171    }
172
173    for (i = 0; i < map_entries; i++) {
174        int in_ch_idx = -1, out_ch_idx = -1;
175        uint64_t in_ch = 0, out_ch = 0;
176        static const char err[] = "Failed to parse channel map\n";
177        switch (mode) {
178        case MAP_ONE_INT:
179            if (get_channel_idx(&mapping, &in_ch_idx, separator, MAX_CH) < 0) {
180                av_log(ctx, AV_LOG_ERROR, err);
181                return AVERROR(EINVAL);
182            }
183            s->map[i].in_channel_idx  = in_ch_idx;
184            s->map[i].out_channel_idx = i;
185            break;
186        case MAP_ONE_STR:
187            if (get_channel(&mapping, &in_ch, separator) < 0) {
188                av_log(ctx, AV_LOG_ERROR, err);
189                return AVERROR(EINVAL);
190            }
191            s->map[i].in_channel      = in_ch;
192            s->map[i].out_channel_idx = i;
193            break;
194        case MAP_PAIR_INT_INT:
195            if (get_channel_idx(&mapping, &in_ch_idx, '-', MAX_CH) < 0 ||
196                get_channel_idx(&mapping, &out_ch_idx, separator, MAX_CH) < 0) {
197                av_log(ctx, AV_LOG_ERROR, err);
198                return AVERROR(EINVAL);
199            }
200            s->map[i].in_channel_idx  = in_ch_idx;
201            s->map[i].out_channel_idx = out_ch_idx;
202            break;
203        case MAP_PAIR_INT_STR:
204            if (get_channel_idx(&mapping, &in_ch_idx, '-', MAX_CH) < 0 ||
205                get_channel(&mapping, &out_ch, separator) < 0 ||
206                out_ch & out_ch_mask) {
207                av_log(ctx, AV_LOG_ERROR, err);
208                return AVERROR(EINVAL);
209            }
210            s->map[i].in_channel_idx  = in_ch_idx;
211            s->map[i].out_channel     = out_ch;
212            out_ch_mask |= out_ch;
213            break;
214        case MAP_PAIR_STR_INT:
215            if (get_channel(&mapping, &in_ch, '-') < 0 ||
216                get_channel_idx(&mapping, &out_ch_idx, separator, MAX_CH) < 0) {
217                av_log(ctx, AV_LOG_ERROR, err);
218                return AVERROR(EINVAL);
219            }
220            s->map[i].in_channel      = in_ch;
221            s->map[i].out_channel_idx = out_ch_idx;
222            break;
223        case MAP_PAIR_STR_STR:
224            if (get_channel(&mapping, &in_ch, '-') < 0 ||
225                get_channel(&mapping, &out_ch, separator) < 0 ||
226                out_ch & out_ch_mask) {
227                av_log(ctx, AV_LOG_ERROR, err);
228                return AVERROR(EINVAL);
229            }
230            s->map[i].in_channel = in_ch;
231            s->map[i].out_channel = out_ch;
232            out_ch_mask |= out_ch;
233            break;
234        }
235    }
236    s->mode          = mode;
237    s->nch           = map_entries;
238    s->output_layout = out_ch_mask ? out_ch_mask :
239                       av_get_default_channel_layout(map_entries);
240
241    if (s->channel_layout_str) {
242        uint64_t fmt;
243        if ((fmt = av_get_channel_layout(s->channel_layout_str)) == 0) {
244            av_log(ctx, AV_LOG_ERROR, "Error parsing channel layout: '%s'.\n",
245                   s->channel_layout_str);
246            return AVERROR(EINVAL);
247        }
248        if (mode == MAP_NONE) {
249            int i;
250            s->nch = av_get_channel_layout_nb_channels(fmt);
251            for (i = 0; i < s->nch; i++) {
252                s->map[i].in_channel_idx  = i;
253                s->map[i].out_channel_idx = i;
254            }
255        } else if (out_ch_mask && out_ch_mask != fmt) {
256            av_get_channel_layout_string(buf, sizeof(buf), 0, out_ch_mask);
257            av_log(ctx, AV_LOG_ERROR,
258                   "Output channel layout '%s' does not match the list of channel mapped: '%s'.\n",
259                   s->channel_layout_str, buf);
260            return AVERROR(EINVAL);
261        } else if (s->nch != av_get_channel_layout_nb_channels(fmt)) {
262            av_log(ctx, AV_LOG_ERROR,
263                   "Output channel layout %s does not match the number of channels mapped %d.\n",
264                   s->channel_layout_str, s->nch);
265            return AVERROR(EINVAL);
266        }
267        s->output_layout = fmt;
268    }
269    if (!s->output_layout) {
270        av_log(ctx, AV_LOG_ERROR, "Output channel layout is not set and "
271               "cannot be guessed from the maps.\n");
272        return AVERROR(EINVAL);
273    }
274
275    ff_add_channel_layout(&s->channel_layouts, s->output_layout);
276
277    if (mode == MAP_PAIR_INT_STR || mode == MAP_PAIR_STR_STR) {
278        for (i = 0; i < s->nch; i++) {
279            s->map[i].out_channel_idx = av_get_channel_layout_channel_index(
280                s->output_layout, s->map[i].out_channel);
281        }
282    }
283
284    return 0;
285}
286
287static int channelmap_query_formats(AVFilterContext *ctx)
288{
289    ChannelMapContext *s = ctx->priv;
290
291    ff_set_common_formats(ctx, ff_planar_sample_fmts());
292    ff_set_common_samplerates(ctx, ff_all_samplerates());
293    ff_channel_layouts_ref(ff_all_channel_layouts(), &ctx->inputs[0]->out_channel_layouts);
294    ff_channel_layouts_ref(s->channel_layouts,       &ctx->outputs[0]->in_channel_layouts);
295
296    return 0;
297}
298
299static int channelmap_filter_frame(AVFilterLink *inlink, AVFrame *buf)
300{
301    AVFilterContext  *ctx = inlink->dst;
302    AVFilterLink *outlink = ctx->outputs[0];
303    const ChannelMapContext *s = ctx->priv;
304    const int nch_in = av_get_channel_layout_nb_channels(inlink->channel_layout);
305    const int nch_out = s->nch;
306    int ch;
307    uint8_t *source_planes[MAX_CH];
308
309    memcpy(source_planes, buf->extended_data,
310           nch_in * sizeof(source_planes[0]));
311
312    if (nch_out > nch_in) {
313        if (nch_out > FF_ARRAY_ELEMS(buf->data)) {
314            uint8_t **new_extended_data =
315                av_mallocz_array(nch_out, sizeof(*buf->extended_data));
316            if (!new_extended_data) {
317                av_frame_free(&buf);
318                return AVERROR(ENOMEM);
319            }
320            if (buf->extended_data == buf->data) {
321                buf->extended_data = new_extended_data;
322            } else {
323                av_free(buf->extended_data);
324                buf->extended_data = new_extended_data;
325            }
326        } else if (buf->extended_data != buf->data) {
327            av_free(buf->extended_data);
328            buf->extended_data = buf->data;
329        }
330    }
331
332    for (ch = 0; ch < nch_out; ch++) {
333        buf->extended_data[s->map[ch].out_channel_idx] =
334            source_planes[s->map[ch].in_channel_idx];
335    }
336
337    if (buf->data != buf->extended_data)
338        memcpy(buf->data, buf->extended_data,
339           FFMIN(FF_ARRAY_ELEMS(buf->data), nch_out) * sizeof(buf->data[0]));
340
341    return ff_filter_frame(outlink, buf);
342}
343
344static int channelmap_config_input(AVFilterLink *inlink)
345{
346    AVFilterContext *ctx = inlink->dst;
347    ChannelMapContext *s = ctx->priv;
348    int nb_channels = av_get_channel_layout_nb_channels(inlink->channel_layout);
349    int i, err = 0;
350    const char *channel_name;
351    char layout_name[256];
352
353    for (i = 0; i < s->nch; i++) {
354        struct ChannelMap *m = &s->map[i];
355
356        if (s->mode == MAP_PAIR_STR_INT || s->mode == MAP_PAIR_STR_STR) {
357            m->in_channel_idx = av_get_channel_layout_channel_index(
358                inlink->channel_layout, m->in_channel);
359        }
360
361        if (m->in_channel_idx < 0 || m->in_channel_idx >= nb_channels) {
362            av_get_channel_layout_string(layout_name, sizeof(layout_name),
363                                         0, inlink->channel_layout);
364            if (m->in_channel) {
365                channel_name = av_get_channel_name(m->in_channel);
366                av_log(ctx, AV_LOG_ERROR,
367                       "input channel '%s' not available from input layout '%s'\n",
368                       channel_name, layout_name);
369            } else {
370                av_log(ctx, AV_LOG_ERROR,
371                       "input channel #%d not available from input layout '%s'\n",
372                       m->in_channel_idx, layout_name);
373            }
374            err = AVERROR(EINVAL);
375        }
376    }
377
378    return err;
379}
380
381static const AVFilterPad avfilter_af_channelmap_inputs[] = {
382    {
383        .name           = "default",
384        .type           = AVMEDIA_TYPE_AUDIO,
385        .filter_frame   = channelmap_filter_frame,
386        .config_props   = channelmap_config_input,
387        .needs_writable = 1,
388    },
389    { NULL }
390};
391
392static const AVFilterPad avfilter_af_channelmap_outputs[] = {
393    {
394        .name = "default",
395        .type = AVMEDIA_TYPE_AUDIO
396    },
397    { NULL }
398};
399
400AVFilter ff_af_channelmap = {
401    .name          = "channelmap",
402    .description   = NULL_IF_CONFIG_SMALL("Remap audio channels."),
403    .init          = channelmap_init,
404    .query_formats = channelmap_query_formats,
405    .priv_size     = sizeof(ChannelMapContext),
406    .priv_class    = &channelmap_class,
407    .inputs        = avfilter_af_channelmap_inputs,
408    .outputs       = avfilter_af_channelmap_outputs,
409};
410