NDK29_FFmpeg内存释放

NDK开发汇总

一 native层内存泄漏

在上一篇文章中,实现了音视频播放与同步
NDK27_FFmpeg音视频同步
当退出播放后,native的内存没有降低,内存产生了泄漏,C++中需要对内存进行主动回收
在这里插入图片描述

二 内存回收

1 设置超时时间

连接是耗时操作,设置连接超时时间AVDictionary,并释放AVDictionary

AVDictionary *options = 0;
    //设置超时时间 微妙 超时时间5秒
av_dict_set(&options, "timeout", "5000000", 0);
int ret = avformat_open_input(&formatContext, dataSource, 0, &options);
av_dict_free(&options);

2 DNFFmpeg内存释放

  • 释放JavaCallHelper,不去调用java的方法去播放
  • 定义stop方法,start中申请的内存在stop中释放

start是多线程,不能直接结束,用pthread_join等待的话;由于stop在主线程,会卡顿,所以要开线程去释放


void DNFFmpeg::_prepare() {
	...
	AVDictionary *options = 0;
    //设置超时时间 微妙 超时时间5秒
    av_dict_set(&options, "timeout", "5000000", 0);
    int ret = avformat_open_input(&formatContext, dataSource, 0, &options);
    av_dict_free(&options);
	...
}

void DNFFmpeg::_start() {
    //1、读取媒体数据包(音视频数据包)
    int ret;
    while (isPlaying) {
        //读取文件的时候没有网络请求,一下子读完了,可能导致oom
        //特别是读本地文件的时候 一下子就读完了
        if (audioChannel && audioChannel->packets.size() > 100) {
            //10ms
            av_usleep(1000 * 10);
            continue;
        }
        if (videoChannel && videoChannel->packets.size() > 100) {
            av_usleep(1000 * 10);
            continue;
        }
        AVPacket *packet = av_packet_alloc();
        ret = av_read_frame(formatContext, packet);
        //=0成功 其他:失败
        if (ret == 0) {
            //stream_index 这一个流的一个序号
            if (audioChannel && packet->stream_index == audioChannel->id) {
                audioChannel->packets.push(packet);
            } else if (videoChannel && packet->stream_index == videoChannel->id) {
                videoChannel->packets.push(packet);
            }
        } else if (ret == AVERROR_EOF) {
            //读取完成 但是可能还没播放完
            if (audioChannel->packets.empty() && audioChannel->frames.empty()
                && videoChannel->packets.empty() && videoChannel->frames.empty()) {
                break;
            }
            //为什么这里要让它继续循环 而不是sleep
            //如果是做直播 ,可以sleep
            //如果要支持点播(播放本地文件) seek 后退
        } else {
            //
            break;
        }
    }
    isPlaying = 0;
    audioChannel->stop();
    videoChannel->stop();
};

void *async_stop(void *args) {
    DNFFmpeg *ffmpeg = static_cast<DNFFmpeg *>(args);
    //   等待prepare结束
    pthread_join(ffmpeg->pid, 0);
    ffmpeg->isPlaying = 0;
    // 保证 start线程结束
    pthread_join(ffmpeg->pid_play, 0);
    DELETE(ffmpeg->videoChannel);
    DELETE(ffmpeg->audioChannel);
    // 这时候释放就不会出现问题了
    if (ffmpeg->formatContext) {
        //先关闭读取 (关闭fileintputstream)
        avformat_close_input(&ffmpeg->formatContext);
        avformat_free_context(ffmpeg->formatContext);
        ffmpeg->formatContext = 0;
    }
    DELETE(ffmpeg);
    return 0;
}

void DNFFmpeg::stop() {
    isPlaying = 0;
    callHelper = 0;
    // formatContext
    pthread_create(&pid_stop, 0, aync_stop, this);
};

回收AVCodecContext 并定义stop方法用于AudioChannel和VideoChannel回收

  virtual ~BaseChannel() {
        frames.clear();
        packets.clear();
        if (avCodecContext) {
            avcodec_close(avCodecContext);
            avcodec_free_context(&avCodecContext);
            avCodecContext = 0;
        }
    }
    virtual void stop() = 0;

3 VideoChannel.stop

释放swsContext,队列停止工作,保证线程安全

void VideoChannel::render() {
	...
    isPlaying = 0;
    sws_freeContext(swsContext);
    swsContext = 0;
}

void VideoChannel::stop() {
		isPlaying = 0;
		frames.setWork(0);
		packets.setWork(0);
		pthread_join(pid_decode, 0);
		pthread_join(pid_render, 0);
	}
	

4 AudioChannel->stop

AVFrame使用完后释放,播放器、混音器、引擎释放,队列停止工作


int AudioChannel::getPcm() {
	...
	releaseAvFrame(&frame);
    return data_size;
}

void AudioChannel::stop() {
    isPlaying = 0;
    packets.setWork(0);
    frames.setWork(0);
    pthread_join(pid_audio_decode,0);
    pthread_join(pid_audio_play,0);
    if(swrContext){
        swr_free(&swrContext);
        swrContext = 0;
    }

    //释放播放器
    if(bqPlayerObject){
        (*bqPlayerObject)->Destroy(bqPlayerObject);
        bqPlayerObject = 0;
        bqPlayerInterface = 0;
        bqPlayerBufferQueueInterface = 0;
    }

    //释放混音器
    if(outputMixObject){
        (*outputMixObject)->Destroy(outputMixObject);
        outputMixObject = 0;
    }

    //释放引擎
    if(engineObject){
        (*engineObject)->Destroy(engineObject);
        engineObject = 0;
        engineInterface = 0;
    }
}

5 队列

当内容没有被添加到队列的时候,需要进行释放

if (work) {
            q.push(new_value);
            pthread_cond_signal(&cond);
            pthread_mutex_unlock(&mutex);
        }else{
            releaseCallback(&new_value);
        }

6 释放Window

	 public void setSurfaceView(SurfaceView surfaceView) {
        if(null != holder){
            holder.removeCallback(this);
        }
        holder = surfaceView.getHolder();
        holder.addCallback(this);
    }
	
	 public void release(){
        holder.removeCallback(this);
        native_release();
    }

extern "C"
JNIEXPORT void JNICALL
Java_com_cn_ray_player_DNPlayer_native_1stop(JNIEnv *env, jobject instance) {
    if (ffmpeg) {
        ffmpeg->stop();
    }
    DELETE(helper);
}
	
JNIEXPORT void JNICALL
Java_com_cn_ray_player_DNPlayer_native_1release(JNIEnv *env, jobject instance) {

    pthread_mutex_lock(&mutex);
    if (window) {
        //把老的释放
        ANativeWindow_release(window);
        window = 0;
    }
    pthread_mutex_unlock(&mutex);
}

7 读取限制

注意:AudioChannel和VideoChannel的frames也要限制大小,否则会OOM




void DNFFmpeg::_start() {
  //读取文件的时候没有网络请求,一下子读完了,可能导致oom
        //特别是读本地文件的时候 一下子就读完了
        if (audioChannel && audioChannel->packets.size() > 100) {
            //10ms
            av_usleep(1000 * 10);
            continue;
        }
		
		}
8 AudioChannel释放AVFrame
	int AudioChannel::getPcm() {
		...
		if (!isPlaying) {
			if (ret) {
				releaseAvFrame(&frame);
			}
        return data_size;
		}
		...
		releaseAvFrame(&frame);
		return data_size;
	}
		

三 进行回收后效果图

在这里插入图片描述

四 Demo

FFmpegDemo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在编译FFmpeg 6.0时,需要使用NDK 21版本进行相关操作。 首先,我们需要安装NDK并配置环境变量。可以从官方网站(developer.android.com/ndk)下载NDK安装包,并按照指示进行安装。安装完成后,将NDK的路径添加到系统环境变量中。 然后,我们需要获取FFmpeg 6.0版本的源代码。可以从FFmpeg的官方网站(ffmpeg.org)下载最新版本的源代码压缩包,并解压到本地目录中。 接下来,打开终端或命令提示符,并进入FFmpeg源代码所在的目录。执行以下命令进行配置: ./configure --arch=arm --cpu=armv7-a --target-os=android --enable-cross-compile --cross-prefix=arm-linux-androideabi- --sysroot=/path/to/ndk/sysroot --extra-cflags='-isysroot /path/to/ndk/sysroot/arch-arm -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 -mthumb' --extra-ldflags='-Wl,-rpath-link=/path/to/ndk/sysroot/usr/lib/arm-linux-androideabi/,-L/path/to/ndk/sysroot/usr/lib/arm-linux-androideabi/ -nostdlib' --prefix=/path/to/output/directory 请确保将上述命令中的"/path/to/ndk"替换为NDK的实际路径,"/path/to/output/directory"替换为输出目录的实际路径。 配置完成后,执行以下命令进行编译: make -j4 其中"-j4"表示使用4个线程进行编译,可以根据实际情况进行调整。 编译完成后,执行以下命令进行安装: make install 至此,FFmpeg 6.0的编译过程就完成了。编译后的二进制文件和相关库将安装到指定的输出目录中。 需要注意的是,在编译过程中可能会遇到一些依赖项缺失的情况,需要根据具体错误信息进行处理。另外,NDK版本和FFmpeg版本之间的兼容性也需要注意,有时需要向上或向下调整NDK版本以确保编译成功。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值