使用ffmpeg实现一个播放器?是不是没什么新意,不过一直使用ffmpeg程序,还没有用ffmpeg代码接口实现播放器,并且还需要使用linux的alsa接口播放出声音,所以做出来还是觉得有点意思;
需求:实现一个嵌入式linux上支持mp3/aac/wav文件的播放器
实现:所以考虑基于ffmpeg 实现一个嵌入式linux的播放器,这里主要应用ffmpeg的协议处理和音频解码能力,虽然网上的代码很多,不过由于版本的差异,例子程序接口存在差异,实现起来还是花了两天调试的时间;
0、几点总结:
---多看官方的例子程序,官方例子路径:\ffmpeg-4.1.9\tmp\share\ffmpeg\examples
---avcodec_open2失败,怎么处理?
关键函数:avcodec_parameters_to_context 将avcodec_find_decoder找到的音频解码器复制decoder;
---av_read_frame存在内存泄漏,怎么处理?
关键函数:av_packet_unref(&input_packet);
---alsa播放设备如何枚举?
关键函数:snd_device_name_get_hint
avcodec_receive_frame接收解码完的frame只用申请一次内存;
AVFrame *pframeSRC = av_frame_alloc();
这里ffmpeg使用版本:ffmpeg-4.1.9,编译选项:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | //fdk-aacm root@lyz-VirtualBox:/home/lyz/work/broadcast_app/app/thirds_libs_src/fdk-aac/build# vim arm-gcc-cxx11.cmake root@lyz-VirtualBox:/home/lyz/work/broadcast_app/app/thirds_libs_src/fdk-aac/build# cmake -DCMAKE_TOOLCHAIN_FILE=/home/lyz/work/broadcast_app/app/thirds_libs_src/fdk-aac/build/arm-gcc-cxx11.cmake ../ -- The C compiler identification is GNU 6.4.1 root@lyz-VirtualBox:/home/lyz/work/broadcast_app/app_linux# cat /home/lyz/work/broadcast_app/app/thirds_libs_src/fdk-aac/build/arm-gcc-cxx11.cmake # Sample toolchain file for building with gcc compiler # # Typical usage: # *) cmake -H. -B_build -DCMAKE_TOOLCHAIN_FILE="${PWD}/toolchains/gcc.cmake" SET(CMAKE_SYSTEM_NAME Linux) set(CMAKE_SYSTEM_PROCESSOR arm) # set compiler set(CMAKE_C_COMPILER arm-openwrt-linux-gnueabi-gcc) set(CMAKE_CXX_COMPILER arm-openwrt-linux-gnueabi-g++) set(CONFIGURE_OPTS --enable- static =yes --enable-shared=no --disable-shared) # set c++ standard set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) //mp3 /home/lyz/work/broadcast_app/app/thirds_libs_src/lame-3.100 ./configure --host=arm-openwrt-linux-gnueabi --prefix=${PWD}/build/ ./configure --target-os=linux --prefix=/home/lyz/work/broadcast_app/app_linux/thirds_libs_src/ffmpeg-4.1.9/tmp --disable-shared --disable-muxers --enable-pic --enable- static --enable-gpl --enable-nonfree --enable-ffmpeg --disable-debug --disable-filters --disable-encoders --disable-hwaccels --enable- static --enable-libmp3lame --enable-demuxers --enable-parsers --enable-protocols --disable-x86asm --disable-stripping --extra-cflags= '-I/home/lyz/work/broadcast_app/app_linux/libs/include/ -I/home/lyz/work/broadcast_app/app_linux/libs/include/lame -Os -fpic ' --extra-ldflags= '-ldl -lm -L/home/lyz/work/broadcast_app/app_linux/libs/' --enable-decoder=aac --enable-swresample --enable-decoder=ac3 |
1、cpp文件引用ffmpeg库,出现链接错误,需要在包括头文件的地方增加两个前缀:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //.cpp #include <alsa/asoundlib.h> #ifdef __cplusplus extern "C" { #endif #include "libavutil/time.h" #include "libavformat/avformat.h" #include "libavcodec/avcodec.h" #include "libavdevice/avdevice.h" #include "libswresample/swresample.h" #include "libswscale/swscale.h" #ifdef __cplusplus } #endif |
2、上面修改后,还是出现链接错误,与链接库的链接顺序有关系;
错误的a库顺序:
1 | LDFLAGS += -L ./libs/ -lavcodec -lavfilter -lavformat -lavutil -lpostproc -lswscale -lswresample -lfdk-aac -lmp3lame |
正确的链接库顺序:
1 | LDFLAGS += -Wl,-Bstatic -L./libs -lavformat -lavcodec -lswscale -lswresample -lavutil -lavfilter -lavdevice -lpostproc -lfdk-aac -lmp3lame |
注意到动态链接和静态链接:
LDFLAGS += -Wl,-Bstatic -L./libs -lavformat -lavcodec -lswscale -lswresample -lavutil -lavfilter -lavdevice -lpostproc -lfdk-aac -lmp3lame
LDFLAGS += -Wl,-Bdynamic -ldl -lm -lasound -lpthread
3、内存泄漏,用valgrind 检查会有内存泄漏,播放一会就因为内存问题挂掉了;
使用valgrind可以很好的定位程序中的内存问题;
root@lyz-VirtualBox:/home/lyz/work/broadcast_app/app_linux# valgrind ./bas ./Test1.wav 0
4、使用alsa接口,完整播放出mp3文件声音的代码;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 | //static const char *device = "hw:1,0"; /* playback device "hw:0,0" */ static snd_pcm_format_t format = SND_PCM_FORMAT_S16; /* sample format */ static unsigned int rate = 44100; /* stream rate */ static unsigned int channels = 2; /* count of channels */ static unsigned int buffer_time = 500000; /* ring buffer length in us */ static unsigned int period_time = 100000; /* period time in us */ static int resample = 1; /* enable alsa-lib resampling */ static snd_pcm_sframes_t buffer_size; static snd_pcm_sframes_t period_size; snd_pcm_access_t mode = SND_PCM_ACCESS_RW_INTERLEAVED; static snd_output_t *output = NULL; /*配置参数*/ static int set_hwparams(snd_pcm_t *handle,snd_pcm_hw_params_t *params,snd_pcm_access_t access) { unsigned int rrate; snd_pcm_uframes_t size; int err, dir = 0; /* choose all parameters */ err = snd_pcm_hw_params_any(handle, params); if (err < 0) { printf ( "Broken configuration for playback: no configurations available: %s\n" , snd_strerror(err)); return err; } /* set hardware resampling */ err = snd_pcm_hw_params_set_rate_resample(handle, params, resample); if (err < 0) { printf ( "Resampling setup failed for playback: %s\n" , snd_strerror(err)); return err; } /* set the interleaved read/write format */ /*访问格式*/ err = snd_pcm_hw_params_set_access(handle, params, mode); if (err < 0) { printf ( "Access type not available for playback: %s\n" , snd_strerror(err)); return err; } /* set the sample format */ /*采样格式*/ err = snd_pcm_hw_params_set_format(handle, params, format); if (err < 0) { printf ( "Sample format not available for playback: %s\n" , snd_strerror(err)); return err; } /* set the count of channels */ /*音频声道*/ err = snd_pcm_hw_params_set_channels(handle, params, channels); if (err < 0) { printf ( "Channels count (%u) not available for playbacks: %s\n" , channels, snd_strerror(err)); return err; } /* set the stream rate */ /*采样率*/ rrate = rate; err = snd_pcm_hw_params_set_rate_near(handle, params, &rrate, 0); if (err < 0) { printf ( "Rate %uHz not available for playback: %s\n" , rate, snd_strerror(err)); return err; } if (rrate != rate) { printf ( "Rate doesn't match (requested %uHz, get %iHz)\n" , rate, err); return -EINVAL; } /* set the buffer time */ /*底层buffer区间,以时间为单位,500000=0.5s*/ err = snd_pcm_hw_params_set_buffer_time_near(handle, params, &buffer_time, &dir); if (err < 0) { printf ( "Unable to set buffer time %u for playback: %s\n" , buffer_time, snd_strerror(err)); return err; } err = snd_pcm_hw_params_get_buffer_size(params, &size); if (err < 0) { printf ( "Unable to get buffer size for playback: %s\n" , snd_strerror(err)); return err; } buffer_size = size; printf ( "buffer_size=%ld\n" ,buffer_size); /* set the period time */ /*底层period区间,以时间为单位,100000=0.1s*/ err = snd_pcm_hw_params_set_period_time_near(handle, params, &period_time, &dir); if (err < 0) { printf ( "Unable to set period time %u for playback: %s\n" , period_time, snd_strerror(err)); return err; } /*底层period区间,以字节为单位,44100*0.1=4410*/ err = snd_pcm_hw_params_get_period_size(params, &size, &dir); if (err < 0) { printf ( "Unable to get period size for playback: %s\n" , snd_strerror(err)); return err; } period_size = size; printf ( "period_size=%ld\n" ,period_size); /* write the parameters to device */ err = snd_pcm_hw_params(handle, params); if (err < 0) { printf ( "Unable to set hw params for playback: %s\n" , snd_strerror(err)); return err; } return 0; } /** * Initialize one data packet for reading or writing. * @param packet Packet to be initialized */ static void init_packet(AVPacket *packet) { av_init_packet(packet); /* Set the packet data and size so that it is recognized as being empty. */ packet->data = NULL; packet->size = 0; } int test_play_mp3( int argc, char *argv[]) { int rc; int size; int got_picture; int nb_data; bool pkt_pending = false ; int audio_stream_idx; char **hints, **n; char *alsa_device_name; if (argc < 2){ printf ( "please input filename!\r\n" ); return 1; } printf ( "test_play_file filename :%s\r\n" , argv[1]); snd_pcm_t *handle; snd_pcm_hw_params_t *hwparams; snd_pcm_hw_params_alloca(&hwparams); printf ( "Stream parameters are %uHz, %s, %u channels\n" , rate, snd_pcm_format_name(format), channels); int err; /* Enumerate sound devices */ err = snd_device_name_hint(-1, "pcm" , ( void ***)&hints); if (err != 0){ printf ( "please snd_device_name_hint:%d\r\n" , err); return err; } #if 1 snd_lib_error_set_handler(alsa_error_handler); #else /* Set a null error handler prior to enumeration to suppress errors */ snd_lib_error_set_handler(null_alsa_error_handler); #endif n = hints; while (*n != NULL) { char *name = snd_device_name_get_hint(*n, "NAME" ); if (name != NULL) { if (0 != strcmp ( "null" , name)){ snd_pcm_t* pcm; int pb_result = snd_pcm_open (&pcm, name, SND_PCM_STREAM_PLAYBACK, 0); if (pb_result >= 0) { printf ( "Try to open the device for playback - success\r\n" ); snd_pcm_close (pcm); pcm = NULL; alsa_device_name = name; break ; } printf ( "found device:%s\r\n" , alsa_device_name); //break; } } n++; } printf ( "Playback device is %s\n" , alsa_device_name); /* Install error handler after enumeration, otherwise we'll get many * error messages about invalid card/device ID. */ snd_lib_error_set_handler(alsa_error_handler); err = snd_device_name_free_hint(( void **)hints); err = snd_output_stdio_attach(&output, stdout, 0); if (err < 0) { printf ( "Output failed: %s\n" , snd_strerror(err)); return 0; } /*设置播放模式*/ err = snd_pcm_open(&handle, alsa_device_name, SND_PCM_STREAM_PLAYBACK, 0); if (err < 0) { printf ( "Playback open error: %s\n" , snd_strerror(err)); return 0; } /*设置参数*/ err = set_hwparams(handle, hwparams, mode); if (err < 0) { printf ( "Setting of hwparams failed: %s\n" , snd_strerror(err)); return 0; } //period_size大概是采样点数/帧——4410点/帧 //s16位代表两个字节,再加上双声道 //size公式=period_size*channels*16/8 size = (period_size * channels * snd_pcm_format_physical_width(format)) / 8; /* 2 bytes/sample, 1 channels */ printf ( "size:%d\n" ,size); char *buffer; buffer = ( char *) malloc (size); memset (buffer,0,size); char *in_name=argv[1]; //"鄧紫棋 - 睡公主.wav"; int ret; AVFormatContext* infmt_ctx = NULL; //创建输入封装器 ret=avformat_open_input(&infmt_ctx, in_name, NULL, NULL); if (ret != 0) { printf ( "failed alloc output context\n" ); return -1; } infmt_ctx->max_analyze_duration = 5*AV_TIME_BASE; //读取一部分视音频流并且获得一些相关的信息 ret=avformat_find_stream_info(infmt_ctx, NULL); if (ret < 0) { printf ( "Can't get stream info\n" ); avformat_close_input(&infmt_ctx); return -1; } audio_stream_idx = av_find_best_stream(infmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0); if (audio_stream_idx < 0) { printf ( "Can't find video stream in input file\n" ); avformat_close_input(&infmt_ctx); return -1; } AVCodecParameters *pCodecParameters = infmt_ctx->streams[audio_stream_idx]->codecpar; if (pCodecParameters == NULL){ printf ( "pCodecParameters is NULL\n" ); avformat_close_input(&infmt_ctx); return -1; } //找到解码器 const AVCodec* decodec = avcodec_find_decoder(pCodecParameters->codec_id); if (!decodec) { printf ( "not find decoder codec audio_stream_idx:%d codec_id:%d\n" , audio_stream_idx, pCodecParameters->codec_id); avformat_close_input(&infmt_ctx); return -1; } AVCodecContext *decodec_ctx = avcodec_alloc_context3(decodec); if (!decodec_ctx) { printf ( "Can't allocate decoder context\n" ); avformat_close_input(&infmt_ctx); return AVERROR(ENOMEM); } if (avcodec_parameters_to_context(decodec_ctx, pCodecParameters)<0){ printf ( "Cannot alloc codec context.\n" ); avformat_close_input(&infmt_ctx); return -1; } decodec_ctx->pkt_timebase = infmt_ctx->streams[audio_stream_idx]->time_base; #if 0 decodec_ctx->sample_rate = pCodecParameters->sample_rate; decodec_ctx->sample_fmt = (AVSampleFormat)pCodecParameters->format ; decodec_ctx->channels = pCodecParameters->channels; decodec_ctx->channel_layout = pCodecParameters->channel_layout; #endif// //打开解码器 ret = avcodec_open2(decodec_ctx, decodec, NULL); if (ret < 0) { printf ( "Could not open codec: %d\n" , ret); avformat_close_input(&infmt_ctx); return -1; } //查看输入封装内容 av_dump_format(infmt_ctx, 0, in_name,0); #if 1 AVFrame *pframePCM = av_frame_alloc(); pframePCM->format = AV_SAMPLE_FMT_S16; pframePCM->channel_layout = AV_CH_LAYOUT_STEREO; pframePCM->sample_rate = rate; pframePCM->nb_samples = period_size; pframePCM->channels = channels; av_frame_get_buffer(pframePCM, 0); #else uint8_t *converted_input_samples = NULL; int converted_input_samples_size = av_samples_alloc(&converted_input_samples, NULL, channels , period_size, AV_SAMPLE_FMT_S16, 0); #endif struct SwrContext *pcm_convert_ctx = swr_alloc(); if (!pcm_convert_ctx) { printf ( "Could not allocate resampler context\n" ); free (buffer); return -1; } swr_alloc_set_opts(pcm_convert_ctx, AV_CH_LAYOUT_STEREO, AV_SAMPLE_FMT_S16, pframePCM->sample_rate, av_get_default_channel_layout(decodec_ctx->channels), decodec_ctx->sample_fmt, decodec_ctx->sample_rate, 0, NULL); ret = swr_init(pcm_convert_ctx); if (ret<0) { printf ( "Failed to initialize the resampling context\n" ); free (buffer); return -1; } AVPacket *input_packet=av_packet_alloc(); init_packet(input_packet); AVFrame *pframeSRC = av_frame_alloc(); #if 0 pframeSRC->format = (AVSampleFormat)pCodecParameters->format ; pframeSRC->channel_layout = decodec_ctx->channel_layout; pframeSRC->sample_rate = decodec_ctx->sample_rate; pframeSRC->nb_samples = (20*decodec_ctx->sample_rate * channels * 2) / 8000;; pframeSRC->channels = channels; av_frame_get_buffer(pframeSRC, 0); #endif int finished = 0; int decode_ret = 0; int data_size = av_get_bytes_per_sample(decodec_ctx->sample_fmt); printf ( "data_size:%d, frame_size:%d, dst_samples:%d\n" , data_size, pCodecParameters->frame_size, pframePCM->nb_samples); while (!finished) { ret=av_read_frame(infmt_ctx, input_packet); if (ret != 0) { if (ret == AVERROR_EOF){ finished = 1; break ; } printf ( "fail to read_frame\n" ); break ; } //avcodec_send_packet/avcodec_receive_frame //针对多音轨问题处理 if (input_packet->stream_index != audio_stream_idx){ av_packet_unref(input_packet); continue ; } //解码获取初始音频 ret = avcodec_send_packet(decodec_ctx, input_packet); if (ret == AVERROR(EAGAIN)) { pkt_pending = true ; continue ; } if (ret < 0){ break ; } int no_resample = 0; do { decode_ret = avcodec_receive_frame(decodec_ctx, pframeSRC); if (decode_ret == AVERROR_EOF) { //取完数据帧复位解码器 //avcodec_flush_buffers(decodec_ctx); printf ( "avcodec_receive_frame eof\n" ); //av_packet_unref(&input_packet); break ; } else if (decode_ret < 0){ break ; } int source_samples = swr_get_out_samples(pcm_convert_ctx, pframeSRC->nb_samples); int out_samples = source_samples; // uint8_t *write_2_pcm = NULL; if (out_samples != pframePCM->nb_samples){ no_resample = 1; //读取到一帧音频或者视频 //MP3->PCM, ret=swr_convert(pcm_convert_ctx, pframePCM->data, pframePCM->nb_samples,( const uint8_t **)pframeSRC->extended_data, pframeSRC->nb_samples); if (ret <= 0) { printf ( "[0]out_samples:%d, pframeSRC->nb_samples:%d,ret:%d\n" , source_samples, pframeSRC->nb_samples, ret); continue ; } else { //printf("[2]out_samples:%d, pframeSRC->nb_samples:%d,ret:%d\n", source_samples, pframeSRC->nb_samples, ret); } write_2_pcm = pframePCM->data[0]; nb_data = ret; } else { printf ( "out_samples:%d, pframeSRC->nb_samples:%d \n" , out_samples, pframeSRC->nb_samples ); nb_data = out_samples; write_2_pcm = pframeSRC->data[0]; } //向硬件写入音频数据 rc = snd_pcm_writei(handle, write_2_pcm, out_samples); if (rc == -EPIPE) { printf ( "underrun occurred\n" ); err=snd_pcm_prepare(handle); if (err<0) { printf ( "can not recover from underrun: %s\n" ,snd_strerror(err)); } } else if (rc < 0) { fprintf (stderr, "error from writei: %s\n" ,snd_strerror(rc)); } else if (rc != ( int )nb_data) { fprintf (stderr, "short write, write %d frames\n" , rc); } } while (no_resample && decode_ret > 0); av_packet_unref(input_packet); } if (pcm_convert_ctx) { swr_free(&pcm_convert_ctx); } av_packet_free(&input_packet); if (pframeSRC) { av_frame_free(&pframeSRC); } #if 1 if (pframePCM) { av_frame_free(&pframePCM); } #endif if (decodec_ctx != NULL){ avcodec_close(decodec_ctx); avcodec_free_context(&decodec_ctx); } if (infmt_ctx != NULL) { avformat_close_input(&infmt_ctx); avformat_free_context(infmt_ctx); } snd_pcm_drain(handle); snd_pcm_close(handle); //free(converted_input_samples); free (buffer); free (alsa_device_name); return 0; } |
参考:https://blog.csdn.net/pk296256948/article/details/113695358
下一步:实现对rtsp流的请求;
--
2022/11/28更新:实现rtsp播放器,只需要将播放路径直接给一个rtsp的地址就可以了,是不是很简单!
-------------------广告线---------------
项目、合作,欢迎勾搭,邮箱:promall@qq.com
本文为呱牛笔记原创文章,转载无需和我联系,但请注明来自呱牛笔记 ,it3q.com