1 /*                                                     -*- linux-c -*-
2     Copyright (C) 2005 Tom Szilagyi
3 
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8 
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13 
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 
18     $Id: dec_lavc.c 1280 2014-04-10 22:48:52Z tszilagyi $
19 */
20 
21 #include <config.h>
22 
23 #include <stddef.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <sys/types.h>
27 #include <ctype.h>
28 #include <libavutil/avutil.h>
29 
30 #include "../common.h"
31 #include "../rb.h"
32 #include "dec_lavc.h"
33 
34 
35 /* uncomment this to get some debug info */
36 /* #define LAVC_DEBUG */
37 
38 extern size_t sample_size;
39 
40 /* interleaved: */
conv_fmt_u8(int n_samples,int sample_size,float * fsamples,AVFrame * frame)41 void conv_fmt_u8(int n_samples, int sample_size, float * fsamples, AVFrame * frame) {
42 	int i;
43 	for (i = 0; i < n_samples; i++) {
44 		*fsamples++ = (*((uint8_t*)(frame->extended_data[0] + i*sample_size)) - 128) / 256.f;
45 	}
46 }
conv_fmt_s16(int n_samples,int sample_size,float * fsamples,AVFrame * frame)47 void conv_fmt_s16(int n_samples, int sample_size, float * fsamples, AVFrame * frame) {
48 	int i;
49 	for (i = 0; i < n_samples; i++) {
50 		*fsamples++ = *((int16_t*)(frame->extended_data[0] + i*sample_size)) / 32768.f;
51 	}
52 }
conv_fmt_s32(int n_samples,int sample_size,float * fsamples,AVFrame * frame)53 void conv_fmt_s32(int n_samples, int sample_size, float * fsamples, AVFrame * frame) {
54 	int i;
55 	for (i = 0; i < n_samples; i++) {
56 		*fsamples++ = *((int32_t*)(frame->extended_data[0] + i*sample_size)) / 2147483648.f;
57 	}
58 }
conv_fmt_flt(int n_samples,int sample_size,float * fsamples,AVFrame * frame)59 void conv_fmt_flt(int n_samples, int sample_size, float * fsamples, AVFrame * frame) {
60 	int i;
61 	for (i = 0; i < n_samples; i++) {
62 		*fsamples++ = *((float*)(frame->extended_data[0] + i*sample_size));
63 	}
64 }
conv_fmt_dbl(int n_samples,int sample_size,float * fsamples,AVFrame * frame)65 void conv_fmt_dbl(int n_samples, int sample_size, float * fsamples, AVFrame * frame) {
66 	int i;
67 	for (i = 0; i < n_samples; i++) {
68 		*fsamples++ = *((double*)(frame->extended_data[0] + i*sample_size));
69 	}
70 }
71 
72 /* planar: */
conv_fmt_u8p(int n_samples,int channels,int sample_size,float * fsamples,AVFrame * frame)73 void conv_fmt_u8p(int n_samples, int channels, int sample_size, float * fsamples, AVFrame * frame) {
74 	int i, ch;
75 	for (i = 0; i < n_samples; i++) {
76 		for (ch = 0; ch < channels; ch++) {
77 			*fsamples++ = (*((uint8_t*)(frame->extended_data[ch] + i*sample_size)) - 128) / 256.f;
78 		}
79 	}
80 }
conv_fmt_s16p(int n_samples,int channels,int sample_size,float * fsamples,AVFrame * frame)81 void conv_fmt_s16p(int n_samples, int channels, int sample_size, float * fsamples, AVFrame * frame) {
82 	int i, ch;
83 	for (i = 0; i < n_samples; i++) {
84 		for (ch = 0; ch < channels; ch++) {
85 			*fsamples++ = *((int16_t*)(frame->extended_data[ch] + i*sample_size)) / 32768.f;
86 		}
87 	}
88 }
conv_fmt_s32p(int n_samples,int channels,int sample_size,float * fsamples,AVFrame * frame)89 void conv_fmt_s32p(int n_samples, int channels, int sample_size, float * fsamples, AVFrame * frame) {
90 	int i, ch;
91 	for (i = 0; i < n_samples; i++) {
92 		for (ch = 0; ch < channels; ch++) {
93 			*fsamples++ = *((int32_t*)(frame->extended_data[ch] + i*sample_size)) / 2147483648.f;
94 		}
95 	}
96 }
conv_fmt_fltp(int n_samples,int channels,int sample_size,float * fsamples,AVFrame * frame)97 void conv_fmt_fltp(int n_samples, int channels, int sample_size, float * fsamples, AVFrame * frame) {
98 	int i, ch;
99 	for (i = 0; i < n_samples; i++) {
100 		for (ch = 0; ch < channels; ch++) {
101 			*fsamples++ = *((float*)(frame->extended_data[ch] + i*sample_size));
102 		}
103 	}
104 }
conv_fmt_dblp(int n_samples,int channels,int sample_size,float * fsamples,AVFrame * frame)105 void conv_fmt_dblp(int n_samples, int channels, int sample_size, float * fsamples, AVFrame * frame) {
106 	int i, ch;
107 	for (i = 0; i < n_samples; i++) {
108 		for (ch = 0; ch < channels; ch++) {
109 			*fsamples++ = *((double*)(frame->extended_data[ch] + i*sample_size));
110 		}
111 	}
112 }
113 
114 /* Loosely based on avcodec_decode_audio3() implementation found at:
115  * https://raw.github.com/FFmpeg/FFmpeg/master/libavcodec/utils.c
116  */
decode_audio(AVCodecContext * avctx,float * fsamples,int * frame_size_ptr,AVPacket * avpkt)117 int decode_audio(AVCodecContext *avctx, float *fsamples, int *frame_size_ptr, AVPacket *avpkt) {
118 	int ret;
119 	AVFrame frame = { { 0 } };
120 	int got_frame = 0;
121 
122 	ret = avcodec_decode_audio4(avctx, &frame, &got_frame, avpkt);
123 	if (ret >= 0 && got_frame) {
124 		int plane_size;
125 		int planar = av_sample_fmt_is_planar(avctx->sample_fmt);
126 		int sample_size = av_get_bytes_per_sample(avctx->sample_fmt);
127 		int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
128 							   frame.nb_samples, avctx->sample_fmt, 1);
129 		int n_samples = plane_size / sample_size;
130 		if (*frame_size_ptr < data_size) {
131 			av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
132 			       "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
133 			return AVERROR(EINVAL);
134 		}
135 
136 		switch (avctx->sample_fmt) {
137 		/* interleaved: */
138 		case AV_SAMPLE_FMT_U8: conv_fmt_u8(n_samples, sample_size, fsamples, &frame); break;
139 		case AV_SAMPLE_FMT_S16: conv_fmt_s16(n_samples, sample_size, fsamples, &frame); break;
140 		case AV_SAMPLE_FMT_S32: conv_fmt_s32(n_samples, sample_size, fsamples, &frame); break;
141 		case AV_SAMPLE_FMT_FLT: conv_fmt_flt(n_samples, sample_size, fsamples, &frame); break;
142 		case AV_SAMPLE_FMT_DBL: conv_fmt_dbl(n_samples, sample_size, fsamples, &frame); break;
143 		/* planar: */
144 		case AV_SAMPLE_FMT_U8P: conv_fmt_u8p(n_samples, avctx->channels, sample_size, fsamples, &frame); break;
145 		case AV_SAMPLE_FMT_S16P: conv_fmt_s16p(n_samples, avctx->channels, sample_size, fsamples, &frame); break;
146 		case AV_SAMPLE_FMT_S32P: conv_fmt_s32p(n_samples, avctx->channels, sample_size, fsamples, &frame); break;
147 		case AV_SAMPLE_FMT_FLTP: conv_fmt_fltp(n_samples, avctx->channels, sample_size, fsamples, &frame); break;
148 		case AV_SAMPLE_FMT_DBLP: conv_fmt_dblp(n_samples, avctx->channels, sample_size, fsamples, &frame); break;
149 		default:
150 			fprintf(stderr, "Fatal error: dec_lavc.c: decode_audio #1: invalid sample format %s\n",
151 				av_get_sample_fmt_name(avctx->sample_fmt));
152 			exit(1); // no, we really don't want to handle this gracefully
153 		}
154 		*frame_size_ptr = planar ? n_samples * avctx->channels : n_samples;
155 	} else {
156 		*frame_size_ptr = 0;
157 	}
158 	return ret;
159 }
160 
161 /* return 1 if reached end of stream, 0 else */
162 int
decode_lavc(decoder_t * dec)163 decode_lavc(decoder_t * dec) {
164 
165         lavc_pdata_t * pd = (lavc_pdata_t *)dec->pdata;
166         file_decoder_t * fdec = dec->fdec;
167 
168 	AVPacket packet;
169 #if LIBAVCODEC_VERSION_MAJOR < 53
170         int16_t samples[MAX_AUDIO_FRAME_SIZE];
171         int n_bytes = MAX_AUDIO_FRAME_SIZE;
172 #endif /* LIBAVCODEC_VERSION_MAJOR >= 53 */
173         float fsamples[MAX_AUDIO_FRAME_SIZE];
174 	int n_samples = MAX_AUDIO_FRAME_SIZE;
175 	int i;
176 
177 	if (av_read_frame(pd->avFormatCtx, &packet) < 0)
178 		return 1;
179 
180 	if (!(packet.stream_index == pd->audioStream))
181 		goto end;
182 
183 #if LIBAVCODEC_VERSION_MAJOR < 53
184 	avcodec_decode_audio3(pd->avCodecCtx, samples, &n_bytes, &packet);
185 	if (n_bytes <= 0) goto end;
186 	n_samples = n_bytes / 2;
187 	for (i = 0; i < n_samples; i++) {
188 		fsamples[i] = samples[i] * fdec->voladj_lin / 32768.f;
189 	}
190 #else /* LIBAVCODEC_VERSION_MAJOR >= 53 */
191 	decode_audio(pd->avCodecCtx, fsamples, &n_samples, &packet);
192 	if (n_samples <= 0) goto end;
193 	for (i = 0; i < n_samples; i++) {
194 		fsamples[i] *= fdec->voladj_lin;
195 	}
196 #endif /* LIBAVCODEC_VERSION_MAJOR >= 53 */
197 
198 	rb_write(pd->rb, (char *)fsamples, n_samples * sample_size);
199 end:
200 	av_free_packet(&packet);
201         return 0;
202 }
203 
204 
205 decoder_t *
lavc_decoder_init(file_decoder_t * fdec)206 lavc_decoder_init(file_decoder_t * fdec) {
207 
208         decoder_t * dec = NULL;
209 
210         if ((dec = calloc(1, sizeof(decoder_t))) == NULL) {
211                 fprintf(stderr, "dec_lavc.c: lavc_decoder_new() failed: calloc error\n");
212                 return NULL;
213         }
214 
215 	dec->fdec = fdec;
216 
217         if ((dec->pdata = calloc(1, sizeof(lavc_pdata_t))) == NULL) {
218                 fprintf(stderr, "dec_lavc.c: lavc_decoder_new() failed: calloc error\n");
219                 return NULL;
220         }
221 
222 	dec->init = lavc_decoder_init;
223 	dec->destroy = lavc_decoder_destroy;
224 	dec->open = lavc_decoder_open;
225 	dec->send_metadata = lavc_decoder_send_metadata;
226 	dec->close = lavc_decoder_close;
227 	dec->read = lavc_decoder_read;
228 	dec->seek = lavc_decoder_seek;
229 
230 	return dec;
231 }
232 
233 
234 void
lavc_decoder_destroy(decoder_t * dec)235 lavc_decoder_destroy(decoder_t * dec) {
236 
237 	free(dec->pdata);
238 	free(dec);
239 }
240 
241 
242 int
lavc_decoder_open(decoder_t * dec,char * filename)243 lavc_decoder_open(decoder_t * dec, char * filename) {
244 
245 	lavc_pdata_t * pd = (lavc_pdata_t *)dec->pdata;
246 	file_decoder_t * fdec = dec->fdec;
247 	int i;
248 
249 #if LIBAVFORMAT_VERSION_MAJOR < 53
250 	if (av_open_input_file(&pd->avFormatCtx, filename, NULL, 0, NULL) != 0)
251 #else /* LIBAVFORMAT_VERSION_MAJOR >= 53 */
252 	if (avformat_open_input(&pd->avFormatCtx, filename, NULL, NULL) != 0)
253 #endif /* LIBAVFORMAT_VERSION_MAJOR >= 53 */
254 	{
255 		return DECODER_OPEN_BADLIB;
256 	}
257 
258 #if LIBAVFORMAT_VERSION_MAJOR < 53
259 	if (av_find_stream_info(pd->avFormatCtx) < 0)
260 #else /* LIBAVFORMAT_VERSION_MAJOR >= 53 */
261 	if (avformat_find_stream_info(pd->avFormatCtx, NULL) < 0)
262 #endif /* LIBAVFORMAT_VERSION_MAJOR >= 53 */
263 	{
264 		return DECODER_OPEN_BADLIB;
265 	}
266 
267 	/* debug */
268 #ifdef LAVC_DEBUG
269 	dump_format(pd->avFormatCtx, 0, filename, 0);
270 #endif /* LAVC_DEBUG */
271 
272 	pd->audioStream = -1;
273 	for (i = 0; i < pd->avFormatCtx->nb_streams; i++) {
274 		if (pd->avFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
275 			pd->audioStream = i;
276 			break;
277 		}
278 	}
279 	if (pd->audioStream == -1)
280 		return DECODER_OPEN_BADLIB;
281 
282 	pd->avCodecCtx = pd->avFormatCtx->streams[pd->audioStream]->codec;
283 #if LIBAVCODEC_VERSION_MAJOR < 55
284 #if LIBAVCODEC_VERSION_MAJOR >= 53
285 	pd->avCodecCtx->get_buffer = avcodec_default_get_buffer;
286 	pd->avCodecCtx->release_buffer = avcodec_default_release_buffer;
287 #endif /* LIBAVCODEC_VERSION_MAJOR >= 53 */
288 #endif /* LIBAVCODEC_VERSION_MAJOR < 55 */
289 
290 	pd->time_base = pd->avFormatCtx->streams[pd->audioStream]->time_base;
291 
292 	pd->avCodec = avcodec_find_decoder(pd->avCodecCtx->codec_id);
293 	if (pd->avCodec == NULL)
294 		return DECODER_OPEN_BADLIB;
295 
296 #if LIBAVCODEC_VERSION_MAJOR < 53
297 	if (avcodec_open(pd->avCodecCtx, pd->avCodec) < 0)
298 #else /* LIBAVCODEC_VERSION_MAJOR >= 53 */
299 	if (avcodec_open2(pd->avCodecCtx, pd->avCodec, NULL) < 0)
300 #endif /* LIBAVCODEC_VERSION_MAJOR >= 53 */
301 	{
302 		return DECODER_OPEN_BADLIB;
303 	}
304 
305 	if ((pd->avCodecCtx->channels != 1) && (pd->avCodecCtx->channels != 2)) {
306 		fprintf(stderr,
307 			"lavc_decoder_open: audio stream with %d channels is unsupported\n",
308 			pd->avCodecCtx->channels);
309 		return DECODER_OPEN_FERROR;
310 	}
311 
312         pd->is_eos = 0;
313         pd->rb = rb_create(pd->avCodecCtx->channels * sample_size * RB_LAVC_SIZE);
314 
315 	fdec->fileinfo.channels = pd->avCodecCtx->channels;
316 	fdec->fileinfo.sample_rate = pd->avCodecCtx->sample_rate;
317 	fdec->fileinfo.bps = pd->avCodecCtx->bit_rate;
318 	if (pd->avFormatCtx->duration > 0) {
319 		fdec->fileinfo.total_samples = pd->avFormatCtx->duration
320 			/ 1000000.0 * pd->avCodecCtx->sample_rate;
321 	} else {
322 		fdec->fileinfo.total_samples = 0;
323 	}
324 
325 	fdec->file_lib = LAVC_LIB;
326 	snprintf(dec->format_str, MAXLEN-1, "%s/%s", pd->avFormatCtx->iformat->name, pd->avCodec->name);
327 	for (i = 0; dec->format_str[i] != '\0'; i++) {
328 		dec->format_str[i] = toupper(dec->format_str[i]);
329 	}
330 
331 	return DECODER_OPEN_SUCCESS;
332 }
333 
334 
335 void
lavc_decoder_send_metadata(decoder_t * dec)336 lavc_decoder_send_metadata(decoder_t * dec) {
337 }
338 
339 
340 void
lavc_decoder_close(decoder_t * dec)341 lavc_decoder_close(decoder_t * dec) {
342 
343 	lavc_pdata_t * pd = (lavc_pdata_t *)dec->pdata;
344 
345 	avcodec_close(pd->avCodecCtx);
346 
347 #if LIBAVFORMAT_VERSION_MAJOR < 53
348 	av_close_input_file(pd->avFormatCtx);
349 #else /* LIBAVFORMAT_VERSION_MAJOR >= 53 */
350 	avformat_close_input(&pd->avFormatCtx);
351 #endif /* LIBAVFORMAT_VERSION_MAJOR >= 53 */
352 
353 	rb_free(pd->rb);
354 }
355 
356 
357 unsigned int
lavc_decoder_read(decoder_t * dec,float * dest,int num)358 lavc_decoder_read(decoder_t * dec, float * dest, int num) {
359 
360 	lavc_pdata_t * pd = (lavc_pdata_t *)dec->pdata;
361 
362         unsigned int numread = 0;
363         unsigned int n_avail = 0;
364 
365         while ((rb_read_space(pd->rb) <
366                 num * pd->avCodecCtx->channels * sample_size) && (!pd->is_eos)) {
367 
368                 pd->is_eos = decode_lavc(dec);
369         }
370 
371         n_avail = rb_read_space(pd->rb) / (pd->avCodecCtx->channels * sample_size);
372 
373         if (n_avail > num)
374                 n_avail = num;
375 
376         rb_read(pd->rb, (char *)dest, n_avail *	pd->avCodecCtx->channels * sample_size);
377         numread = n_avail;
378         return numread;
379 }
380 
381 
382 void
lavc_decoder_seek(decoder_t * dec,unsigned long long seek_to_pos)383 lavc_decoder_seek(decoder_t * dec, unsigned long long seek_to_pos) {
384 
385 	lavc_pdata_t * pd = (lavc_pdata_t *)dec->pdata;
386 	file_decoder_t * fdec = dec->fdec;
387 	char flush_dest;
388 
389 	long long pos = fdec->fileinfo.total_samples - fdec->samples_left;
390 	int64_t timestamp = (double)seek_to_pos / fdec->fileinfo.sample_rate
391 		* pd->time_base.den / pd->time_base.num;
392 	int flags = (pos > seek_to_pos) ? AVSEEK_FLAG_BACKWARD : 0;
393 
394 	if (av_seek_frame(pd->avFormatCtx, pd->audioStream, timestamp, flags) >= 0) {
395 		fdec->samples_left = fdec->fileinfo.total_samples - seek_to_pos;
396 		/* empty lavc decoder ringbuffer */
397 		while (rb_read_space(pd->rb))
398 			rb_read(pd->rb, &flush_dest, sizeof(char));
399 	} else {
400 		fprintf(stderr, "lavc_decoder_seek: warning: av_seek_frame() failed\n");
401 	}
402 }
403 
404 
405 
406 // vim: shiftwidth=8:tabstop=8:softtabstop=8 :
407 
408