android基于ffmpeg的简单视频播发器 时间同步

2024-05-11 06:32

本文主要是介绍android基于ffmpeg的简单视频播发器 时间同步,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前面写了视频解码和音频解码,接下来要同步了

java代码

setContentView(R.layout.activity_main);
SurfaceView surfaceView = findViewById(R.id.surface_view);
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {@Override
    public void surfaceCreated(SurfaceHolder holder) {}@Override
    public void surfaceChanged(final SurfaceHolder holder, int format, int width, int height) {Thread audioThread = new Thread(){@Override
            public void run() {super.run();
                String videoPath = "/storage/emulated/0/baiduNetdisk/season09.mp4";
                audioPlay(videoPath);
            }};
        audioThread.start();
        Thread videoThread = new Thread(){@Override
            public void run() {super.run();
                String videoPath = "/storage/emulated/0/baiduNetdisk/season09.mp4";
                videoPlay(videoPath,holder.getSurface());
            }};
        videoThread.start();

    }@Override
    public void surfaceDestroyed(SurfaceHolder holder) {}
});
就是开两个线程主要还是c++代码

既然要同步线程,肯定是让快的线程等待慢的线程,通过前面的代码知道,视频线程比音频快,所以只能让视频线程进行等待,等待的话就用到了锁

pthread_mutex_t video_mutex;
pthread_cond_t video_cond;
还需要等待时间

long audio_time = 0;
long start_time = 0;

知道当前时间

long getCurrentTime() {struct timeval tv;
    gettimeofday(&tv,NULL);
    return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

计算等待时间的方法

timespec waitTime(long timeout_ms){struct timespec abstime;
    struct timeval now;
    gettimeofday(&now, NULL);
    long nsec = now.tv_usec * 1000 + (timeout_ms % 1000) * 1000000;
    abstime.tv_sec=now.tv_sec + nsec / 1000000000 + timeout_ms / 1000;
    abstime.tv_nsec=nsec % 1000000000;
    return abstime;
}
首先,要在音频线程计算出音频的时间

double nowTime = frame->pts * av_q2d(avStream->time_base);
long t = (long) (nowTime * 1000);
audio_time = t;
start_time = getCurrentTime();
然后在视频线程计算出时间差

double nowTime = yuvFrame->pts * av_q2d(avStream->time_base);
long t = (long) (nowTime * 1000);
long time = getCurrentTime() - start_time;
long wait = t - time - audio_time;
再让视频线程进行等待

struct timespec abstime = waitTime(wait);
pthread_mutex_lock(&video_mutex);
pthread_cond_timedwait(&video_cond, &video_mutex,&abstime);
pthread_mutex_unlock(&video_mutex);
这样就实现时间同步,误差是一定有的,几毫秒到十几毫秒吧

贴完整代码

pthread_mutex_t video_mutex;
pthread_cond_t video_cond;

long audio_time = 0;
long start_time = 0;

long getCurrentTime() {struct timeval tv;
    gettimeofday(&tv,NULL);
    return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}timespec waitTime(long timeout_ms){struct timespec abstime;
    struct timeval now;
    gettimeofday(&now, NULL);
    long nsec = now.tv_usec * 1000 + (timeout_ms % 1000) * 1000000;
    abstime.tv_sec=now.tv_sec + nsec / 1000000000 + timeout_ms / 1000;
    abstime.tv_nsec=nsec % 1000000000;
    return abstime;
}extern "C"
JNIEXPORT void JNICALL
Java_com_example_ffmpegrun_MainActivity_videoPlay(JNIEnv *env, jobject instance, jstring path_,
                                                  jobject surface) {const char *path = env->GetStringUTFChars(path_, 0);
    
    // TODO

    pthread_mutex_init (&video_mutex,NULL);
    pthread_cond_init(&video_cond,NULL);


    av_register_all();
    AVFormatContext *fmt_ctx = avformat_alloc_context();
    if (avformat_open_input(&fmt_ctx, path, NULL, NULL) < 0) {return;
    }if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {return;
    }AVStream *avStream = NULL;
    int video_stream_index = -1;
    for (int i = 0; i < fmt_ctx->nb_streams; i++) {if (fmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {avStream = fmt_ctx->streams[i];
            video_stream_index = i;
            break;
        }}if (video_stream_index == -1) {return;
    }AVCodecContext *codec_ctx = avcodec_alloc_context3(NULL);
    avcodec_parameters_to_context(codec_ctx, avStream->codecpar);

    AVCodec *avCodec = avcodec_find_decoder(codec_ctx->codec_id);
    if (avcodec_open2(codec_ctx, avCodec, NULL) < 0) {return;
    }ANativeWindow* nativeWindow = ANativeWindow_fromSurface(env,surface);

    AVFrame *yuvFrame = av_frame_alloc();

    EGLUtils *eglUtils = new EGLUtils();
    eglUtils->initEGL(nativeWindow);

    OpenGLUtils *openGLUtils = new OpenGLUtils();
    openGLUtils->surfaceCreated();
    openGLUtils->surfaceChanged(eglUtils->getWidth(),eglUtils->getHeight());
    openGLUtils->initTexture(codec_ctx->width,codec_ctx->height);

    int y_size = codec_ctx->width * codec_ctx->height;
    AVPacket *pkt = (AVPacket *) malloc(sizeof(AVPacket));
    av_new_packet(pkt, y_size);
    int ret;
    while (1) {if (av_read_frame(fmt_ctx, pkt) < 0) {av_packet_unref(pkt);
            break;
        }if (pkt->stream_index == video_stream_index) {ret = avcodec_send_packet(codec_ctx, pkt);
            if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {av_packet_unref(pkt);
                continue;
            }ret = avcodec_receive_frame(codec_ctx, yuvFrame);
            if (ret < 0 && ret != AVERROR_EOF) {av_packet_unref(pkt);
                continue;
            }double nowTime = yuvFrame->pts * av_q2d(avStream->time_base);
            long t = (long) (nowTime * 1000);
            long time = getCurrentTime() - start_time;
            long wait = t - time - audio_time;

            struct timespec abstime = waitTime(wait);
            pthread_mutex_lock(&video_mutex);
            pthread_cond_timedwait(&video_cond, &video_mutex,&abstime);
            pthread_mutex_unlock(&video_mutex);

            openGLUtils->updateTexture(yuvFrame->width,yuvFrame->height,yuvFrame->data[0],yuvFrame->data[1],yuvFrame->data[2]);
            openGLUtils->surfaceDraw();
            eglUtils->drawEGL();

            av_packet_unref(pkt);
        }av_packet_unref(pkt);
    }av_frame_free(&yuvFrame);
    avcodec_close(codec_ctx);
    avformat_close_input(&fmt_ctx);

    pthread_cond_destroy(&video_cond);
    pthread_mutex_destroy(&video_mutex);

    env->ReleaseStringUTFChars(path_, path);
}
#define MAX_AUDIO_FRME_SIZE 48000 * 4
extern "C"
JNIEXPORT void JNICALL
Java_com_example_ffmpegrun_MainActivity_audioPlay(JNIEnv *env, jobject instance, jstring path_) {const char *path = env->GetStringUTFChars(path_, 0);

    // TODO

    av_register_all();
    AVFormatContext *fmt_ctx = avformat_alloc_context();
    if (avformat_open_input(&fmt_ctx, path, NULL, NULL) < 0) {return;
    }if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {return;
    }AVStream *avStream = NULL;
    int audio_stream_index = -1;
    for (int i = 0; i < fmt_ctx->nb_streams; i++) {if (fmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {avStream = fmt_ctx->streams[i];
            audio_stream_index = i;
            break;
        }}if (audio_stream_index == -1) {return;
    }AVCodecContext *codec_ctx = avcodec_alloc_context3(NULL);
    avcodec_parameters_to_context(codec_ctx, avStream->codecpar);

    AVCodec *avCodec = avcodec_find_decoder(codec_ctx->codec_id);
    if (avcodec_open2(codec_ctx, avCodec, NULL) < 0) {return;
    }SwrContext *swr_ctx = swr_alloc();

    enum AVSampleFormat in_sample_fmt = codec_ctx->sample_fmt;

    enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;

    int in_sample_rate = codec_ctx->sample_rate;

    int out_sample_rate = in_sample_rate;

    uint64_t in_ch_layout = codec_ctx->channel_layout;

    uint64_t out_ch_layout = AV_CH_LAYOUT_STEREO;


    swr_alloc_set_opts(swr_ctx,
                       out_ch_layout, out_sample_fmt, out_sample_rate,
                       in_ch_layout, in_sample_fmt, in_sample_rate,
                       0, NULL);
    swr_init(swr_ctx);

    int out_channel_nb = av_get_channel_layout_nb_channels(out_ch_layout);

    jclass player_class = env->GetObjectClass(instance);
    jmethodID create_audio_track_mid = env->GetMethodID(player_class, "createAudio",
                                                        "(II)Landroid/media/AudioTrack;");
    jobject audio_track = env->CallObjectMethod(instance, create_audio_track_mid,
                                                out_sample_rate, out_channel_nb);


    jclass audio_track_class = env->GetObjectClass(audio_track);
    jmethodID audio_track_play_mid = env->GetMethodID(audio_track_class, "play", "()V");
    jmethodID audio_track_stop_mid = env->GetMethodID(audio_track_class, "stop", "()V");
    env->CallVoidMethod(audio_track, audio_track_play_mid);

    jmethodID audio_track_write_mid = env->GetMethodID(audio_track_class, "write",
                                                       "([BII)I");


    uint8_t *out_buffer = (uint8_t *) av_malloc(MAX_AUDIO_FRME_SIZE);

    AVPacket *pkt = (AVPacket *) malloc(sizeof(AVPacket));
    int ret;
    while (1) {if (av_read_frame(fmt_ctx, pkt) < 0){av_packet_unref(pkt);
            break;
        }ret = avcodec_send_packet(codec_ctx, pkt);
        if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {av_packet_unref(pkt);
            continue;
        }AVFrame *frame = av_frame_alloc();

        ret = avcodec_receive_frame(codec_ctx, frame);
        if (ret < 0 && ret != AVERROR_EOF) {av_packet_unref(pkt);
            av_frame_free(&frame);
            continue;
        }double nowTime = frame->pts * av_q2d(avStream->time_base);
        long t = (long) (nowTime * 1000);
        audio_time = t;
        start_time = getCurrentTime();

        swr_convert(swr_ctx, &out_buffer, MAX_AUDIO_FRME_SIZE,
                    (const uint8_t **) frame->data,
                    frame->nb_samples);
        int out_buffer_size = av_samples_get_buffer_size(NULL, out_channel_nb,
                                                         frame->nb_samples, out_sample_fmt,
                                                         1);

        jbyteArray audio_sample_array = env->NewByteArray(out_buffer_size);
        jbyte *sample_bytep = env->GetByteArrayElements(audio_sample_array, NULL);

        memcpy(sample_bytep, out_buffer, (size_t) out_buffer_size);
        env->ReleaseByteArrayElements(audio_sample_array, sample_bytep, 0);


        env->CallIntMethod(audio_track, audio_track_write_mid,
                           audio_sample_array, 0, out_buffer_size);

        env->DeleteLocalRef(audio_sample_array);

        av_frame_free(&frame);

        av_packet_unref(pkt);
    }env->CallVoidMethod(audio_track, audio_track_stop_mid);
    av_free(out_buffer);
    swr_free(&swr_ctx);
    avcodec_close(codec_ctx);
    avformat_close_input(&fmt_ctx);

    env->ReleaseStringUTFChars(path_, path);
}

2017/11/6更新

发现个bug修改一下

声音解码时在av_read_frame()之后加个判断

if(pkt->stream_index == audio_stream_index)

然后再进行播放处理,因为av_read_frame()得到的数据有视频数据和音频数据,因为这个线程是专门处理声音的,所以把视频数据给过滤掉,就像视频线程会过滤音频数据一样









这篇关于android基于ffmpeg的简单视频播发器 时间同步的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/978763

相关文章

基于Linux的ffmpeg python的关键帧抽取

《基于Linux的ffmpegpython的关键帧抽取》本文主要介绍了基于Linux的ffmpegpython的关键帧抽取,实现以按帧或时间间隔抽取关键帧,文中通过示例代码介绍的非常详细,对大家的学... 目录1.FFmpeg的环境配置1) 创建一个虚拟环境envjavascript2) ffmpeg-py

C++ 函数 strftime 和时间格式示例详解

《C++函数strftime和时间格式示例详解》strftime是C/C++标准库中用于格式化日期和时间的函数,定义在ctime头文件中,它将tm结构体中的时间信息转换为指定格式的字符串,是处理... 目录C++ 函数 strftipythonme 详解一、函数原型二、功能描述三、格式字符串说明四、返回值五

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

从基础到进阶详解Pandas时间数据处理指南

《从基础到进阶详解Pandas时间数据处理指南》Pandas构建了完整的时间数据处理生态,核心由四个基础类构成,Timestamp,DatetimeIndex,Period和Timedelta,下面我... 目录1. 时间数据类型与基础操作1.1 核心时间对象体系1.2 时间数据生成技巧2. 时间索引与数据

基于Python实现一个简单的题库与在线考试系统

《基于Python实现一个简单的题库与在线考试系统》在当今信息化教育时代,在线学习与考试系统已成为教育技术领域的重要组成部分,本文就来介绍一下如何使用Python和PyQt5框架开发一个名为白泽题库系... 目录概述功能特点界面展示系统架构设计类结构图Excel题库填写格式模板题库题目填写格式表核心数据结构

Linux实现线程同步的多种方式汇总

《Linux实现线程同步的多种方式汇总》本文详细介绍了Linux下线程同步的多种方法,包括互斥锁、自旋锁、信号量以及它们的使用示例,通过这些同步机制,可以解决线程安全问题,防止资源竞争导致的错误,示例... 目录什么是线程同步?一、互斥锁(单人洗手间规则)适用场景:特点:二、条件变量(咖啡厅取餐系统)工作流

Mysql的主从同步/复制的原理分析

《Mysql的主从同步/复制的原理分析》:本文主要介绍Mysql的主从同步/复制的原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录为什么要主从同步?mysql主从同步架构有哪些?Mysql主从复制的原理/整体流程级联复制架构为什么好?Mysql主从复制注意

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

C/C++ chrono简单使用场景示例详解

《C/C++chrono简单使用场景示例详解》:本文主要介绍C/C++chrono简单使用场景示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友... 目录chrono使用场景举例1 输出格式化字符串chrono使用场景China编程举例1 输出格式化字符串示

Python使用FFmpeg实现高效音频格式转换工具

《Python使用FFmpeg实现高效音频格式转换工具》在数字音频处理领域,音频格式转换是一项基础但至关重要的功能,本文主要为大家介绍了Python如何使用FFmpeg实现强大功能的图形化音频转换工具... 目录概述功能详解软件效果展示主界面布局转换过程截图完成提示开发步骤详解1. 环境准备2. 项目功能结