nativeaudio

audio playback for Go
Log | Files | Refs | README | LICENSE

libav.go (12433B)


      1 //go:build linux && cgo
      2 
      3 // Package libav decodes compressed audio by linking ffmpeg's libraries
      4 // directly, rather than shelling out to the ffmpeg binary.
      5 //
      6 // The decode pipeline lives in C. libav is a struct-field API, and the
      7 // layout of AVFrame, AVCodecContext and friends changes between major
      8 // versions, so letting the headers describe them at build time is the
      9 // only way to stay correct across the libavcodec versions distributions
     10 // actually ship. Go sees five functions over an opaque handle.
     11 //
     12 // Output matches what the subprocess path produces: interleaved s16le
     13 // at the source's own sample rate and channel count.
     14 package libav
     15 
     16 /*
     17 #cgo pkg-config: libavformat libavcodec libavutil libswresample
     18 
     19 #include <libavcodec/avcodec.h>
     20 #include <libavformat/avformat.h>
     21 #include <libavutil/channel_layout.h>
     22 #include <libavutil/opt.h>
     23 #include <libswresample/swresample.h>
     24 #include <stdint.h>
     25 #include <stdlib.h>
     26 #include <string.h>
     27 
     28 // Size of the buffer avio reads the compressed input through. Nothing
     29 // depends on it beyond amortising the callback.
     30 #define NA_IO_BUFFER 4096
     31 
     32 typedef struct na_dec {
     33 	AVFormatContext *fmt;
     34 	AVCodecContext  *codec;
     35 	SwrContext      *swr;
     36 	AVPacket        *pkt;
     37 	AVFrame         *frame;
     38 	AVIOContext     *avio;
     39 
     40 	uint8_t *input;      // owned copy of the compressed bytes; memory source only.
     41 	int64_t  input_size;
     42 	int64_t  input_pos;
     43 
     44 	int index;           // index of the audio stream being decoded.
     45 	int sample_rate;
     46 	int channels;
     47 
     48 	uint8_t *out;        // converted PCM waiting to be collected.
     49 	int      out_cap;
     50 	int      out_len;
     51 	int      out_off;
     52 
     53 	int drained;         // demuxer exhausted and the decoder flushed.
     54 } na_dec;
     55 
     56 static int na_read_packet(void *opaque, uint8_t *buf, int size) {
     57 	na_dec *d = (na_dec *)opaque;
     58 	int64_t remaining = d->input_size - d->input_pos;
     59 	if (remaining <= 0) {
     60 		return AVERROR_EOF;
     61 	}
     62 	if ((int64_t)size > remaining) {
     63 		size = (int)remaining;
     64 	}
     65 	memcpy(buf, d->input + d->input_pos, size);
     66 	d->input_pos += size;
     67 	return size;
     68 }
     69 
     70 // na_seek backs the seeking that mp4 and friends need to read a moov
     71 // atom that trails the audio. It is why decoding from memory uses a
     72 // custom AVIOContext rather than a pipe: the subprocess path cannot
     73 // seek a pipe, which is the whole reason it writes a temporary file.
     74 static int64_t na_seek(void *opaque, int64_t offset, int whence) {
     75 	na_dec *d = (na_dec *)opaque;
     76 	int64_t pos;
     77 	if (whence == AVSEEK_SIZE) {
     78 		return d->input_size;
     79 	}
     80 	switch (whence) {
     81 	case SEEK_SET: pos = offset; break;
     82 	case SEEK_CUR: pos = d->input_pos + offset; break;
     83 	case SEEK_END: pos = d->input_size + offset; break;
     84 	default: return -1;
     85 	}
     86 	if (pos < 0 || pos > d->input_size) {
     87 		return -1;
     88 	}
     89 	d->input_pos = pos;
     90 	return pos;
     91 }
     92 
     93 // na_init finds the audio stream and opens a decoder for it. The
     94 // resampler is left until the first frame arrives, because a decoder is
     95 // not obliged to report its sample format before it has decoded
     96 // anything, while codecpar always knows the rate and channel count.
     97 static int na_init(na_dec *d) {
     98 	const AVCodec *codec = NULL;
     99 	AVCodecParameters *par = NULL;
    100 	int err;
    101 
    102 	if ((err = avformat_find_stream_info(d->fmt, NULL)) < 0) {
    103 		return err;
    104 	}
    105 	if ((err = av_find_best_stream(d->fmt, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0)) < 0) {
    106 		return err;
    107 	}
    108 	d->index = err;
    109 	par = d->fmt->streams[d->index]->codecpar;
    110 
    111 	if (!(d->codec = avcodec_alloc_context3(codec))) {
    112 		return AVERROR(ENOMEM);
    113 	}
    114 	if ((err = avcodec_parameters_to_context(d->codec, par)) < 0) {
    115 		return err;
    116 	}
    117 	if ((err = avcodec_open2(d->codec, codec, NULL)) < 0) {
    118 		return err;
    119 	}
    120 	if (!(d->pkt = av_packet_alloc()) || !(d->frame = av_frame_alloc())) {
    121 		return AVERROR(ENOMEM);
    122 	}
    123 
    124 	d->sample_rate = par->sample_rate;
    125 	d->channels = par->ch_layout.nb_channels;
    126 	return 0;
    127 }
    128 
    129 // na_convert resamples the decoded frame to interleaved s16le, building
    130 // the resampler on first use from the frame's own description.
    131 static int na_convert(na_dec *d) {
    132 	int channels, want, need, got;
    133 	uint8_t *plane[1];
    134 	int err;
    135 
    136 	if (!d->swr) {
    137 		AVChannelLayout out;
    138 		memset(&out, 0, sizeof(out));
    139 		if ((err = av_channel_layout_copy(&out, &d->frame->ch_layout)) < 0) {
    140 			return err;
    141 		}
    142 		err = swr_alloc_set_opts2(&d->swr,
    143 			&out, AV_SAMPLE_FMT_S16, d->frame->sample_rate,
    144 			&d->frame->ch_layout, (enum AVSampleFormat)d->frame->format, d->frame->sample_rate,
    145 			0, NULL);
    146 		av_channel_layout_uninit(&out);
    147 		if (err < 0) {
    148 			return err;
    149 		}
    150 		if ((err = swr_init(d->swr)) < 0) {
    151 			return err;
    152 		}
    153 	}
    154 
    155 	channels = d->frame->ch_layout.nb_channels;
    156 	if ((want = swr_get_out_samples(d->swr, d->frame->nb_samples)) < 0) {
    157 		return want;
    158 	}
    159 	need = want * channels * 2;
    160 	if (need > d->out_cap) {
    161 		uint8_t *grown = av_realloc(d->out, need);
    162 		if (!grown) {
    163 			return AVERROR(ENOMEM);
    164 		}
    165 		d->out = grown;
    166 		d->out_cap = need;
    167 	}
    168 
    169 	plane[0] = d->out;
    170 	got = swr_convert(d->swr, plane, want, (const uint8_t **)d->frame->extended_data, d->frame->nb_samples);
    171 	if (got < 0) {
    172 		return got;
    173 	}
    174 	d->out_len = got * channels * 2;
    175 	d->out_off = 0;
    176 	return 0;
    177 }
    178 
    179 // na_next refills the pending buffer, returning AVERROR_EOF once the
    180 // input is exhausted and the decoder has been flushed.
    181 static int na_next(na_dec *d) {
    182 	int err;
    183 
    184 	for (;;) {
    185 		err = avcodec_receive_frame(d->codec, d->frame);
    186 		if (err == 0) {
    187 			if ((err = na_convert(d)) < 0) {
    188 				return err;
    189 			}
    190 			if (d->out_len == 0) {
    191 				continue;
    192 			}
    193 			return 0;
    194 		}
    195 		if (err == AVERROR_EOF) {
    196 			return AVERROR_EOF;
    197 		}
    198 		if (err != AVERROR(EAGAIN)) {
    199 			return err;
    200 		}
    201 		if (d->drained) {
    202 			return AVERROR_EOF;
    203 		}
    204 
    205 		err = av_read_frame(d->fmt, d->pkt);
    206 		if (err == AVERROR_EOF) {
    207 			d->drained = 1;
    208 			// A null packet tells the decoder to emit whatever it has
    209 			// buffered, which is where the tail of the audio comes from.
    210 			avcodec_send_packet(d->codec, NULL);
    211 			continue;
    212 		}
    213 		if (err < 0) {
    214 			return err;
    215 		}
    216 		if (d->pkt->stream_index != d->index) {
    217 			av_packet_unref(d->pkt);
    218 			continue;
    219 		}
    220 		err = avcodec_send_packet(d->codec, d->pkt);
    221 		av_packet_unref(d->pkt);
    222 		if (err < 0 && err != AVERROR(EAGAIN)) {
    223 			return err;
    224 		}
    225 	}
    226 }
    227 
    228 static int na_read(na_dec *d, uint8_t *buf, int size) {
    229 	int n, err;
    230 
    231 	if (d->out_off >= d->out_len) {
    232 		if ((err = na_next(d)) < 0) {
    233 			return err;
    234 		}
    235 	}
    236 	n = d->out_len - d->out_off;
    237 	if (n > size) {
    238 		n = size;
    239 	}
    240 	memcpy(buf, d->out + d->out_off, n);
    241 	d->out_off += n;
    242 	return n;
    243 }
    244 
    245 static na_dec *na_alloc(void) {
    246 	return (na_dec *)av_mallocz(sizeof(na_dec));
    247 }
    248 
    249 static int na_open_file(na_dec *d, const char *path) {
    250 	int err = avformat_open_input(&d->fmt, path, NULL, NULL);
    251 	if (err < 0) {
    252 		return err;
    253 	}
    254 	return na_init(d);
    255 }
    256 
    257 static int na_open_memory(na_dec *d, const uint8_t *data, int64_t size) {
    258 	uint8_t *iobuf;
    259 	int err;
    260 
    261 	if (!(d->input = av_malloc(size))) {
    262 		return AVERROR(ENOMEM);
    263 	}
    264 	memcpy(d->input, data, size);
    265 	d->input_size = size;
    266 
    267 	if (!(iobuf = av_malloc(NA_IO_BUFFER))) {
    268 		return AVERROR(ENOMEM);
    269 	}
    270 	if (!(d->avio = avio_alloc_context(iobuf, NA_IO_BUFFER, 0, d, na_read_packet, NULL, na_seek))) {
    271 		av_free(iobuf);
    272 		return AVERROR(ENOMEM);
    273 	}
    274 	if (!(d->fmt = avformat_alloc_context())) {
    275 		return AVERROR(ENOMEM);
    276 	}
    277 	d->fmt->pb = d->avio;
    278 	d->fmt->flags |= AVFMT_FLAG_CUSTOM_IO;
    279 
    280 	if ((err = avformat_open_input(&d->fmt, NULL, NULL, NULL)) < 0) {
    281 		return err;
    282 	}
    283 	return na_init(d);
    284 }
    285 
    286 static void na_free(na_dec *d) {
    287 	if (!d) {
    288 		return;
    289 	}
    290 	if (d->frame) av_frame_free(&d->frame);
    291 	if (d->pkt) av_packet_free(&d->pkt);
    292 	if (d->swr) swr_free(&d->swr);
    293 	if (d->codec) avcodec_free_context(&d->codec);
    294 	// A failed avformat_open_input has already freed the context and
    295 	// nulled it, so this covers both paths.
    296 	if (d->fmt) avformat_close_input(&d->fmt);
    297 	if (d->avio) {
    298 		// Custom IO owns its buffer; closing the format context does not
    299 		// reclaim it, and avio may have swapped it for a larger one.
    300 		av_freep(&d->avio->buffer);
    301 		avio_context_free(&d->avio);
    302 	}
    303 	if (d->input) av_freep(&d->input);
    304 	if (d->out) av_freep(&d->out);
    305 	av_free(d);
    306 }
    307 */
    308 import "C"
    309 
    310 import (
    311 	"errors"
    312 	"fmt"
    313 	"io"
    314 	"sync"
    315 	"unsafe"
    316 )
    317 
    318 // Format describes the PCM a Stream produces.
    319 type Format struct {
    320 	SampleRate     int
    321 	Channels       int
    322 	BytesPerSample int
    323 }
    324 
    325 // Startup prepares the library. libav needs no global initialisation
    326 // any more, so this only quietens its logging: libav writes diagnostics
    327 // to stderr by default, and a library has no business doing that to its
    328 // host. Decode failures are reported through error values instead.
    329 func Startup() error {
    330 	C.av_log_set_level(C.AV_LOG_QUIET)
    331 	return nil
    332 }
    333 
    334 // Shutdown releases global state. There is none to release.
    335 func Shutdown() error { return nil }
    336 
    337 // Stream decodes incrementally, yielding interleaved s16le PCM.
    338 type Stream struct {
    339 	mu     sync.Mutex
    340 	dec    *C.na_dec
    341 	format Format
    342 }
    343 
    344 // Open decodes compressed audio held in memory.
    345 //
    346 // The bytes are copied into memory libav owns, which keeps them out of
    347 // reach of the Go collector while the C callbacks read them. Compressed
    348 // audio is roughly an order of magnitude smaller than the PCM it
    349 // becomes, so the copy costs little next to what streaming saves.
    350 func Open(compressed []byte) (*Stream, error) {
    351 	if len(compressed) == 0 {
    352 		return nil, errors.New("libav: no audio to decode")
    353 	}
    354 	dec := C.na_alloc()
    355 	if dec == nil {
    356 		return nil, errors.New("libav: allocating decoder")
    357 	}
    358 	rc := C.na_open_memory(dec, (*C.uint8_t)(unsafe.Pointer(&compressed[0])), C.int64_t(len(compressed)))
    359 	return finish(dec, rc, "decoding audio from memory")
    360 }
    361 
    362 // OpenFile decodes the audio file at path. libav reads the file itself,
    363 // so unlike the Media Foundation backend nothing is buffered up front.
    364 func OpenFile(path string) (*Stream, error) {
    365 	dec := C.na_alloc()
    366 	if dec == nil {
    367 		return nil, errors.New("libav: allocating decoder")
    368 	}
    369 	cpath := C.CString(path)
    370 	defer C.free(unsafe.Pointer(cpath))
    371 	rc := C.na_open_file(dec, cpath)
    372 	return finish(dec, rc, fmt.Sprintf("decoding %q", path))
    373 }
    374 
    375 // finish turns an open result into a Stream, releasing the decoder if
    376 // the open failed or produced audio this package cannot represent.
    377 func finish(dec *C.na_dec, rc C.int, what string) (*Stream, error) {
    378 	if rc < 0 {
    379 		C.na_free(dec)
    380 		return nil, fmt.Errorf("libav: %s: %s", what, averr(rc))
    381 	}
    382 	channels := int(dec.channels)
    383 	if channels < 1 || channels > 2 {
    384 		C.na_free(dec)
    385 		return nil, fmt.Errorf("libav: can only handle {1,2} channels got %d", channels)
    386 	}
    387 	return &Stream{
    388 		dec: dec,
    389 		format: Format{
    390 			SampleRate: int(dec.sample_rate),
    391 			Channels:   channels,
    392 			// Always 2: the resampler is configured for s16 regardless
    393 			// of what the source held.
    394 			BytesPerSample: 2,
    395 		},
    396 	}, nil
    397 }
    398 
    399 // Format describes the PCM this Stream produces. It is known as soon as
    400 // the Stream is opened, before any audio is read.
    401 func (s *Stream) Format() Format { return s.format }
    402 
    403 // Read fills p with decoded PCM, returning io.EOF once the audio is
    404 // exhausted.
    405 func (s *Stream) Read(p []byte) (int, error) {
    406 	if len(p) == 0 {
    407 		return 0, nil
    408 	}
    409 	s.mu.Lock()
    410 	defer s.mu.Unlock()
    411 	if s.dec == nil {
    412 		return 0, io.EOF
    413 	}
    414 	n := C.na_read(s.dec, (*C.uint8_t)(unsafe.Pointer(&p[0])), C.int(len(p)))
    415 	switch {
    416 	case n == C.int(eof):
    417 		return 0, io.EOF
    418 	case n < 0:
    419 		return 0, fmt.Errorf("libav: decoding: %s", averr(n))
    420 	}
    421 	return int(n), nil
    422 }
    423 
    424 // Close releases the decoder. It is safe to call more than once, and
    425 // abandoning a Stream before io.EOF is fine as long as it is closed.
    426 //
    427 // Nothing can wedge here the way Media Foundation can: the decode runs
    428 // on the calling goroutine, so there is no worker to wait for and
    429 // nothing in flight once Read has returned.
    430 func (s *Stream) Close() error {
    431 	s.mu.Lock()
    432 	defer s.mu.Unlock()
    433 	if s.dec == nil {
    434 		return nil
    435 	}
    436 	C.na_free(s.dec)
    437 	s.dec = nil
    438 	return nil
    439 }
    440 
    441 // eof is libav's AVERROR_EOF, computed once rather than spelled out,
    442 // since the macro is a byte-order-dependent FourCC.
    443 var eof = C.int(C.AVERROR_EOF)
    444 
    445 // averr renders a libav error code the way ffmpeg would report it.
    446 func averr(code C.int) string {
    447 	buf := make([]byte, C.AV_ERROR_MAX_STRING_SIZE)
    448 	if C.av_strerror(code, (*C.char)(unsafe.Pointer(&buf[0])), C.size_t(len(buf))) < 0 {
    449 		return fmt.Sprintf("error %d", int(code))
    450 	}
    451 	if i := bytesIndexZero(buf); i >= 0 {
    452 		buf = buf[:i]
    453 	}
    454 	return string(buf)
    455 }
    456 
    457 func bytesIndexZero(b []byte) int {
    458 	for i, c := range b {
    459 		if c == 0 {
    460 			return i
    461 		}
    462 	}
    463 	return -1
    464 }