feat: 内置 FFmpeg 音频扩展软解 AC3/DTS
新增 player-media3-ffmpeg:media3 1.11.1 的 decoder_ffmpeg 源码 + 自带 FFmpeg 6.0.1 静态库(arm64-v8a / armeabi-v7a,ac3/eac3/truehd/mlp/dca), 以 EXTENSION_RENDERER_MODE_PREFER 接入,AAC 等仍走系统 MediaCodec。 音轨选择改为仅在默认音轨不可解码时才自动改选;提示文案去掉环绕音频 警告,只保留真正无法解码的情况。构建脚本与依赖下载见 tools/ffmpeg。
This commit is contained in:
1 parent
71a5d5f72e
commit
40435701fb
17 files changed
+1382
-23
No files matched your search
@@ -55,8 +55,6 @@ import com.ttstd.player.render.TextureViewBinding
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
private val PASSTHROUGH_AUDIO = setOf("audio/ac3", "audio/eac3", "audio/vnd.dts", "audio/vnd.dts.hd", "audio/truehd")
|
||||
|
||||
/** 播放界面只拥有 Surface 与控件;内核/观看会话由 PlayerModel 管理。 */
|
||||
class PlayerActivity : AppCompatActivity() {
|
||||
private lateinit var model: PlayerModel
|
||||
@@ -123,7 +121,6 @@ class PlayerActivity : AppCompatActivity() {
|
||||
val audioTracks = state.tracks.filter { it.type == TrackType.AUDIO }
|
||||
val selectedAudio = audioTracks.firstOrNull { it.selected } ?: audioTracks.firstOrNull()
|
||||
val audioUnsupported = selectedAudio != null && !selectedAudio.supported
|
||||
val audioWarning = audioUnsupported || selectedAudio?.mimeType in PASSTHROUGH_AUDIO
|
||||
val centerText = when {
|
||||
remote == "dlna" -> "正在 ${dlna.device} 播放\n${dlna.error ?: "可关闭页面,投屏会继续"}"
|
||||
loading || state.phase == PlaybackPhase.PREPARING || state.phase == PlaybackPhase.BUFFERING -> "正在缓冲…"
|
||||
@@ -147,11 +144,10 @@ class PlayerActivity : AppCompatActivity() {
|
||||
}
|
||||
LaunchedEffect(state.playWhenReady, ratio, remote) { updatePipParams() }
|
||||
LaunchedEffect(pip) { if (pip) controlsVisible = false else controlsVisible = true }
|
||||
LaunchedEffect(current?.ref?.id, audioWarning, audioUnsupported) {
|
||||
if (audioWarning) Toast.makeText(
|
||||
LaunchedEffect(current?.ref?.id, audioUnsupported) {
|
||||
if (audioUnsupported) Toast.makeText(
|
||||
this@PlayerActivity,
|
||||
if (audioUnsupported) "当前音轨设备不支持,将静音播放;可切换音轨或使用 AAC 转码版本"
|
||||
else "当前音轨为 AC3/DTS 环绕音频,需设备/功放支持;若无声音请切换音轨或使用 AAC 转码版本",
|
||||
"当前音轨设备无法解码,将静音播放;可在“更多 → 音轨”切换其他音轨",
|
||||
Toast.LENGTH_LONG,
|
||||
).show()
|
||||
}
|
||||
@@ -198,7 +194,7 @@ class PlayerActivity : AppCompatActivity() {
|
||||
dlna = dlna,
|
||||
landscape = true,
|
||||
fromServer = current?.ref?.accountId != null,
|
||||
audioWarning = audioWarning,
|
||||
audioUnsupported = audioUnsupported,
|
||||
modifier = Modifier.align(Alignment.BottomCenter),
|
||||
onSeek = ::seekTo,
|
||||
onSeekBy = ::seekBy,
|
||||
@@ -243,7 +239,7 @@ class PlayerActivity : AppCompatActivity() {
|
||||
dlna = dlna,
|
||||
landscape = false,
|
||||
fromServer = current?.ref?.accountId != null,
|
||||
audioWarning = audioWarning,
|
||||
audioUnsupported = audioUnsupported,
|
||||
onSeek = ::seekTo,
|
||||
onSeekBy = ::seekBy,
|
||||
onToggle = { togglePlayback(remote, dlna) },
|
||||
@@ -430,7 +426,7 @@ class PlayerActivity : AppCompatActivity() {
|
||||
dlna: DlnaUiState,
|
||||
landscape: Boolean,
|
||||
fromServer: Boolean,
|
||||
audioWarning: Boolean,
|
||||
audioUnsupported: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
onSeek: (Long) -> Unit,
|
||||
onSeekBy: (Long) -> Unit,
|
||||
@@ -483,7 +479,7 @@ class PlayerActivity : AppCompatActivity() {
|
||||
Text(
|
||||
(if (remote != null) "投屏中 · 点击右上角投屏管理连接"
|
||||
else "${if (fromServer) "媒体来源播放" else "本机 / 在线播放"} · 双击画面快进 / 后退\n音轨、字幕、倍速与显示选项在更多菜单中") +
|
||||
if (audioWarning) "\n当前音轨可能需要设备/功放支持,若无声可切换音轨或转码" else "",
|
||||
if (audioUnsupported) "\n正在播放的音轨设备无法解码,可切换其他音轨" else "",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = AppMuted,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
@@ -544,7 +540,7 @@ class PlayerActivity : AppCompatActivity() {
|
||||
val tracks = state.tracks.filter { it.type == dialog.type }
|
||||
val prefix = if (dialog.type == TrackType.TEXT) "关闭字幕" else "自动选择"
|
||||
val labels = listOf(prefix) + tracks.map {
|
||||
val note = if (!it.supported) "(设备不支持)" else if (it.mimeType in PASSTHROUGH_AUDIO) "(可能需要设备支持)" else ""
|
||||
val note = if (!it.supported) "(设备不支持)" else ""
|
||||
"${it.label ?: it.language ?: "轨道 ${it.id}"}${if (it.selected) " ✓" else ""}$note"
|
||||
}
|
||||
ChoiceDialog(
|
||||
|
||||
+2
-1
@@ -8,7 +8,8 @@
|
||||
|
||||
- 本地媒体库:MediaStore 扫描机身存储与可插拔卷(U 盘);API 29+ 用 `getExternalVolumeNames` 遍历多卷,23-28 回退主卷;结果排序后持久化,无权限时回退缓存。列表支持标题搜索、按名称/时长/最近修改/大小排序、按文件夹(`BUCKET_DISPLAY_NAME`)过滤。缩略图内存 LruCache + 私有目录磁盘缓存,key 由 URI、修改时间与大小派生,重扫或重启复用。
|
||||
- 画中画与后台续播:API 26+ 播放中按 Home 进入画中画继续播放;API 23-25 由 `LocalPlaybackService` 前台媒体服务 + MediaSession 通知栏续播,命令转发全局引擎,暂停或结束自动停止。返回键、退出播放页、进入画中画失败时立即暂停。
|
||||
- 字幕与音轨:Matroska 默认字幕未映射时自动选首条文本轨(用户关闭后不再自动开启);普通文件无视频轨 1.5 秒、READY 后 8 秒无首帧分别报 `NO_VIDEO_TRACK` / `NO_FIRST_FRAME`;音轨带 `supported/mimeType`,AC3/DTS passthrough 在无常规编码时自动避开并提示。
|
||||
- 字幕与音轨:Matroska 默认字幕未映射时自动选首条文本轨(用户关闭后不再自动开启);普通文件无视频轨 1.5 秒、READY 后 8 秒无首帧分别报 `NO_VIDEO_TRACK` / `NO_FIRST_FRAME`;音轨带 `supported/mimeType`,默认音轨不可解码时才自动改选可解码音轨。
|
||||
- FFmpeg 音频扩展(`player-media3-ffmpeg`):内置 `libffmpegJNI.so`(FFmpeg 6.0.1,arm64-v8a / armeabi-v7a),启用 ac3/eac3/truehd/mlp/dca 软解;`EXTENSION_RENDERER_MODE_PREFER`,扩展只声明上述格式,AAC/Opus 仍走 MediaCodec。x86/x86_64(模拟器)无内置 so,回落系统解码并给出音轨不支持提示。
|
||||
- 卡顿与掉帧统计:Ended/换源/释放时汇总缓冲次数、缓冲时长、播放时长与掉帧数(`JankSummary`),telemetry 记录 `jankRate = bufferingMs / playbackMs`。
|
||||
- 运行中自动软解回退:解码类错误(初始化/解码/格式不支持/超出能力)时自动切换到 `SOFTWARE_ONLY` 一次,恢复进度与播放意图(`AutoFallback`)。
|
||||
- 清晰度降级:自适应流(HLS/DASH/SmoothStreaming)缓冲达 3 次或累计 8 秒时,限制到 720p / 1.5Mbps 一次(`QualityDegraded`),换源时清除上限。
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# player-media3-ffmpeg
|
||||
|
||||
Media3 `decoder_ffmpeg` 扩展的本地化副本,用于补齐 AC3 / E-AC3 / DTS / TrueHD 音频软解。
|
||||
|
||||
- 源码来源:`androidx/media` 仓库 tag `1.11.1`,`libraries/decoder_ffmpeg`(Apache-2.0,文件头保留原始版权)。
|
||||
- 保留原包名 `androidx.media3.decoder.ffmpeg`:`DefaultRenderersFactory` 通过反射按类名加载 `FfmpegAudioRenderer`,改名会失去自动发现。
|
||||
- 只包含音频渲染器;未编译 FFmpeg 视频解码器,因此不会接管 H.264/HEVC。
|
||||
- `src/main/jniLibs/<abi>/libffmpegJNI.so` 为预编译产物(FFmpeg 6.0.1,LGPL,静态链接 avcodec/avutil/swresample),
|
||||
仅启用 `ac3 eac3 truehd dca` 解码器。重新生成见 `tools/ffmpeg/build_ffmpeg.sh`。
|
||||
- 使用方式:`DefaultRenderersFactory.setExtensionRendererMode(EXTENSION_RENDERER_MODE_PREFER)`;
|
||||
扩展渲染器只声明自己支持的格式(上述环绕音频),AAC/Opus 等仍走系统 MediaCodec。
|
||||
@@ -0,0 +1,25 @@
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.ttstd.player.ffmpeg"
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 23
|
||||
ndk { abiFilters += listOf("armeabi-v7a", "arm64-v8a") }
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api("androidx.media3:media3-exoplayer:1.11.1")
|
||||
api("androidx.media3:media3-decoder:1.11.1")
|
||||
compileOnly("androidx.annotation:annotation:1.6.0")
|
||||
compileOnly("org.checkerframework:checker-qual:3.42.0")
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
extern "C" {
|
||||
#ifdef __cplusplus
|
||||
#define __STDC_CONSTANT_MACROS
|
||||
#ifdef _STDINT_H
|
||||
#undef _STDINT_H
|
||||
#endif
|
||||
#include <stdint.h>
|
||||
#endif
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavutil/channel_layout.h>
|
||||
#include <libavutil/error.h>
|
||||
#include <libavutil/opt.h>
|
||||
#include <libswresample/swresample.h>
|
||||
}
|
||||
|
||||
#define LOG_TAG "ffmpeg_jni"
|
||||
#define LOGE(...) \
|
||||
((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
|
||||
#define LOGD(...) \
|
||||
((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
|
||||
|
||||
#define ERROR_STRING_BUFFER_LENGTH 256
|
||||
|
||||
// Output format corresponding to AudioFormat.ENCODING_PCM_16BIT.
|
||||
static const AVSampleFormat OUTPUT_FORMAT_PCM_16BIT = AV_SAMPLE_FMT_S16;
|
||||
// Output format corresponding to AudioFormat.ENCODING_PCM_FLOAT.
|
||||
static const AVSampleFormat OUTPUT_FORMAT_PCM_FLOAT = AV_SAMPLE_FMT_FLT;
|
||||
|
||||
// LINT.IfChange
|
||||
static const int AUDIO_DECODER_ERROR_INVALID_DATA = -1;
|
||||
static const int AUDIO_DECODER_ERROR_OTHER = -2;
|
||||
// LINT.ThenChange(../java/androidx/media3/decoder/ffmpeg/FfmpegAudioDecoder.java)
|
||||
|
||||
static jmethodID growOutputBufferMethod;
|
||||
|
||||
/**
|
||||
* Returns the AVCodec with the specified name, or NULL if it is not available.
|
||||
*/
|
||||
const AVCodec* getCodecByName(JNIEnv* env, jstring codecName);
|
||||
|
||||
/**
|
||||
* Allocates and opens a new AVCodecContext for the specified codec, passing the
|
||||
* provided extraData as initialization data for the decoder if it is non-NULL.
|
||||
* Returns the created context.
|
||||
*/
|
||||
AVCodecContext* createContext(JNIEnv* env, const AVCodec* codec,
|
||||
jbyteArray extraData, jboolean outputFloat,
|
||||
jint rawSampleRate, jint rawChannelCount);
|
||||
|
||||
struct GrowOutputBufferCallback {
|
||||
uint8_t* operator()(int requiredSize) const;
|
||||
|
||||
JNIEnv* env;
|
||||
jobject thiz;
|
||||
jobject decoderOutputBuffer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Decodes the packet into the output buffer, returning the number of bytes
|
||||
* written, or a negative AUDIO_DECODER_ERROR constant value in the case of an
|
||||
* error.
|
||||
*/
|
||||
int decodePacket(AVCodecContext* context, AVPacket* packet,
|
||||
uint8_t* outputBuffer, int outputSize,
|
||||
GrowOutputBufferCallback growBuffer);
|
||||
|
||||
/**
|
||||
* Transforms ffmpeg AVERROR into a negative AUDIO_DECODER_ERROR constant value.
|
||||
*/
|
||||
int transformError(int errorNumber);
|
||||
|
||||
/**
|
||||
* Outputs a log message describing the avcodec error number.
|
||||
*/
|
||||
void logError(const char* functionName, int errorNumber);
|
||||
|
||||
/**
|
||||
* Releases the specified context.
|
||||
*/
|
||||
void releaseContext(AVCodecContext* context);
|
||||
|
||||
jstring ffmpegGetVersion(JNIEnv* env, jobject thiz) {
|
||||
return env->NewStringUTF(LIBAVCODEC_IDENT);
|
||||
}
|
||||
|
||||
jint ffmpegGetInputBufferPaddingSize(JNIEnv* env, jobject thiz) {
|
||||
return (jint)AV_INPUT_BUFFER_PADDING_SIZE;
|
||||
}
|
||||
|
||||
jboolean ffmpegHasDecoder(JNIEnv* env, jobject thiz, jstring codecName) {
|
||||
return getCodecByName(env, codecName) != NULL;
|
||||
}
|
||||
|
||||
jlong ffmpegInitialize(JNIEnv* env, jobject thiz, jstring codecName,
|
||||
jbyteArray extraData, jboolean outputFloat,
|
||||
jint rawSampleRate, jint rawChannelCount) {
|
||||
const AVCodec* codec = getCodecByName(env, codecName);
|
||||
if (!codec) {
|
||||
LOGE("Codec not found.");
|
||||
return 0L;
|
||||
}
|
||||
return (jlong)createContext(env, codec, extraData, outputFloat, rawSampleRate,
|
||||
rawChannelCount);
|
||||
}
|
||||
|
||||
jint ffmpegDecode(JNIEnv* env, jobject thiz, jlong context, jobject inputData,
|
||||
jint inputSize, jobject decoderOutputBuffer,
|
||||
jobject outputData, jint outputSize) {
|
||||
if (!context) {
|
||||
LOGE("Context must be non-NULL.");
|
||||
return -1;
|
||||
}
|
||||
if (!inputData || !decoderOutputBuffer || !outputData) {
|
||||
LOGE("Input and output buffers must be non-NULL.");
|
||||
return -1;
|
||||
}
|
||||
if (inputSize < 0) {
|
||||
LOGE("Invalid input buffer size: %d.", inputSize);
|
||||
return -1;
|
||||
}
|
||||
if (outputSize < 0) {
|
||||
LOGE("Invalid output buffer length: %d", outputSize);
|
||||
return -1;
|
||||
}
|
||||
uint8_t* inputBuffer = (uint8_t*)env->GetDirectBufferAddress(inputData);
|
||||
uint8_t* outputBuffer = (uint8_t*)env->GetDirectBufferAddress(outputData);
|
||||
AVPacket* packet = av_packet_alloc();
|
||||
if (!packet) {
|
||||
LOGE("Failed to allocate packet.");
|
||||
return -1;
|
||||
}
|
||||
packet->data = inputBuffer;
|
||||
packet->size = inputSize;
|
||||
const int ret =
|
||||
decodePacket((AVCodecContext*)context, packet, outputBuffer, outputSize,
|
||||
GrowOutputBufferCallback{env, thiz, decoderOutputBuffer});
|
||||
av_packet_free(&packet);
|
||||
return ret;
|
||||
}
|
||||
|
||||
uint8_t* GrowOutputBufferCallback::operator()(int requiredSize) const {
|
||||
jobject newOutputData = env->CallObjectMethod(
|
||||
thiz, growOutputBufferMethod, decoderOutputBuffer, requiredSize);
|
||||
if (env->ExceptionCheck()) {
|
||||
LOGE("growOutputBuffer() failed");
|
||||
env->ExceptionDescribe();
|
||||
return nullptr;
|
||||
}
|
||||
return static_cast<uint8_t*>(env->GetDirectBufferAddress(newOutputData));
|
||||
}
|
||||
|
||||
jint ffmpegGetChannelCount(JNIEnv* env, jobject thiz, jlong context) {
|
||||
if (!context) {
|
||||
LOGE("Context must be non-NULL.");
|
||||
return -1;
|
||||
}
|
||||
return ((AVCodecContext*)context)->ch_layout.nb_channels;
|
||||
}
|
||||
|
||||
jint ffmpegGetSampleRate(JNIEnv* env, jobject thiz, jlong context) {
|
||||
if (!context) {
|
||||
LOGE("Context must be non-NULL.");
|
||||
return -1;
|
||||
}
|
||||
return ((AVCodecContext*)context)->sample_rate;
|
||||
}
|
||||
|
||||
jlong ffmpegReset(JNIEnv* env, jobject thiz, jlong jContext,
|
||||
jbyteArray extraData) {
|
||||
AVCodecContext* context = (AVCodecContext*)jContext;
|
||||
if (!context) {
|
||||
LOGE("Tried to reset without a context.");
|
||||
return 0L;
|
||||
}
|
||||
|
||||
AVCodecID codecId = context->codec_id;
|
||||
if (codecId == AV_CODEC_ID_TRUEHD) {
|
||||
jboolean outputFloat =
|
||||
(jboolean)(context->request_sample_fmt == OUTPUT_FORMAT_PCM_FLOAT);
|
||||
// Release and recreate the context if the codec is TrueHD.
|
||||
// TODO: Figure out why flushing doesn't work for this codec.
|
||||
releaseContext(context);
|
||||
const AVCodec* codec = avcodec_find_decoder(codecId);
|
||||
if (!codec) {
|
||||
LOGE("Unexpected error finding codec %d.", codecId);
|
||||
return 0L;
|
||||
}
|
||||
return (jlong)createContext(env, codec, extraData, outputFloat,
|
||||
/* rawSampleRate= */ -1,
|
||||
/* rawChannelCount= */ -1);
|
||||
}
|
||||
|
||||
avcodec_flush_buffers(context);
|
||||
return (jlong)context;
|
||||
}
|
||||
|
||||
void ffmpegRelease(JNIEnv* env, jobject thiz, jlong context) {
|
||||
if (context) {
|
||||
releaseContext((AVCodecContext*)context);
|
||||
}
|
||||
}
|
||||
|
||||
const AVCodec* getCodecByName(JNIEnv* env, jstring codecName) {
|
||||
if (!codecName) {
|
||||
return NULL;
|
||||
}
|
||||
const char* codecNameChars = env->GetStringUTFChars(codecName, NULL);
|
||||
const AVCodec* codec = avcodec_find_decoder_by_name(codecNameChars);
|
||||
env->ReleaseStringUTFChars(codecName, codecNameChars);
|
||||
return codec;
|
||||
}
|
||||
|
||||
AVCodecContext* createContext(JNIEnv* env, const AVCodec* codec,
|
||||
jbyteArray extraData, jboolean outputFloat,
|
||||
jint rawSampleRate, jint rawChannelCount) {
|
||||
AVCodecContext* context = avcodec_alloc_context3(codec);
|
||||
if (!context) {
|
||||
LOGE("Failed to allocate context.");
|
||||
return NULL;
|
||||
}
|
||||
context->request_sample_fmt =
|
||||
outputFloat ? OUTPUT_FORMAT_PCM_FLOAT : OUTPUT_FORMAT_PCM_16BIT;
|
||||
if (extraData) {
|
||||
jsize size = env->GetArrayLength(extraData);
|
||||
context->extradata_size = size;
|
||||
context->extradata =
|
||||
(uint8_t*)av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
|
||||
if (!context->extradata) {
|
||||
LOGE("Failed to allocate extradata.");
|
||||
releaseContext(context);
|
||||
return NULL;
|
||||
}
|
||||
env->GetByteArrayRegion(extraData, 0, size, (jbyte*)context->extradata);
|
||||
}
|
||||
if (context->codec_id == AV_CODEC_ID_PCM_MULAW ||
|
||||
context->codec_id == AV_CODEC_ID_PCM_ALAW) {
|
||||
context->sample_rate = rawSampleRate;
|
||||
av_channel_layout_default(&context->ch_layout, rawChannelCount);
|
||||
}
|
||||
context->err_recognition = AV_EF_IGNORE_ERR;
|
||||
int result = avcodec_open2(context, codec, NULL);
|
||||
if (result < 0) {
|
||||
logError("avcodec_open2", result);
|
||||
releaseContext(context);
|
||||
return NULL;
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
int decodePacket(AVCodecContext* context, AVPacket* packet,
|
||||
uint8_t* outputBuffer, int outputSize,
|
||||
GrowOutputBufferCallback growBuffer) {
|
||||
int result = 0;
|
||||
// Queue input data.
|
||||
result = avcodec_send_packet(context, packet);
|
||||
if (result) {
|
||||
logError("avcodec_send_packet", result);
|
||||
return transformError(result);
|
||||
}
|
||||
|
||||
// Dequeue output data until it runs out.
|
||||
int outSize = 0;
|
||||
while (true) {
|
||||
AVFrame* frame = av_frame_alloc();
|
||||
if (!frame) {
|
||||
LOGE("Failed to allocate output frame.");
|
||||
return AUDIO_DECODER_ERROR_INVALID_DATA;
|
||||
}
|
||||
result = avcodec_receive_frame(context, frame);
|
||||
if (result) {
|
||||
av_frame_free(&frame);
|
||||
if (result == AVERROR(EAGAIN)) {
|
||||
break;
|
||||
}
|
||||
logError("avcodec_receive_frame", result);
|
||||
return transformError(result);
|
||||
}
|
||||
|
||||
// Resample output.
|
||||
AVSampleFormat sampleFormat = context->sample_fmt;
|
||||
int channelCount = context->ch_layout.nb_channels;
|
||||
int sampleRate = context->sample_rate;
|
||||
int sampleCount = frame->nb_samples;
|
||||
int dataSize = av_samples_get_buffer_size(NULL, channelCount, sampleCount,
|
||||
sampleFormat, 1);
|
||||
SwrContext* resampleContext = static_cast<SwrContext*>(context->opaque);
|
||||
if (!resampleContext) {
|
||||
result =
|
||||
swr_alloc_set_opts2(&resampleContext, // ps
|
||||
&context->ch_layout, // out_ch_layout
|
||||
context->request_sample_fmt, // out_sample_fmt
|
||||
sampleRate, // out_sample_rate
|
||||
&context->ch_layout, // in_ch_layout
|
||||
sampleFormat, // in_sample_fmt
|
||||
sampleRate, // in_sample_rate
|
||||
0, // log_offset
|
||||
NULL // log_ctx
|
||||
);
|
||||
if (result < 0) {
|
||||
logError("swr_alloc_set_opts2", result);
|
||||
av_frame_free(&frame);
|
||||
return transformError(result);
|
||||
}
|
||||
result = swr_init(resampleContext);
|
||||
if (result < 0) {
|
||||
logError("swr_init", result);
|
||||
av_frame_free(&frame);
|
||||
return transformError(result);
|
||||
}
|
||||
context->opaque = resampleContext;
|
||||
}
|
||||
|
||||
int outSampleSize = av_get_bytes_per_sample(context->request_sample_fmt);
|
||||
int outSamples = swr_get_out_samples(resampleContext, sampleCount);
|
||||
int bufferOutSize = outSampleSize * channelCount * outSamples;
|
||||
if (outSize + bufferOutSize > outputSize) {
|
||||
LOGD(
|
||||
"Output buffer size (%d) too small for output data (%d), "
|
||||
"reallocating buffer.",
|
||||
outputSize, outSize + bufferOutSize);
|
||||
outputSize = outSize + bufferOutSize;
|
||||
outputBuffer = growBuffer(outputSize);
|
||||
if (!outputBuffer) {
|
||||
LOGE("Failed to reallocate output buffer.");
|
||||
av_frame_free(&frame);
|
||||
return AUDIO_DECODER_ERROR_OTHER;
|
||||
}
|
||||
}
|
||||
result = swr_convert(resampleContext, &outputBuffer, bufferOutSize,
|
||||
(const uint8_t**)frame->data, frame->nb_samples);
|
||||
av_frame_free(&frame);
|
||||
if (result < 0) {
|
||||
logError("swr_convert", result);
|
||||
return AUDIO_DECODER_ERROR_INVALID_DATA;
|
||||
}
|
||||
int available = swr_get_out_samples(resampleContext, 0);
|
||||
if (available != 0) {
|
||||
LOGE("Expected no samples remaining after resampling, but found %d.",
|
||||
available);
|
||||
return AUDIO_DECODER_ERROR_INVALID_DATA;
|
||||
}
|
||||
outputBuffer += bufferOutSize;
|
||||
outSize += bufferOutSize;
|
||||
}
|
||||
return outSize;
|
||||
}
|
||||
|
||||
int transformError(int errorNumber) {
|
||||
return errorNumber == AVERROR_INVALIDDATA ? AUDIO_DECODER_ERROR_INVALID_DATA
|
||||
: AUDIO_DECODER_ERROR_OTHER;
|
||||
}
|
||||
|
||||
void logError(const char* functionName, int errorNumber) {
|
||||
char* buffer = (char*)malloc(ERROR_STRING_BUFFER_LENGTH * sizeof(char));
|
||||
av_strerror(errorNumber, buffer, ERROR_STRING_BUFFER_LENGTH);
|
||||
LOGE("Error in %s: %s", functionName, buffer);
|
||||
free(buffer);
|
||||
}
|
||||
|
||||
void releaseContext(AVCodecContext* context) {
|
||||
if (!context) {
|
||||
return;
|
||||
}
|
||||
SwrContext* swrContext;
|
||||
if ((swrContext = (SwrContext*)context->opaque)) {
|
||||
swr_free(&swrContext);
|
||||
context->opaque = NULL;
|
||||
}
|
||||
avcodec_free_context(&context);
|
||||
}
|
||||
|
||||
jint JNI_OnLoad(JavaVM* vm, void* reserved) {
|
||||
JNIEnv* env;
|
||||
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
|
||||
LOGE("JNI_OnLoad: GetEnv failed");
|
||||
return -1;
|
||||
}
|
||||
jclass clazz =
|
||||
env->FindClass("androidx/media3/decoder/ffmpeg/FfmpegAudioDecoder");
|
||||
if (!clazz) {
|
||||
LOGE("JNI_OnLoad: FindClass failed");
|
||||
return -1;
|
||||
}
|
||||
growOutputBufferMethod =
|
||||
env->GetMethodID(clazz, "growOutputBuffer",
|
||||
"(Landroidx/media3/decoder/"
|
||||
"SimpleDecoderOutputBuffer;I)Ljava/nio/ByteBuffer;");
|
||||
if (!growOutputBufferMethod) {
|
||||
LOGE("JNI_OnLoad: GetMethodID failed");
|
||||
return -1;
|
||||
}
|
||||
static const JNINativeMethod kFfmpegAudioDecoderMethods[] = {
|
||||
{"ffmpegInitialize", "(Ljava/lang/String;[BZII)J",
|
||||
reinterpret_cast<void*>(ffmpegInitialize)},
|
||||
{"ffmpegDecode",
|
||||
"(JLjava/nio/ByteBuffer;ILandroidx/media3/decoder/"
|
||||
"SimpleDecoderOutputBuffer;Ljava/nio/ByteBuffer;I)I",
|
||||
reinterpret_cast<void*>(ffmpegDecode)},
|
||||
{"ffmpegGetChannelCount", "(J)I",
|
||||
reinterpret_cast<void*>(ffmpegGetChannelCount)},
|
||||
{"ffmpegGetSampleRate", "(J)I",
|
||||
reinterpret_cast<void*>(ffmpegGetSampleRate)},
|
||||
{"ffmpegReset", "(J[B)J", reinterpret_cast<void*>(ffmpegReset)},
|
||||
{"ffmpegRelease", "(J)V", reinterpret_cast<void*>(ffmpegRelease)},
|
||||
};
|
||||
if (env->RegisterNatives(clazz, kFfmpegAudioDecoderMethods,
|
||||
sizeof(kFfmpegAudioDecoderMethods) /
|
||||
sizeof(kFfmpegAudioDecoderMethods[0])) < 0) {
|
||||
LOGE("JNI_OnLoad: RegisterNatives failed for FfmpegAudioDecoder");
|
||||
return -1;
|
||||
}
|
||||
|
||||
jclass libraryClazz =
|
||||
env->FindClass("androidx/media3/decoder/ffmpeg/FfmpegLibrary");
|
||||
if (!libraryClazz) {
|
||||
LOGE("JNI_OnLoad: FindClass failed for FfmpegLibrary");
|
||||
return -1;
|
||||
}
|
||||
static const JNINativeMethod kFfmpegLibraryMethods[] = {
|
||||
{"ffmpegGetVersion", "()Ljava/lang/String;",
|
||||
reinterpret_cast<void*>(ffmpegGetVersion)},
|
||||
{"ffmpegGetInputBufferPaddingSize", "()I",
|
||||
reinterpret_cast<void*>(ffmpegGetInputBufferPaddingSize)},
|
||||
{"ffmpegHasDecoder", "(Ljava/lang/String;)Z",
|
||||
reinterpret_cast<void*>(ffmpegHasDecoder)},
|
||||
};
|
||||
if (env->RegisterNatives(libraryClazz, kFfmpegLibraryMethods,
|
||||
sizeof(kFfmpegLibraryMethods) /
|
||||
sizeof(kFfmpegLibraryMethods[0])) < 0) {
|
||||
LOGE("JNI_OnLoad: RegisterNatives failed for FfmpegLibrary");
|
||||
return -1;
|
||||
}
|
||||
|
||||
return JNI_VERSION_1_6;
|
||||
}
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package androidx.media3.decoder.ffmpeg;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkNotNull;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.media3.common.C;
|
||||
import androidx.media3.common.Format;
|
||||
import androidx.media3.common.MimeTypes;
|
||||
import androidx.media3.common.util.ParsableByteArray;
|
||||
import androidx.media3.common.util.UnstableApi;
|
||||
import androidx.media3.common.util.Util;
|
||||
import androidx.media3.decoder.DecoderInputBuffer;
|
||||
import androidx.media3.decoder.SimpleDecoder;
|
||||
import androidx.media3.decoder.SimpleDecoderOutputBuffer;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.List;
|
||||
|
||||
/** FFmpeg audio decoder. */
|
||||
@UnstableApi
|
||||
public final class FfmpegAudioDecoder
|
||||
extends SimpleDecoder<DecoderInputBuffer, SimpleDecoderOutputBuffer, FfmpegDecoderException> {
|
||||
|
||||
private static final int INITIAL_OUTPUT_BUFFER_SIZE_16BIT = 65535;
|
||||
private static final int INITIAL_OUTPUT_BUFFER_SIZE_32BIT = INITIAL_OUTPUT_BUFFER_SIZE_16BIT * 2;
|
||||
|
||||
private static final int AUDIO_DECODER_ERROR_INVALID_DATA = -1;
|
||||
private static final int AUDIO_DECODER_ERROR_OTHER = -2;
|
||||
|
||||
// FLAC parsing constants
|
||||
private static final byte[] flacStreamMarker = {'f', 'L', 'a', 'C'};
|
||||
private static final int FLAC_METADATA_TYPE_STREAM_INFO = 0;
|
||||
private static final int FLAC_METADATA_BLOCK_HEADER_SIZE = 4;
|
||||
private static final int FLAC_STREAM_INFO_DATA_SIZE = 34;
|
||||
|
||||
private final String codecName;
|
||||
@Nullable private final byte[] extraData;
|
||||
private final @C.PcmEncoding int encoding;
|
||||
private int outputBufferSize;
|
||||
|
||||
private long nativeContext; // May be reassigned on resetting the codec.
|
||||
private boolean hasOutputFormat;
|
||||
private volatile int channelCount;
|
||||
private volatile int sampleRate;
|
||||
|
||||
public FfmpegAudioDecoder(
|
||||
Format format,
|
||||
int numInputBuffers,
|
||||
int numOutputBuffers,
|
||||
int initialInputBufferSize,
|
||||
boolean outputFloat)
|
||||
throws FfmpegDecoderException {
|
||||
super(new DecoderInputBuffer[numInputBuffers], new SimpleDecoderOutputBuffer[numOutputBuffers]);
|
||||
if (!FfmpegLibrary.isAvailable()) {
|
||||
throw new FfmpegDecoderException("Failed to load decoder native libraries.");
|
||||
}
|
||||
checkNotNull(format.sampleMimeType);
|
||||
codecName = checkNotNull(FfmpegLibrary.getCodecName(format.sampleMimeType));
|
||||
extraData = getExtraData(format.sampleMimeType, format.initializationData);
|
||||
encoding = outputFloat ? C.ENCODING_PCM_FLOAT : C.ENCODING_PCM_16BIT;
|
||||
outputBufferSize =
|
||||
outputFloat ? INITIAL_OUTPUT_BUFFER_SIZE_32BIT : INITIAL_OUTPUT_BUFFER_SIZE_16BIT;
|
||||
nativeContext =
|
||||
ffmpegInitialize(codecName, extraData, outputFloat, format.sampleRate, format.channelCount);
|
||||
if (nativeContext == 0) {
|
||||
throw new FfmpegDecoderException("Initialization failed.");
|
||||
}
|
||||
setInitialInputBufferSize(initialInputBufferSize);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "ffmpeg" + FfmpegLibrary.getVersion() + "-" + codecName;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DecoderInputBuffer createInputBuffer() {
|
||||
return new DecoderInputBuffer(
|
||||
DecoderInputBuffer.BUFFER_REPLACEMENT_MODE_DIRECT,
|
||||
FfmpegLibrary.getInputBufferPaddingSize());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected SimpleDecoderOutputBuffer createOutputBuffer() {
|
||||
return new SimpleDecoderOutputBuffer(this::releaseOutputBuffer);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected FfmpegDecoderException createUnexpectedDecodeException(Throwable error) {
|
||||
return new FfmpegDecoderException("Unexpected decode error", error);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
protected FfmpegDecoderException decode(
|
||||
DecoderInputBuffer inputBuffer, SimpleDecoderOutputBuffer outputBuffer, boolean reset) {
|
||||
if (reset) {
|
||||
nativeContext = ffmpegReset(nativeContext, extraData);
|
||||
if (nativeContext == 0) {
|
||||
return new FfmpegDecoderException("Error resetting (see logcat).");
|
||||
}
|
||||
}
|
||||
ByteBuffer inputData = Util.castNonNull(inputBuffer.data);
|
||||
int inputSize = inputData.limit();
|
||||
ByteBuffer outputData = outputBuffer.init(inputBuffer.timeUs, outputBufferSize);
|
||||
int result =
|
||||
ffmpegDecode(
|
||||
nativeContext, inputData, inputSize, outputBuffer, outputData, outputBufferSize);
|
||||
if (result == AUDIO_DECODER_ERROR_OTHER) {
|
||||
return new FfmpegDecoderException("Error decoding (see logcat).");
|
||||
} else if (result == AUDIO_DECODER_ERROR_INVALID_DATA) {
|
||||
// Treat invalid data errors as non-fatal to match the behavior of MediaCodec. No output will
|
||||
// be produced for this buffer, so mark it as skipped to ensure that the audio sink's
|
||||
// position is reset when more audio is produced.
|
||||
outputBuffer.shouldBeSkipped = true;
|
||||
return null;
|
||||
} else if (result == 0) {
|
||||
// There's no need to output empty buffers.
|
||||
outputBuffer.shouldBeSkipped = true;
|
||||
return null;
|
||||
}
|
||||
if (!hasOutputFormat) {
|
||||
channelCount = ffmpegGetChannelCount(nativeContext);
|
||||
sampleRate = ffmpegGetSampleRate(nativeContext);
|
||||
if (sampleRate == 0 && "alac".equals(codecName)) {
|
||||
checkNotNull(extraData);
|
||||
// ALAC decoder did not set the sample rate in earlier versions of FFmpeg. See
|
||||
// https://trac.ffmpeg.org/ticket/6096.
|
||||
ParsableByteArray parsableExtraData = new ParsableByteArray(extraData);
|
||||
parsableExtraData.setPosition(extraData.length - 4);
|
||||
sampleRate = parsableExtraData.readUnsignedIntToInt();
|
||||
}
|
||||
hasOutputFormat = true;
|
||||
}
|
||||
// Get a new reference to the output ByteBuffer in case the native decode method reallocated the
|
||||
// buffer to grow its size.
|
||||
outputData = checkNotNull(outputBuffer.data);
|
||||
outputData.position(0);
|
||||
outputData.limit(result);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Called from native code
|
||||
@SuppressWarnings("unused")
|
||||
private ByteBuffer growOutputBuffer(SimpleDecoderOutputBuffer outputBuffer, int requiredSize) {
|
||||
// Use it for new buffer so that hopefully we won't need to reallocate again
|
||||
outputBufferSize = requiredSize;
|
||||
return outputBuffer.grow(requiredSize);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void release() {
|
||||
super.release();
|
||||
ffmpegRelease(nativeContext);
|
||||
nativeContext = 0;
|
||||
}
|
||||
|
||||
/** Returns the channel count of output audio. */
|
||||
public int getChannelCount() {
|
||||
return channelCount;
|
||||
}
|
||||
|
||||
/** Returns the sample rate of output audio. */
|
||||
public int getSampleRate() {
|
||||
return sampleRate;
|
||||
}
|
||||
|
||||
/** Returns the encoding of output audio. */
|
||||
public @C.PcmEncoding int getEncoding() {
|
||||
return encoding;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns FFmpeg-compatible codec-specific initialization data ("extra data"), or {@code null} if
|
||||
* not required.
|
||||
*/
|
||||
@Nullable
|
||||
private static byte[] getExtraData(String mimeType, List<byte[]> initializationData) {
|
||||
switch (mimeType) {
|
||||
case MimeTypes.AUDIO_AAC:
|
||||
case MimeTypes.AUDIO_OPUS:
|
||||
return initializationData.get(0);
|
||||
case MimeTypes.AUDIO_ALAC:
|
||||
return getAlacExtraData(initializationData);
|
||||
case MimeTypes.AUDIO_VORBIS:
|
||||
return getVorbisExtraData(initializationData);
|
||||
case MimeTypes.AUDIO_FLAC:
|
||||
return getFlacExtraData(initializationData);
|
||||
default:
|
||||
// Other codecs do not require extra data.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] getAlacExtraData(List<byte[]> initializationData) {
|
||||
// FFmpeg's ALAC decoder expects an ALAC atom, which contains the ALAC "magic cookie", as extra
|
||||
// data. initializationData[0] contains only the magic cookie, and so we need to package it into
|
||||
// an ALAC atom. See:
|
||||
// https://ffmpeg.org/doxygen/0.6/alac_8c.html
|
||||
// https://github.com/macosforge/alac/blob/master/ALACMagicCookieDescription.txt
|
||||
byte[] magicCookie = initializationData.get(0);
|
||||
int alacAtomLength = 12 + magicCookie.length;
|
||||
ByteBuffer alacAtom = ByteBuffer.allocate(alacAtomLength);
|
||||
alacAtom.putInt(alacAtomLength);
|
||||
alacAtom.putInt(0x616c6163); // type=alac
|
||||
alacAtom.putInt(0); // version=0, flags=0
|
||||
alacAtom.put(magicCookie, /* offset= */ 0, magicCookie.length);
|
||||
return alacAtom.array();
|
||||
}
|
||||
|
||||
private static byte[] getVorbisExtraData(List<byte[]> initializationData) {
|
||||
byte[] header0 = initializationData.get(0);
|
||||
byte[] header1 = initializationData.get(1);
|
||||
byte[] extraData = new byte[header0.length + header1.length + 6];
|
||||
extraData[0] = (byte) (header0.length >> 8);
|
||||
extraData[1] = (byte) (header0.length & 0xFF);
|
||||
System.arraycopy(header0, 0, extraData, 2, header0.length);
|
||||
extraData[header0.length + 2] = 0;
|
||||
extraData[header0.length + 3] = 0;
|
||||
extraData[header0.length + 4] = (byte) (header1.length >> 8);
|
||||
extraData[header0.length + 5] = (byte) (header1.length & 0xFF);
|
||||
System.arraycopy(header1, 0, extraData, header0.length + 6, header1.length);
|
||||
return extraData;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static byte[] getFlacExtraData(List<byte[]> initializationData) {
|
||||
for (int i = 0; i < initializationData.size(); i++) {
|
||||
byte[] out = extractFlacStreamInfo(initializationData.get(i));
|
||||
if (out != null) {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static byte[] extractFlacStreamInfo(byte[] data) {
|
||||
int offset = 0;
|
||||
if (arrayStartsWith(data, flacStreamMarker)) {
|
||||
offset = flacStreamMarker.length;
|
||||
}
|
||||
|
||||
if (data.length - offset == FLAC_STREAM_INFO_DATA_SIZE) {
|
||||
byte[] streamInfo = new byte[FLAC_STREAM_INFO_DATA_SIZE];
|
||||
System.arraycopy(data, offset, streamInfo, 0, FLAC_STREAM_INFO_DATA_SIZE);
|
||||
return streamInfo;
|
||||
}
|
||||
|
||||
if (data.length >= offset + FLAC_METADATA_BLOCK_HEADER_SIZE) {
|
||||
int type = data[offset] & 0x7F;
|
||||
int length =
|
||||
((data[offset + 1] & 0xFF) << 16)
|
||||
| ((data[offset + 2] & 0xFF) << 8)
|
||||
| (data[offset + 3] & 0xFF);
|
||||
|
||||
if (type == FLAC_METADATA_TYPE_STREAM_INFO
|
||||
&& length == FLAC_STREAM_INFO_DATA_SIZE
|
||||
&& data.length >= offset + FLAC_METADATA_BLOCK_HEADER_SIZE + FLAC_STREAM_INFO_DATA_SIZE) {
|
||||
byte[] streamInfo = new byte[FLAC_STREAM_INFO_DATA_SIZE];
|
||||
System.arraycopy(
|
||||
data,
|
||||
offset + FLAC_METADATA_BLOCK_HEADER_SIZE,
|
||||
streamInfo,
|
||||
0,
|
||||
FLAC_STREAM_INFO_DATA_SIZE);
|
||||
return streamInfo;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean arrayStartsWith(byte[] data, byte[] prefix) {
|
||||
if (data.length < prefix.length) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < prefix.length; i++) {
|
||||
if (data[i] != prefix[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private native long ffmpegInitialize(
|
||||
String codecName,
|
||||
@Nullable byte[] extraData,
|
||||
boolean outputFloat,
|
||||
int rawSampleRate,
|
||||
int rawChannelCount);
|
||||
|
||||
private native int ffmpegDecode(
|
||||
long context,
|
||||
ByteBuffer inputData,
|
||||
int inputSize,
|
||||
SimpleDecoderOutputBuffer decoderOutputBuffer,
|
||||
ByteBuffer outputData,
|
||||
int outputSize);
|
||||
|
||||
private native int ffmpegGetChannelCount(long context);
|
||||
|
||||
private native int ffmpegGetSampleRate(long context);
|
||||
|
||||
private native long ffmpegReset(long context, @Nullable byte[] extraData);
|
||||
|
||||
private native void ffmpegRelease(long context);
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package androidx.media3.decoder.ffmpeg;
|
||||
|
||||
import static androidx.media3.exoplayer.audio.AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY;
|
||||
import static androidx.media3.exoplayer.audio.AudioSink.SINK_FORMAT_SUPPORTED_WITH_TRANSCODING;
|
||||
import static androidx.media3.exoplayer.audio.AudioSink.SINK_FORMAT_UNSUPPORTED;
|
||||
import static com.google.common.base.Preconditions.checkNotNull;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.media3.common.C;
|
||||
import androidx.media3.common.Format;
|
||||
import androidx.media3.common.MimeTypes;
|
||||
import androidx.media3.common.audio.AudioProcessor;
|
||||
import androidx.media3.common.util.TraceUtil;
|
||||
import androidx.media3.common.util.UnstableApi;
|
||||
import androidx.media3.common.util.Util;
|
||||
import androidx.media3.decoder.CryptoConfig;
|
||||
import androidx.media3.exoplayer.audio.AudioRendererEventListener;
|
||||
import androidx.media3.exoplayer.audio.AudioSink;
|
||||
import androidx.media3.exoplayer.audio.AudioSink.SinkFormatSupport;
|
||||
import androidx.media3.exoplayer.audio.DecoderAudioRenderer;
|
||||
import androidx.media3.exoplayer.audio.DefaultAudioSink;
|
||||
|
||||
/** Decodes and renders audio using FFmpeg. */
|
||||
@UnstableApi
|
||||
public final class FfmpegAudioRenderer extends DecoderAudioRenderer<FfmpegAudioDecoder> {
|
||||
|
||||
private static final String TAG = "FfmpegAudioRenderer";
|
||||
|
||||
/** The number of input and output buffers. */
|
||||
private static final int NUM_BUFFERS = 16;
|
||||
|
||||
/** The default input buffer size. */
|
||||
private static final int DEFAULT_INPUT_BUFFER_SIZE = 960 * 6;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link #FfmpegAudioRenderer(Context)} instead.
|
||||
*/
|
||||
@SuppressWarnings("deprecation") // Calling deprecated constructor.
|
||||
@Deprecated
|
||||
public FfmpegAudioRenderer() {
|
||||
this(/* eventHandler= */ null, /* eventListener= */ null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance.
|
||||
*
|
||||
* @param context A context.
|
||||
*/
|
||||
public FfmpegAudioRenderer(Context context) {
|
||||
this(context, /* eventHandler= */ null, /* eventListener= */ null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance.
|
||||
*
|
||||
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
|
||||
* null if delivery of events is not required.
|
||||
* @param eventListener A listener of events. May be null if delivery of events is not required.
|
||||
* @param audioProcessors Optional {@link AudioProcessor}s that will process audio before output.
|
||||
* @deprecated Use {@link #FfmpegAudioRenderer(Context, Handler, AudioRendererEventListener,
|
||||
* AudioProcessor...)} instead.
|
||||
*/
|
||||
@SuppressWarnings("deprecation") // Calling deprecated constructor.
|
||||
@Deprecated
|
||||
public FfmpegAudioRenderer(
|
||||
@Nullable Handler eventHandler,
|
||||
@Nullable AudioRendererEventListener eventListener,
|
||||
AudioProcessor... audioProcessors) {
|
||||
this(
|
||||
eventHandler,
|
||||
eventListener,
|
||||
new DefaultAudioSink.Builder().setAudioProcessors(audioProcessors).build());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance.
|
||||
*
|
||||
* @param context A context.
|
||||
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
|
||||
* null if delivery of events is not required.
|
||||
* @param eventListener A listener of events. May be null if delivery of events is not required.
|
||||
* @param audioProcessors Optional {@link AudioProcessor}s that will process audio before output.
|
||||
*/
|
||||
public FfmpegAudioRenderer(
|
||||
Context context,
|
||||
@Nullable Handler eventHandler,
|
||||
@Nullable AudioRendererEventListener eventListener,
|
||||
AudioProcessor... audioProcessors) {
|
||||
this(
|
||||
eventHandler,
|
||||
eventListener,
|
||||
new DefaultAudioSink.Builder(context).setAudioProcessors(audioProcessors).build());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance.
|
||||
*
|
||||
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
|
||||
* null if delivery of events is not required.
|
||||
* @param eventListener A listener of events. May be null if delivery of events is not required.
|
||||
* @param audioSink The sink to which audio will be output.
|
||||
*/
|
||||
public FfmpegAudioRenderer(
|
||||
@Nullable Handler eventHandler,
|
||||
@Nullable AudioRendererEventListener eventListener,
|
||||
AudioSink audioSink) {
|
||||
super(eventHandler, eventListener, audioSink);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return TAG;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected @C.FormatSupport int supportsFormatInternal(Format format) {
|
||||
String mimeType = checkNotNull(format.sampleMimeType);
|
||||
if (!FfmpegLibrary.isAvailable() || !MimeTypes.isAudio(mimeType)) {
|
||||
return C.FORMAT_UNSUPPORTED_TYPE;
|
||||
} else if (!FfmpegLibrary.supportsFormat(mimeType)
|
||||
|| (!sinkSupportsFormat(format, C.ENCODING_PCM_16BIT)
|
||||
&& !sinkSupportsFormat(format, C.ENCODING_PCM_FLOAT))) {
|
||||
return C.FORMAT_UNSUPPORTED_SUBTYPE;
|
||||
} else if (format.cryptoType != C.CRYPTO_TYPE_NONE) {
|
||||
return C.FORMAT_UNSUPPORTED_DRM;
|
||||
} else {
|
||||
return C.FORMAT_HANDLED;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @AdaptiveSupport int supportsMixedMimeTypeAdaptation() {
|
||||
return ADAPTIVE_NOT_SEAMLESS;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected FfmpegAudioDecoder createDecoder(Format format, @Nullable CryptoConfig cryptoConfig)
|
||||
throws FfmpegDecoderException {
|
||||
TraceUtil.beginSection("createFfmpegAudioDecoder");
|
||||
int initialInputBufferSize =
|
||||
format.maxInputSize != Format.NO_VALUE ? format.maxInputSize : DEFAULT_INPUT_BUFFER_SIZE;
|
||||
FfmpegAudioDecoder decoder =
|
||||
new FfmpegAudioDecoder(
|
||||
format, NUM_BUFFERS, NUM_BUFFERS, initialInputBufferSize, shouldOutputFloat(format));
|
||||
TraceUtil.endSection();
|
||||
return decoder;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Format getOutputFormat(FfmpegAudioDecoder decoder) {
|
||||
checkNotNull(decoder);
|
||||
return new Format.Builder()
|
||||
.setSampleMimeType(MimeTypes.AUDIO_RAW)
|
||||
.setChannelCount(decoder.getChannelCount())
|
||||
.setSampleRate(decoder.getSampleRate())
|
||||
.setPcmEncoding(decoder.getEncoding())
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the renderer's {@link AudioSink} supports the PCM format that will be output
|
||||
* from the decoder for the given input format and requested output encoding.
|
||||
*/
|
||||
private boolean sinkSupportsFormat(Format inputFormat, @C.PcmEncoding int pcmEncoding) {
|
||||
return sinkSupportsFormat(
|
||||
Util.getPcmFormat(pcmEncoding, inputFormat.channelCount, inputFormat.sampleRate));
|
||||
}
|
||||
|
||||
private boolean shouldOutputFloat(Format inputFormat) {
|
||||
if (!sinkSupportsFormat(inputFormat, C.ENCODING_PCM_16BIT)) {
|
||||
// We have no choice because the sink doesn't support 16-bit integer PCM.
|
||||
return true;
|
||||
}
|
||||
|
||||
@SinkFormatSupport
|
||||
int formatSupport =
|
||||
getSinkFormatSupport(
|
||||
Util.getPcmFormat(
|
||||
C.ENCODING_PCM_FLOAT, inputFormat.channelCount, inputFormat.sampleRate));
|
||||
switch (formatSupport) {
|
||||
case SINK_FORMAT_SUPPORTED_DIRECTLY:
|
||||
// AC-3 is always 16-bit, so there's no point using floating point. Assume that it's worth
|
||||
// using for all other formats.
|
||||
return !MimeTypes.AUDIO_AC3.equals(inputFormat.sampleMimeType);
|
||||
case SINK_FORMAT_UNSUPPORTED:
|
||||
case SINK_FORMAT_SUPPORTED_WITH_TRANSCODING:
|
||||
default:
|
||||
// Always prefer 16-bit PCM if the sink does not provide direct support for floating point.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package androidx.media3.decoder.ffmpeg;
|
||||
|
||||
import androidx.media3.common.util.UnstableApi;
|
||||
import androidx.media3.decoder.DecoderException;
|
||||
|
||||
/** Thrown when an FFmpeg decoder error occurs. */
|
||||
@UnstableApi
|
||||
public final class FfmpegDecoderException extends DecoderException {
|
||||
|
||||
/* package */ FfmpegDecoderException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/* package */ FfmpegDecoderException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package androidx.media3.decoder.ffmpeg;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.media3.common.C;
|
||||
import androidx.media3.common.MediaLibraryInfo;
|
||||
import androidx.media3.common.MimeTypes;
|
||||
import androidx.media3.common.util.LibraryLoader;
|
||||
import androidx.media3.common.util.Log;
|
||||
import androidx.media3.common.util.UnstableApi;
|
||||
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
|
||||
|
||||
/** Configures and queries the underlying native library. */
|
||||
@UnstableApi
|
||||
public final class FfmpegLibrary {
|
||||
|
||||
static {
|
||||
MediaLibraryInfo.registerModule("media3.decoder.ffmpeg");
|
||||
}
|
||||
|
||||
private static final String TAG = "FfmpegLibrary";
|
||||
|
||||
private static final LibraryLoader LOADER =
|
||||
new LibraryLoader("ffmpegJNI") {
|
||||
@Override
|
||||
protected void loadLibrary(String name) {
|
||||
System.loadLibrary(name);
|
||||
}
|
||||
};
|
||||
|
||||
private static @MonotonicNonNull String version;
|
||||
private static int inputBufferPaddingSize = C.LENGTH_UNSET;
|
||||
|
||||
private FfmpegLibrary() {}
|
||||
|
||||
/**
|
||||
* Override the names of the FFmpeg native libraries. If an application wishes to call this
|
||||
* method, it must do so before calling any other method defined by this class, and before
|
||||
* instantiating a {@link FfmpegAudioRenderer} or {@link ExperimentalFfmpegVideoRenderer}
|
||||
* instance.
|
||||
*
|
||||
* @param libraries The names of the FFmpeg native libraries.
|
||||
*/
|
||||
public static void setLibraries(String... libraries) {
|
||||
LOADER.setLibraries(libraries);
|
||||
}
|
||||
|
||||
/** Returns whether the underlying library is available, loading it if necessary. */
|
||||
public static boolean isAvailable() {
|
||||
return LOADER.isAvailable();
|
||||
}
|
||||
|
||||
/** Returns the version of the underlying library if available, or null otherwise. */
|
||||
@Nullable
|
||||
public static String getVersion() {
|
||||
if (!isAvailable()) {
|
||||
return null;
|
||||
}
|
||||
if (version == null) {
|
||||
version = ffmpegGetVersion();
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the required amount of padding for input buffers in bytes, or {@link C#LENGTH_UNSET} if
|
||||
* the underlying library is not available.
|
||||
*/
|
||||
public static int getInputBufferPaddingSize() {
|
||||
if (!isAvailable()) {
|
||||
return C.LENGTH_UNSET;
|
||||
}
|
||||
if (inputBufferPaddingSize == C.LENGTH_UNSET) {
|
||||
inputBufferPaddingSize = ffmpegGetInputBufferPaddingSize();
|
||||
}
|
||||
return inputBufferPaddingSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the underlying library supports the specified MIME type.
|
||||
*
|
||||
* @param mimeType The MIME type to check.
|
||||
*/
|
||||
public static boolean supportsFormat(String mimeType) {
|
||||
if (!isAvailable()) {
|
||||
return false;
|
||||
}
|
||||
@Nullable String codecName = getCodecName(mimeType);
|
||||
if (codecName == null) {
|
||||
return false;
|
||||
}
|
||||
if (!ffmpegHasDecoder(codecName)) {
|
||||
Log.w(TAG, "No " + codecName + " decoder available. Check the FFmpeg build configuration.");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the FFmpeg decoder that could be used to decode the format, or {@code null}
|
||||
* if it's unsupported.
|
||||
*/
|
||||
@Nullable
|
||||
/* package */ static String getCodecName(String mimeType) {
|
||||
switch (mimeType) {
|
||||
case MimeTypes.AUDIO_AAC:
|
||||
return "aac";
|
||||
case MimeTypes.AUDIO_MPEG:
|
||||
case MimeTypes.AUDIO_MPEG_L1:
|
||||
case MimeTypes.AUDIO_MPEG_L2:
|
||||
return "mp3";
|
||||
case MimeTypes.AUDIO_AC3:
|
||||
return "ac3";
|
||||
case MimeTypes.AUDIO_E_AC3:
|
||||
case MimeTypes.AUDIO_E_AC3_JOC:
|
||||
return "eac3";
|
||||
case MimeTypes.AUDIO_TRUEHD:
|
||||
return "truehd";
|
||||
case MimeTypes.AUDIO_DTS:
|
||||
case MimeTypes.AUDIO_DTS_EXPRESS:
|
||||
case MimeTypes.AUDIO_DTS_HD:
|
||||
return "dca";
|
||||
case MimeTypes.AUDIO_VORBIS:
|
||||
return "vorbis";
|
||||
case MimeTypes.AUDIO_OPUS:
|
||||
return "opus";
|
||||
case MimeTypes.AUDIO_AMR_NB:
|
||||
return "amrnb";
|
||||
case MimeTypes.AUDIO_AMR_WB:
|
||||
return "amrwb";
|
||||
case MimeTypes.AUDIO_FLAC:
|
||||
return "flac";
|
||||
case MimeTypes.AUDIO_ALAC:
|
||||
return "alac";
|
||||
case MimeTypes.AUDIO_MLAW:
|
||||
return "pcm_mulaw";
|
||||
case MimeTypes.AUDIO_ALAW:
|
||||
return "pcm_alaw";
|
||||
case MimeTypes.VIDEO_H264:
|
||||
return "h264";
|
||||
case MimeTypes.VIDEO_H265:
|
||||
return "hevc";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static native String ffmpegGetVersion();
|
||||
|
||||
private static native int ffmpegGetInputBufferPaddingSize();
|
||||
|
||||
private static native boolean ffmpegHasDecoder(String codecName);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* Copyright (C) 2019 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
@NonNullApi
|
||||
package androidx.media3.decoder.ffmpeg;
|
||||
|
||||
import androidx.media3.common.util.NonNullApi;
|
||||
Binary file not shown.
Binary file not shown.
@@ -27,6 +27,7 @@ dependencies {
|
||||
api(project(":player-android-api"))
|
||||
implementation(project(":player-core"))
|
||||
implementation(project(":player-media3-source"))
|
||||
implementation(project(":player-media3-ffmpeg"))
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
||||
implementation("androidx.media3:media3-exoplayer:1.11.1")
|
||||
}
|
||||
@@ -164,7 +164,11 @@ class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
}
|
||||
}
|
||||
// fallback 仅处理可用解码器初始化回退,不承诺运行中错误自动软解。
|
||||
val renderers = DefaultRenderersFactory(context).setMediaCodecSelector(selector).setEnableDecoderFallback(true)
|
||||
// FFmpeg 扩展只声明 AC3/E-AC3/DTS/TrueHD(jniLibs 内置),AAC 等仍走系统 MediaCodec。
|
||||
val renderers = DefaultRenderersFactory(context)
|
||||
.setMediaCodecSelector(selector)
|
||||
.setEnableDecoderFallback(true)
|
||||
.setExtensionRendererMode(DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER)
|
||||
return ExoPlayer.Builder(context, renderers).build().also {
|
||||
it.setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(), true)
|
||||
it.setHandleAudioBecomingNoisy(true)
|
||||
@@ -299,19 +303,17 @@ class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput {
|
||||
CommandResult.Failed(error)
|
||||
}
|
||||
}
|
||||
/** 有可用音轨时优先 AAC/Opus 等常规编码;AC3/DTS 等环绕音频只在没有更好选择时保留。 */
|
||||
/** 默认音轨都不可解码时才改选可解码音轨;AC3/DTS/TrueHD 由内置 FFmpeg 扩展软解,不再改选。 */
|
||||
private fun applySupportedAudio(tracks: Tracks) {
|
||||
if (released || lastError != null) return
|
||||
val groups = tracks.groups.filter { it.type == C.TRACK_TYPE_AUDIO }
|
||||
if (groups.isEmpty()) return
|
||||
val supportedGroups = groups.filter { group -> (0 until group.length).any { group.isTrackSupported(it) } }
|
||||
if (supportedGroups.isEmpty()) return
|
||||
val selectedRank = groups.filter { group ->
|
||||
(0 until group.length).any { group.isTrackSelected(it) }
|
||||
}.minOfOrNull(::audioRank) ?: 3
|
||||
val target = supportedGroups.minByOrNull(::audioRank) ?: return
|
||||
val targetRank = audioRank(target)
|
||||
if (targetRank >= selectedRank) return
|
||||
val selectedSupported = groups.any { group ->
|
||||
(0 until group.length).any { group.isTrackSelected(it) && group.isTrackSupported(it) }
|
||||
}
|
||||
if (selectedSupported) return
|
||||
val target = groups.filter { group -> (0 until group.length).any { group.isTrackSupported(it) } }
|
||||
.minByOrNull(::audioRank) ?: return
|
||||
val indices = (0 until target.length).filter { target.isTrackSupported(it) }
|
||||
if (indices.isEmpty()) return
|
||||
handler.post {
|
||||
|
||||
@@ -36,6 +36,7 @@ dependencyResolutionManagement {
|
||||
rootProject.name = "TTVideoPlayer"
|
||||
include(":player-api", ":player-core", ":player-android-api", ":player-media3", ":player-render-android", ":player-lifecycle", ":player-telemetry", ":app-demo")
|
||||
include(":player-media3-source")
|
||||
include(":player-media3-ffmpeg")
|
||||
include(":player-rtmp-native")
|
||||
|
||||
include(":library-api", ":library-http", ":library-webdav", ":library-smb", ":library-jellyfin", ":library-storage", ":player-cast-api", ":player-cast-dlna", ":player-cast-relay", ":player-cast-google")
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# FFmpeg 音频扩展构建
|
||||
|
||||
`player-media3-ffmpeg` 使用的 `libffmpegJNI.so` 由本脚本生成,产物提交在
|
||||
`player-media3-ffmpeg/src/main/jniLibs/<abi>/`,日常 Gradle 构建不需要 NDK/FFmpeg 源码。
|
||||
|
||||
## 依赖
|
||||
|
||||
- Android NDK r28c(Linux 版,`28.2.13676358`):`https://dl.google.com/android/repository/android-ndk-r28c-linux.zip`
|
||||
- FFmpeg 6.0.1 源码:`https://ffmpeg.org/releases/ffmpeg-6.0.1.tar.xz`(media3 1.11.1 推荐版本)
|
||||
- `make`(WSL/Ubuntu 下 `apt install make`)
|
||||
|
||||
## 步骤(WSL)
|
||||
|
||||
```bash
|
||||
mkdir -p ~/ffbuild && cd ~/ffbuild
|
||||
curl -LO https://dl.google.com/android/repository/android-ndk-r28c-linux.zip && unzip -q android-ndk-r28c-linux.zip
|
||||
curl -LO https://ffmpeg.org/releases/ffmpeg-6.0.1.tar.xz && tar xf ffmpeg-6.0.1.tar.xz
|
||||
bash tools/ffmpeg/build_ffmpeg.sh # 默认 arm64-v8a + armeabi-v7a
|
||||
```
|
||||
|
||||
可选环境变量:`NDK_PATH`、`FFMPEG_SRC`、`BUILD_ROOT`、`OUT_DIR`、`ANDROID_API`(默认 23)。
|
||||
|
||||
## 说明
|
||||
|
||||
- 仅启用 `ac3 eac3 truehd mlp dca` 解码器;不含 FFmpeg 视频/解封装/网络模块。
|
||||
- FFmpeg 以 LGPL 配置构建(未启用 `--enable-gpl`),静态链入 `libffmpegJNI.so`;
|
||||
Java/JNI 包装来自 media3 `decoder_ffmpeg`(Apache-2.0)。
|
||||
- 构建带 `-Wl,-z,max-page-size=16384`,兼容 16KB page size 设备。
|
||||
- x86/x86_64 未内置;模拟器上 AC3/DTS 回落系统解码(多数不支持)。
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env bash
|
||||
# 交叉编译 FFmpeg 音频解码库并链接 media3 的 libffmpegJNI.so。
|
||||
#
|
||||
# 用法: build_ffmpeg.sh [abi...]
|
||||
# 默认构建 arm64-v8a armeabi-v7a。
|
||||
# 环境变量:
|
||||
# NDK_PATH Android NDK (默认 ~/ffbuild/android-ndk-r28c)
|
||||
# FFMPEG_SRC FFmpeg 源码目录 (默认 ~/ffbuild/ffmpeg-6.0.1)
|
||||
# BUILD_ROOT 构建目录 (默认 ~/ffbuild/build)
|
||||
# OUT_DIR libffmpegJNI.so 输出目录,默认为仓库内 player-media3-ffmpeg/src/main/jniLibs
|
||||
# ANDROID_API 目标 API (默认 23,与 app minSdk 一致)
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)"
|
||||
|
||||
NDK_PATH="${NDK_PATH:-$HOME/ffbuild/android-ndk-r28c}"
|
||||
FFMPEG_SRC="${FFMPEG_SRC:-$HOME/ffbuild/ffmpeg-6.0.1}"
|
||||
BUILD_ROOT="${BUILD_ROOT:-$HOME/ffbuild/build}"
|
||||
OUT_DIR="${OUT_DIR:-${REPO_DIR}/player-media3-ffmpeg/src/main/jniLibs}"
|
||||
ANDROID_API="${ANDROID_API:-23}"
|
||||
ABIS=("$@")
|
||||
if [[ ${#ABIS[@]} -eq 0 ]]; then ABIS=(arm64-v8a armeabi-v7a); fi
|
||||
|
||||
DECODERS=(ac3 eac3 truehd mlp dca)
|
||||
TOOLCHAIN="${NDK_PATH}/toolchains/llvm/prebuilt/linux-x86_64/bin"
|
||||
JNI_SRC="${REPO_DIR}/player-media3-ffmpeg/src/main/cpp/ffmpeg_jni.cc"
|
||||
JOBS="$(nproc)"
|
||||
|
||||
[[ -x "${TOOLCHAIN}/llvm-ar" ]] || { echo "NDK not found: ${NDK_PATH}" >&2; exit 1; }
|
||||
[[ -f "${FFMPEG_SRC}/configure" ]] || { echo "FFmpeg source not found: ${FFMPEG_SRC}" >&2; exit 1; }
|
||||
|
||||
COMMON_OPTIONS=(
|
||||
--target-os=android --enable-static --disable-shared
|
||||
--disable-doc --disable-programs --disable-everything
|
||||
--disable-avdevice --disable-avformat --disable-swscale
|
||||
--disable-postproc --disable-avfilter --disable-network
|
||||
--disable-symver --disable-v4l2-m2m --disable-vulkan
|
||||
--enable-swresample
|
||||
)
|
||||
for decoder in "${DECODERS[@]}"; do COMMON_OPTIONS+=(--enable-decoder="${decoder}"); done
|
||||
|
||||
configure_abi() {
|
||||
local abi="$1" arch cpu prefix cflags ldflags
|
||||
case "$abi" in
|
||||
arm64-v8a) arch=aarch64; cpu=armv8-a; prefix="aarch64-linux-android${ANDROID_API}-"
|
||||
cflags=""; ldflags="" ;;
|
||||
armeabi-v7a) arch=arm; cpu=armv7-a; prefix="armv7a-linux-androideabi${ANDROID_API}-"
|
||||
cflags="-march=armv7-a -mfloat-abi=softfp"; ldflags="" ;;
|
||||
x86) arch=x86; cpu=i686; prefix="i686-linux-android${ANDROID_API}-"
|
||||
cflags=""; ldflags="--disable-asm" ;;
|
||||
x86_64) arch=x86_64; cpu=x86-64; prefix="x86_64-linux-android${ANDROID_API}-"
|
||||
cflags=""; ldflags="--disable-asm" ;;
|
||||
*) echo "unknown abi: $abi" >&2; exit 1 ;;
|
||||
esac
|
||||
local dir="${BUILD_ROOT}/${abi}"
|
||||
mkdir -p "$dir" "${OUT_DIR}/${abi}"
|
||||
cd "$dir"
|
||||
echo "== configure ${abi} =="
|
||||
# shellcheck disable=SC2086
|
||||
"${FFMPEG_SRC}/configure" \
|
||||
--arch="$arch" --cpu="$cpu" \
|
||||
--libdir="android-libs/${abi}" \
|
||||
--cross-prefix="${TOOLCHAIN}/${prefix}" \
|
||||
--nm="${TOOLCHAIN}/llvm-nm" --ar="${TOOLCHAIN}/llvm-ar" \
|
||||
--ranlib="${TOOLCHAIN}/llvm-ranlib" --strip="${TOOLCHAIN}/llvm-strip" \
|
||||
--extra-cflags="$cflags" ${ldflags} \
|
||||
"${COMMON_OPTIONS[@]}" >/dev/null
|
||||
echo "== make ${abi} =="
|
||||
make -j"$JOBS" >/dev/null
|
||||
make install-libs >/dev/null
|
||||
make clean >/dev/null
|
||||
|
||||
local libs="${dir}/android-libs/${abi}"
|
||||
local link_flags=(-Wl,-z,max-page-size=16384 -Wl,--gc-sections -llog -landroid -lm)
|
||||
[[ "$abi" == "arm64-v8a" ]] && link_flags+=(-Wl,-Bsymbolic)
|
||||
[[ "$abi" == "armeabi-v7a" ]] && link_flags+=(-Wl,--fix-cortex-a8)
|
||||
|
||||
echo "== link libffmpegJNI.so ${abi} =="
|
||||
"${TOOLCHAIN}/${prefix}clang++" -shared -fPIC -O2 -std=c++11 \
|
||||
-fvisibility=hidden -fvisibility-inlines-hidden \
|
||||
-I"${dir}" -I"${FFMPEG_SRC}" "${JNI_SRC}" \
|
||||
"${libs}/libavcodec.a" "${libs}/libswresample.a" "${libs}/libavutil.a" \
|
||||
"${link_flags[@]}" -o "${OUT_DIR}/${abi}/libffmpegJNI.so"
|
||||
"${TOOLCHAIN}/llvm-strip" --strip-unneeded "${OUT_DIR}/${abi}/libffmpegJNI.so"
|
||||
ls -lh "${OUT_DIR}/${abi}/libffmpegJNI.so"
|
||||
}
|
||||
|
||||
for abi in "${ABIS[@]}"; do configure_abi "$abi"; done
|
||||
echo "done: ${OUT_DIR}"
|
||||
Reference in new issue
Block a user