| 6 |
| * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | #include <android/log.h> |
| 17 | #include <jni.h> |
| 18 | #include <stdlib.h> |
| 19 |
| 20 | extern "C" { |
| 21 | #ifdef __cplusplus |
| 22 | #define __STDC_CONSTANT_MACROS |
| 23 | #ifdef _STDINT_H |
| 24 | #undef _STDINT_H |
| 25 | #endif |
| 26 | #include <stdint.h> |
| 27 | #endif |
| 28 | #include "third_party/ffmpeg/libavcodec/avcodec.h" |
| 29 | #include "third_party/ffmpeg/libavutil/channel_layout.h" |
| 30 | #include "third_party/ffmpeg/libavutil/error.h" |
| 31 | #include "third_party/ffmpeg/libavutil/opt.h" |
| 32 | #include "third_party/ffmpeg/libswresample/swresample.h" |
| 33 | } |
| 34 |
| 35 | #define LOG_TAG "ffmpeg_jni" |
| 36 | #define LOGE(...) \ |
| 37 | ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)) |
| 38 | #define LOGD(...) \ |
| 39 | ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)) |
| 40 |
| 41 | #define LIBRARY_FUNC(RETURN_TYPE, NAME, ...) \ |
| 42 | extern "C" { \ |
| 43 | JNIEXPORT RETURN_TYPE \ |
| 44 | Java_androidx_media3_decoder_ffmpeg_FfmpegLibrary_##NAME(JNIEnv *env, \ |
| 45 | jobject thiz, \ |
| 46 | ##__VA_ARGS__); \ |
| 47 | } \ |
| 48 | JNIEXPORT RETURN_TYPE \ |
| 49 | Java_androidx_media3_decoder_ffmpeg_FfmpegLibrary_##NAME( \ |
| 50 | JNIEnv *env, jobject thiz, ##__VA_ARGS__) |
| 51 |
| 52 | #define AUDIO_DECODER_FUNC(RETURN_TYPE, NAME, ...) \ |
| 53 | extern "C" { \ |
| 54 | JNIEXPORT RETURN_TYPE \ |
| 55 | Java_androidx_media3_decoder_ffmpeg_FfmpegAudioDecoder_##NAME( \ |
| 56 | JNIEnv *env, jobject thiz, ##__VA_ARGS__); \ |
| 57 | } \ |
| 58 | JNIEXPORT RETURN_TYPE \ |
| 59 | Java_androidx_media3_decoder_ffmpeg_FfmpegAudioDecoder_##NAME( \ |
| 60 | JNIEnv *env, jobject thiz, ##__VA_ARGS__) |
| 61 |
| 62 | #define ERROR_STRING_BUFFER_LENGTH 256 |
| 63 |
| 64 | // Output format corresponding to AudioFormat.ENCODING_PCM_16BIT. |
| 65 | static const AVSampleFormat OUTPUT_FORMAT_PCM_16BIT = AV_SAMPLE_FMT_S16; |
| 66 | // Output format corresponding to AudioFormat.ENCODING_PCM_FLOAT. |
| 67 | static const AVSampleFormat OUTPUT_FORMAT_PCM_FLOAT = AV_SAMPLE_FMT_FLT; |
| 68 |
| 69 | // LINT.IfChange |
| 70 | static const int AUDIO_DECODER_ERROR_INVALID_DATA = -1; |
| 71 | static const int AUDIO_DECODER_ERROR_OTHER = -2; |
| 72 | // LINT.ThenChange(../java/androidx/media3/decoder/ffmpeg/FfmpegAudioDecoder.java) |
| 73 |
| 74 | static jmethodID growOutputBufferMethod; |
| 75 |
| 76 | /** |
| 77 | * Returns the AVCodec with the specified name, or NULL if it is not available. |
| 78 | */ |
| 79 | const AVCodec *getCodecByName(JNIEnv *env, jstring codecName); |
| 80 |
| 81 | /** |
| 82 | * Allocates and opens a new AVCodecContext for the specified codec, passing the |
| 83 | * provided extraData as initialization data for the decoder if it is non-NULL. |
| 84 | * Returns the created context. |
| 85 | */ |
| 86 | AVCodecContext *createContext(JNIEnv *env, const AVCodec *codec, |
| 87 | jbyteArray extraData, jboolean outputFloat, |
| 88 | jint rawSampleRate, jint rawChannelCount); |
| 89 |
| 90 | struct GrowOutputBufferCallback { |
| 91 | uint8_t *operator()(int requiredSize) const; |
| 92 |
| 93 | JNIEnv *env; |
| 94 | jobject thiz; |
| 95 | jobject decoderOutputBuffer; |
| 96 | }; |
| 97 |
| 98 | /** |
| 99 | * Decodes the packet into the output buffer, returning the number of bytes |
| 100 | * written, or a negative AUDIO_DECODER_ERROR constant value in the case of an |
| 101 | * error. |
| 102 | */ |
| 103 | int decodePacket(AVCodecContext *context, AVPacket *packet, |
| 104 | uint8_t *outputBuffer, int outputSize, |
| 105 | GrowOutputBufferCallback growBuffer); |
| 106 |
| 107 | /** |
| 108 | * Transforms ffmpeg AVERROR into a negative AUDIO_DECODER_ERROR constant value. |
| 109 | */ |
| 110 | int transformError(int errorNumber); |
| 111 |
| 112 | /** |
| 113 | * Outputs a log message describing the avcodec error number. |
| 114 | */ |
| 115 | void logError(const char *functionName, int errorNumber); |
| 116 |
| 117 | /** |
| 118 | * Releases the specified context. |
| 119 | */ |
| 120 | void releaseContext(AVCodecContext *context); |
| 121 |
| 122 | extern "C" { |
| 123 | int ffmpegOnJNILoad(JavaVM *vm, JNIEnv *env) { |
| 124 | jclass clazz = |
| 125 | env->FindClass("androidx/media3/decoder/ffmpeg/FfmpegAudioDecoder"); |
| 126 | if (!clazz) { |
| 127 | LOGE("JNI_OnLoad: FindClass failed"); |
| 128 | return -1; |
| 129 | } |
| 130 | growOutputBufferMethod = |
| 131 | env->GetMethodID(clazz, "growOutputBuffer", |
| 132 | "(Landroidx/media3/decoder/" |
| 133 | "SimpleDecoderOutputBuffer;I)Ljava/nio/ByteBuffer;"); |
| 134 | if (!growOutputBufferMethod) { |
| 135 | LOGE("JNI_OnLoad: GetMethodID failed"); |
| 136 | return -1; |
| 137 | } |
| 138 | return JNI_TRUE; |
| 139 | } |
| 140 | } |
| 141 |
| 142 | LIBRARY_FUNC(jstring, ffmpegGetVersion) { |
| 143 | return env->NewStringUTF(LIBAVCODEC_IDENT); |
| 144 | } |
| 145 |
| 146 | LIBRARY_FUNC(jint, ffmpegGetInputBufferPaddingSize) { |
| 147 | return (jint)AV_INPUT_BUFFER_PADDING_SIZE; |
| 148 | } |
| 149 |
| 150 | LIBRARY_FUNC(jboolean, ffmpegHasDecoder, jstring codecName) { |
| 151 | return getCodecByName(env, codecName) != NULL; |
| 152 | } |
| 153 |
| 154 | AUDIO_DECODER_FUNC(jlong, ffmpegInitialize, jstring codecName, |
| 155 | jbyteArray extraData, jboolean outputFloat, |
| 156 | jint rawSampleRate, jint rawChannelCount) { |
| 157 | const AVCodec *codec = getCodecByName(env, codecName); |
| 158 | if (!codec) { |
| 159 | LOGE("Codec not found."); |
| 160 | return 0L; |
| 161 | } |
| 162 | return (jlong)createContext(env, codec, extraData, outputFloat, rawSampleRate, |
| 163 | rawChannelCount); |
| 164 | } |
| 165 |
| 166 | AUDIO_DECODER_FUNC(jint, ffmpegDecode, jlong context, jobject inputData, |
| 167 | jint inputSize, jobject decoderOutputBuffer, |
| 168 | jobject outputData, jint outputSize) { |
| 169 | if (!context) { |
| 170 | LOGE("Context must be non-NULL."); |
| 171 | return -1; |
| 172 | } |
| 173 | if (!inputData || !decoderOutputBuffer || !outputData) { |
| 174 | LOGE("Input and output buffers must be non-NULL."); |
| 175 | return -1; |
| 176 | } |
| 177 | if (inputSize < 0) { |
| 178 | LOGE("Invalid input buffer size: %d.", inputSize); |
| 179 | return -1; |
| 180 | } |
| 181 | if (outputSize < 0) { |
| 182 | LOGE("Invalid output buffer length: %d", outputSize); |
| 183 | return -1; |
| 184 | } |
| 185 | uint8_t *inputBuffer = (uint8_t *)env->GetDirectBufferAddress(inputData); |
| 186 | uint8_t *outputBuffer = (uint8_t *)env->GetDirectBufferAddress(outputData); |
| 187 | AVPacket *packet = av_packet_alloc(); |
| 188 | if (!packet) { |
| 189 | LOGE("Failed to allocate packet."); |
| 190 | return -1; |
| 191 | } |
| 192 | packet->data = inputBuffer; |
| 193 | packet->size = inputSize; |
| 194 | const int ret = |
| 195 | decodePacket((AVCodecContext *)context, packet, outputBuffer, outputSize, |
| 196 | GrowOutputBufferCallback{env, thiz, decoderOutputBuffer}); |
| 197 | av_packet_free(&packet); |
| 198 | return ret; |
| 199 | } |
| 200 |
| 201 | uint8_t *GrowOutputBufferCallback::operator()(int requiredSize) const { |
| 202 | jobject newOutputData = env->CallObjectMethod( |
| 203 | thiz, growOutputBufferMethod, decoderOutputBuffer, requiredSize); |
| 204 | if (env->ExceptionCheck()) { |
| 205 | LOGE("growOutputBuffer() failed"); |
| 206 | env->ExceptionDescribe(); |
| 207 | return nullptr; |
| 208 | } |
| 209 | return static_cast<uint8_t *>(env->GetDirectBufferAddress(newOutputData)); |
| 210 | } |
| 211 |
| 212 | AUDIO_DECODER_FUNC(jint, ffmpegGetChannelCount, jlong context) { |
| 213 | if (!context) { |
| 214 | LOGE("Context must be non-NULL."); |
| 215 | return -1; |
| 216 | } |
| 217 | return ((AVCodecContext *)context)->ch_layout.nb_channels; |
| 218 | } |
| 219 |
| 220 | AUDIO_DECODER_FUNC(jint, ffmpegGetSampleRate, jlong context) { |
| 221 | if (!context) { |
| 222 | LOGE("Context must be non-NULL."); |
| 223 | return -1; |
| 224 | } |
| 225 | return ((AVCodecContext *)context)->sample_rate; |
| 226 | } |
| 227 |
| 228 | AUDIO_DECODER_FUNC(jlong, ffmpegReset, jlong jContext, jbyteArray extraData) { |
| 229 | AVCodecContext *context = (AVCodecContext *)jContext; |
| 230 | if (!context) { |
| 231 | LOGE("Tried to reset without a context."); |
| 232 | return 0L; |
| 233 | } |
| 234 |
| 235 | AVCodecID codecId = context->codec_id; |
| 236 | if (codecId == AV_CODEC_ID_TRUEHD) { |
| 237 | jboolean outputFloat = |
| 238 | (jboolean)(context->request_sample_fmt == OUTPUT_FORMAT_PCM_FLOAT); |
| 239 | // Release and recreate the context if the codec is TrueHD. |
| 240 | // TODO: Figure out why flushing doesn't work for this codec. |
| 241 | releaseContext(context); |
| 242 | const AVCodec *codec = avcodec_find_decoder(codecId); |
| 243 | if (!codec) { |
| 244 | LOGE("Unexpected error finding codec %d.", codecId); |
| 245 | return 0L; |
| 246 | } |
| 247 | return (jlong)createContext(env, codec, extraData, outputFloat, |
| 248 | /* rawSampleRate= */ -1, |
| 249 | /* rawChannelCount= */ -1); |
| 250 | } |
| 251 |
| 252 | avcodec_flush_buffers(context); |
| 253 | return (jlong)context; |
| 254 | } |
| 255 |
| 256 | AUDIO_DECODER_FUNC(void, ffmpegRelease, jlong context) { |
| 257 | if (context) { |
| 258 | releaseContext((AVCodecContext *)context); |
| 259 | } |
| 260 | } |
| 261 |
| 262 | const AVCodec *getCodecByName(JNIEnv *env, jstring codecName) { |
| 263 | if (!codecName) { |
| 264 | return NULL; |
| 265 | } |
| 266 | const char *codecNameChars = env->GetStringUTFChars(codecName, NULL); |
| 267 | const AVCodec *codec = avcodec_find_decoder_by_name(codecNameChars); |
| 268 | env->ReleaseStringUTFChars(codecName, codecNameChars); |
| 269 | return codec; |
| 270 | } |
| 271 |
| 272 | AVCodecContext *createContext(JNIEnv *env, const AVCodec *codec, |
| 273 | jbyteArray extraData, jboolean outputFloat, |
| 274 | jint rawSampleRate, jint rawChannelCount) { |
| 275 | AVCodecContext *context = avcodec_alloc_context3(codec); |
| 276 | if (!context) { |
| 277 | LOGE("Failed to allocate context."); |
| 278 | return NULL; |
| 279 | } |
| 280 | context->request_sample_fmt = |
| 281 | outputFloat ? OUTPUT_FORMAT_PCM_FLOAT : OUTPUT_FORMAT_PCM_16BIT; |
| 282 | if (extraData) { |
| 283 | jsize size = env->GetArrayLength(extraData); |
| 284 | context->extradata_size = size; |
| 285 | context->extradata = |
| 286 | (uint8_t *)av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE); |
| 287 | if (!context->extradata) { |
| 288 | LOGE("Failed to allocate extradata."); |
| 289 | releaseContext(context); |
| 290 | return NULL; |
| 291 | } |
| 292 | env->GetByteArrayRegion(extraData, 0, size, (jbyte *)context->extradata); |
| 293 | } |
| 294 | if (context->codec_id == AV_CODEC_ID_PCM_MULAW || |
| 295 | context->codec_id == AV_CODEC_ID_PCM_ALAW) { |
| 296 | context->sample_rate = rawSampleRate; |
| 297 | av_channel_layout_default(&context->ch_layout, rawChannelCount); |
| 298 | } |
| 299 | context->err_recognition = AV_EF_IGNORE_ERR; |
| 300 | int result = avcodec_open2(context, codec, NULL); |
| 301 | if (result < 0) { |
| 302 | logError("avcodec_open2", result); |
| 303 | releaseContext(context); |
| 304 | return NULL; |
| 305 | } |
| 306 | return context; |
| 307 | } |
| 308 |
| 309 | int decodePacket(AVCodecContext *context, AVPacket *packet, |
| 310 | uint8_t *outputBuffer, int outputSize, |
| 311 | GrowOutputBufferCallback growBuffer) { |
| 312 | int result = 0; |
| 313 | // Queue input data. |
| 314 | result = avcodec_send_packet(context, packet); |
| 315 | if (result) { |
| 316 | logError("avcodec_send_packet", result); |
| 317 | return transformError(result); |
| 318 | } |
| 319 |
| 320 | // Dequeue output data until it runs out. |
| 321 | int outSize = 0; |
| 322 | while (true) { |
| 323 | AVFrame *frame = av_frame_alloc(); |
| 324 | if (!frame) { |
| 325 | LOGE("Failed to allocate output frame."); |
| 326 | return AUDIO_DECODER_ERROR_INVALID_DATA; |
| 327 | } |
| 328 | result = avcodec_receive_frame(context, frame); |
| 329 | if (result) { |
| 330 | av_frame_free(&frame); |
| 331 | if (result == AVERROR(EAGAIN)) { |
| 332 | break; |
| 333 | } |
| 334 | logError("avcodec_receive_frame", result); |
| 335 | return transformError(result); |
| 336 | } |
| 337 |
| 338 | // Resample output. |
| 339 | AVSampleFormat sampleFormat = context->sample_fmt; |
| 340 | int channelCount = context->ch_layout.nb_channels; |
| 341 | int sampleRate = context->sample_rate; |
| 342 | int sampleCount = frame->nb_samples; |
| 343 | int dataSize = av_samples_get_buffer_size(NULL, channelCount, sampleCount, |
| 344 | sampleFormat, 1); |
| 345 | SwrContext *resampleContext = static_cast<SwrContext *>(context->opaque); |
| 346 | if (!resampleContext) { |
| 347 | result = |
| 348 | swr_alloc_set_opts2(&resampleContext, // ps |
| 349 | &context->ch_layout, // out_ch_layout |
| 350 | context->request_sample_fmt, // out_sample_fmt |
| 351 | sampleRate, // out_sample_rate |
| 352 | &context->ch_layout, // in_ch_layout |
| 353 | sampleFormat, // in_sample_fmt |
| 354 | sampleRate, // in_sample_rate |
| 355 | 0, // log_offset |
| 356 | NULL // log_ctx |
| 357 | ); |
| 358 | if (result < 0) { |
| 359 | logError("swr_alloc_set_opts2", result); |
| 360 | av_frame_free(&frame); |
| 361 | return transformError(result); |
| 362 | } |
| 363 | result = swr_init(resampleContext); |
| 364 | if (result < 0) { |
| 365 | logError("swr_init", result); |
| 366 | av_frame_free(&frame); |
| 367 | return transformError(result); |
| 368 | } |
| 369 | context->opaque = resampleContext; |
| 370 | } |
| 371 |
| 372 | int outSampleSize = av_get_bytes_per_sample(context->request_sample_fmt); |
| 373 | int outSamples = swr_get_out_samples(resampleContext, sampleCount); |
| 374 | int bufferOutSize = outSampleSize * channelCount * outSamples; |
| 375 | if (outSize + bufferOutSize > outputSize) { |
| 376 | LOGD( |
| 377 | "Output buffer size (%d) too small for output data (%d), " |
| 378 | "reallocating buffer.", |
| 379 | outputSize, outSize + bufferOutSize); |
| 380 | outputSize = outSize + bufferOutSize; |
| 381 | outputBuffer = growBuffer(outputSize); |
| 382 | if (!outputBuffer) { |
| 383 | LOGE("Failed to reallocate output buffer."); |
| 384 | av_frame_free(&frame); |
| 385 | return AUDIO_DECODER_ERROR_OTHER; |
| 386 | } |
| 387 | } |
| 388 | result = swr_convert(resampleContext, &outputBuffer, bufferOutSize, |
| 389 | (const uint8_t **)frame->data, frame->nb_samples); |
| 390 | av_frame_free(&frame); |
| 391 | if (result < 0) { |
| 392 | logError("swr_convert", result); |
| 393 | return AUDIO_DECODER_ERROR_INVALID_DATA; |
| 394 | } |
| 395 | int available = swr_get_out_samples(resampleContext, 0); |
| 396 | if (available != 0) { |
| 397 | LOGE("Expected no samples remaining after resampling, but found %d.", |
| 398 | available); |
| 399 | return AUDIO_DECODER_ERROR_INVALID_DATA; |
| 400 | } |
| 401 | outputBuffer += bufferOutSize; |
| 402 | outSize += bufferOutSize; |
| 403 | } |
| 404 | return outSize; |
| 405 | } |
| 406 |
| 407 | int transformError(int errorNumber) { |
| 408 | return errorNumber == AVERROR_INVALIDDATA ? AUDIO_DECODER_ERROR_INVALID_DATA |
| 409 | : AUDIO_DECODER_ERROR_OTHER; |
| 410 | } |
| 411 |
| 412 | void logError(const char *functionName, int errorNumber) { |
| 413 | char *buffer = (char *)malloc(ERROR_STRING_BUFFER_LENGTH * sizeof(char)); |
| 414 | av_strerror(errorNumber, buffer, ERROR_STRING_BUFFER_LENGTH); |
| 415 | LOGE("Error in %s: %s", functionName, buffer); |
| 416 | free(buffer); |
| 417 | } |
| 418 |
| 419 | void releaseContext(AVCodecContext *context) { |
| 420 | if (!context) { |
| 421 | return; |
| 422 | } |
| 423 | SwrContext *swrContext; |
| 424 | if ((swrContext = (SwrContext *)context->opaque)) { |
| 425 | swr_free(&swrContext); |
| 426 | context->opaque = NULL; |
| 427 | } |
| 428 | avcodec_free_context(&context); |
| 429 | } |
| 430 |