| 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 <libavcodec/avcodec.h> |
| 29 | #include <libavutil/channel_layout.h> |
| 30 | #include <libavutil/error.h> |
| 31 | #include <libavutil/opt.h> |
| 32 | #include <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 |
| 39 | #define LIBRARY_FUNC(RETURN_TYPE, NAME, ...) \ |
| 40 | extern "C" { \ |
| 41 | JNIEXPORT RETURN_TYPE \ |
| 42 | Java_com_google_android_exoplayer2_ext_ffmpeg_FfmpegLibrary_##NAME( \ |
| 43 | JNIEnv *env, jobject thiz, ##__VA_ARGS__); \ |
| 44 | } \ |
| 45 | JNIEXPORT RETURN_TYPE \ |
| 46 | Java_com_google_android_exoplayer2_ext_ffmpeg_FfmpegLibrary_##NAME( \ |
| 47 | JNIEnv *env, jobject thiz, ##__VA_ARGS__) |
| 48 |
| 49 | #define AUDIO_DECODER_FUNC(RETURN_TYPE, NAME, ...) \ |
| 50 | extern "C" { \ |
| 51 | JNIEXPORT RETURN_TYPE \ |
| 52 | Java_com_google_android_exoplayer2_ext_ffmpeg_FfmpegAudioDecoder_##NAME( \ |
| 53 | JNIEnv *env, jobject thiz, ##__VA_ARGS__); \ |
| 54 | } \ |
| 55 | JNIEXPORT RETURN_TYPE \ |
| 56 | Java_com_google_android_exoplayer2_ext_ffmpeg_FfmpegAudioDecoder_##NAME( \ |
| 57 | JNIEnv *env, jobject thiz, ##__VA_ARGS__) |
| 58 |
| 59 | #define ERROR_STRING_BUFFER_LENGTH 256 |
| 60 |
| 61 | // Output format corresponding to AudioFormat.ENCODING_PCM_16BIT. |
| 62 | static const AVSampleFormat OUTPUT_FORMAT_PCM_16BIT = AV_SAMPLE_FMT_S16; |
| 63 | // Output format corresponding to AudioFormat.ENCODING_PCM_FLOAT. |
| 64 | static const AVSampleFormat OUTPUT_FORMAT_PCM_FLOAT = AV_SAMPLE_FMT_FLT; |
| 65 |
| 66 | static const int AUDIO_DECODER_ERROR_INVALID_DATA = -1; |
| 67 | static const int AUDIO_DECODER_ERROR_OTHER = -2; |
| 68 |
| 69 | /** |
| 70 | * Returns the AVCodec with the specified name, or NULL if it is not available. |
| 71 | */ |
| 72 | const AVCodec *getCodecByName(JNIEnv *env, jstring codecName); |
| 73 |
| 74 | /** |
| 75 | * Allocates and opens a new AVCodecContext for the specified codec, passing the |
| 76 | * provided extraData as initialization data for the decoder if it is non-NULL. |
| 77 | * Returns the created context. |
| 78 | */ |
| 79 | AVCodecContext *createContext(JNIEnv *env, const AVCodec *codec, jbyteArray extraData, |
| 80 | jboolean outputFloat, jint rawSampleRate, |
| 81 | jint rawChannelCount); |
| 82 |
| 83 | /** |
| 84 | * Decodes the packet into the output buffer, returning the number of bytes |
| 85 | * written, or a negative AUDIO_DECODER_ERROR constant value in the case of an |
| 86 | * error. |
| 87 | */ |
| 88 | int decodePacket(AVCodecContext *context, AVPacket *packet, |
| 89 | uint8_t *outputBuffer, int outputSize); |
| 90 |
| 91 | /** |
| 92 | * Transforms ffmpeg AVERROR into a negative AUDIO_DECODER_ERROR constant value. |
| 93 | */ |
| 94 | int transformError(int errorNumber); |
| 95 |
| 96 | /** |
| 97 | * Outputs a log message describing the avcodec error number. |
| 98 | */ |
| 99 | void logError(const char *functionName, int errorNumber); |
| 100 |
| 101 | /** |
| 102 | * Releases the specified context. |
| 103 | */ |
| 104 | void releaseContext(AVCodecContext *context); |
| 105 |
| 106 | LIBRARY_FUNC(jstring, ffmpegGetVersion) { |
| 107 | return env->NewStringUTF(LIBAVCODEC_IDENT); |
| 108 | } |
| 109 |
| 110 | LIBRARY_FUNC(jint, ffmpegGetInputBufferPaddingSize) { |
| 111 | return (jint)AV_INPUT_BUFFER_PADDING_SIZE; |
| 112 | } |
| 113 |
| 114 | LIBRARY_FUNC(jboolean, ffmpegHasDecoder, jstring codecName) { |
| 115 | return getCodecByName(env, codecName) != NULL; |
| 116 | } |
| 117 |
| 118 | AUDIO_DECODER_FUNC(jlong, ffmpegInitialize, jstring codecName, |
| 119 | jbyteArray extraData, jboolean outputFloat, |
| 120 | jint rawSampleRate, jint rawChannelCount) { |
| 121 | const AVCodec *codec = getCodecByName(env, codecName); |
| 122 | if (!codec) { |
| 123 | LOGE("Codec not found."); |
| 124 | return 0L; |
| 125 | } |
| 126 | return (jlong)createContext(env, codec, extraData, outputFloat, rawSampleRate, |
| 127 | rawChannelCount); |
| 128 | } |
| 129 |
| 130 | AUDIO_DECODER_FUNC(jint, ffmpegDecode, jlong context, jobject inputData, |
| 131 | jint inputSize, jobject outputData, jint outputSize) { |
| 132 | if (!context) { |
| 133 | LOGE("Context must be non-NULL."); |
| 134 | return -1; |
| 135 | } |
| 136 | if (!inputData || !outputData) { |
| 137 | LOGE("Input and output buffers must be non-NULL."); |
| 138 | return -1; |
| 139 | } |
| 140 | if (inputSize < 0) { |
| 141 | LOGE("Invalid input buffer size: %d.", inputSize); |
| 142 | return -1; |
| 143 | } |
| 144 | if (outputSize < 0) { |
| 145 | LOGE("Invalid output buffer length: %d", outputSize); |
| 146 | return -1; |
| 147 | } |
| 148 | uint8_t *inputBuffer = (uint8_t *)env->GetDirectBufferAddress(inputData); |
| 149 | uint8_t *outputBuffer = (uint8_t *)env->GetDirectBufferAddress(outputData); |
| 150 | AVPacket packet; |
| 151 | av_init_packet(&packet); |
| 152 | packet.data = inputBuffer; |
| 153 | packet.size = inputSize; |
| 154 | return decodePacket((AVCodecContext *)context, &packet, outputBuffer, |
| 155 | outputSize); |
| 156 | } |
| 157 |
| 158 | AUDIO_DECODER_FUNC(jint, ffmpegGetChannelCount, jlong context) { |
| 159 | if (!context) { |
| 160 | LOGE("Context must be non-NULL."); |
| 161 | return -1; |
| 162 | } |
| 163 | return ((AVCodecContext *)context)->ch_layout.nb_channels; |
| 164 | } |
| 165 |
| 166 | AUDIO_DECODER_FUNC(jint, ffmpegGetSampleRate, jlong context) { |
| 167 | if (!context) { |
| 168 | LOGE("Context must be non-NULL."); |
| 169 | return -1; |
| 170 | } |
| 171 | return ((AVCodecContext *)context)->sample_rate; |
| 172 | } |
| 173 |
| 174 | AUDIO_DECODER_FUNC(jlong, ffmpegReset, jlong jContext, jbyteArray extraData) { |
| 175 | AVCodecContext *context = (AVCodecContext *)jContext; |
| 176 | if (!context) { |
| 177 | LOGE("Tried to reset without a context."); |
| 178 | return 0L; |
| 179 | } |
| 180 |
| 181 | AVCodecID codecId = context->codec_id; |
| 182 | if (codecId == AV_CODEC_ID_TRUEHD) { |
| 183 | // Release and recreate the context if the codec is TrueHD. |
| 184 | // TODO: Figure out why flushing doesn't work for this codec. |
| 185 | releaseContext(context); |
| 186 | const AVCodec *codec = avcodec_find_decoder(codecId); |
| 187 | if (!codec) { |
| 188 | LOGE("Unexpected error finding codec %d.", codecId); |
| 189 | return 0L; |
| 190 | } |
| 191 | jboolean outputFloat = |
| 192 | (jboolean)(context->request_sample_fmt == OUTPUT_FORMAT_PCM_FLOAT); |
| 193 | return (jlong)createContext(env, codec, extraData, outputFloat, |
| 194 | /* rawSampleRate= */ -1, |
| 195 | /* rawChannelCount= */ -1); |
| 196 | } |
| 197 |
| 198 | avcodec_flush_buffers(context); |
| 199 | return (jlong)context; |
| 200 | } |
| 201 |
| 202 | AUDIO_DECODER_FUNC(void, ffmpegRelease, jlong context) { |
| 203 | if (context) { |
| 204 | releaseContext((AVCodecContext *)context); |
| 205 | } |
| 206 | } |
| 207 |
| 208 | const AVCodec *getCodecByName(JNIEnv *env, jstring codecName) { |
| 209 | if (!codecName) { |
| 210 | return NULL; |
| 211 | } |
| 212 | const char *codecNameChars = env->GetStringUTFChars(codecName, NULL); |
| 213 | const AVCodec *codec = avcodec_find_decoder_by_name(codecNameChars); |
| 214 | env->ReleaseStringUTFChars(codecName, codecNameChars); |
| 215 | return codec; |
| 216 | } |
| 217 |
| 218 | AVCodecContext *createContext(JNIEnv *env, const AVCodec *codec, jbyteArray extraData, |
| 219 | jboolean outputFloat, jint rawSampleRate, |
| 220 | jint rawChannelCount) { |
| 221 | AVCodecContext *context = avcodec_alloc_context3(codec); |
| 222 | if (!context) { |
| 223 | LOGE("Failed to allocate context."); |
| 224 | return NULL; |
| 225 | } |
| 226 | context->request_sample_fmt = |
| 227 | outputFloat ? OUTPUT_FORMAT_PCM_FLOAT : OUTPUT_FORMAT_PCM_16BIT; |
| 228 | if (extraData) { |
| 229 | jsize size = env->GetArrayLength(extraData); |
| 230 | context->extradata_size = size; |
| 231 | context->extradata = |
| 232 | (uint8_t *)av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE); |
| 233 | if (!context->extradata) { |
| 234 | LOGE("Failed to allocate extradata."); |
| 235 | releaseContext(context); |
| 236 | return NULL; |
| 237 | } |
| 238 | env->GetByteArrayRegion(extraData, 0, size, (jbyte *)context->extradata); |
| 239 | } |
| 240 | if (context->codec_id == AV_CODEC_ID_PCM_MULAW || |
| 241 | context->codec_id == AV_CODEC_ID_PCM_ALAW) { |
| 242 | context->sample_rate = rawSampleRate; |
| 243 | av_channel_layout_uninit(&context->ch_layout); |
| 244 | av_channel_layout_default(&context->ch_layout, rawChannelCount); |
| 245 | } |
| 246 | context->err_recognition = AV_EF_IGNORE_ERR; |
| 247 | int result = avcodec_open2(context, codec, NULL); |
| 248 | if (result < 0) { |
| 249 | logError("avcodec_open2", result); |
| 250 | releaseContext(context); |
| 251 | return NULL; |
| 252 | } |
| 253 | return context; |
| 254 | } |
| 255 |
| 256 | int get_swr_context(AVCodecContext *context, SwrContext **out) { |
| 257 | if (context == nullptr || out == nullptr) { |
| 258 | return AVERROR(EINVAL); |
| 259 | } |
| 260 |
| 261 | const AVSampleFormat inputFormat = context->sample_fmt; |
| 262 | const AVSampleFormat outputFormat = context->request_sample_fmt; |
| 263 | const int sampleRate = context->sample_rate; |
| 264 |
| 265 | if (inputFormat == AV_SAMPLE_FMT_NONE || |
| 266 | outputFormat == AV_SAMPLE_FMT_NONE || |
| 267 | sampleRate <= 0 || |
| 268 | context->ch_layout.nb_channels <= 0) { |
| 269 | return AVERROR(EINVAL); |
| 270 | } |
| 271 |
| 272 | SwrContext *resampleContext = |
| 273 | static_cast<SwrContext *>(context->opaque); |
| 274 |
| 275 | if (resampleContext != nullptr) { |
| 276 | AVChannelLayout inputLayout = {}; |
| 277 | AVChannelLayout outputLayout = {}; |
| 278 |
| 279 | int64_t value = 0; |
| 280 | bool mismatch = false; |
| 281 |
| 282 | if (av_opt_get_chlayout( |
| 283 | resampleContext, |
| 284 | "in_chlayout", |
| 285 | 0, |
| 286 | &inputLayout) < 0) { |
| 287 | mismatch = true; |
| 288 | } else if (av_channel_layout_compare( |
| 289 | &inputLayout, |
| 290 | &context->ch_layout) != 0) { |
| 291 | mismatch = true; |
| 292 | } |
| 293 |
| 294 | if (!mismatch && |
| 295 | av_opt_get_chlayout( |
| 296 | resampleContext, |
| 297 | "out_chlayout", |
| 298 | 0, |
| 299 | &outputLayout) < 0) { |
| 300 | mismatch = true; |
| 301 | } else if (!mismatch && |
| 302 | av_channel_layout_compare( |
| 303 | &outputLayout, |
| 304 | &context->ch_layout) != 0) { |
| 305 | mismatch = true; |
| 306 | } |
| 307 |
| 308 | if (!mismatch && |
| 309 | (av_opt_get_int( |
| 310 | resampleContext, |
| 311 | "in_sample_rate", |
| 312 | 0, |
| 313 | &value) < 0 || |
| 314 | value != sampleRate)) { |
| 315 | mismatch = true; |
| 316 | } |
| 317 |
| 318 | if (!mismatch && |
| 319 | (av_opt_get_int( |
| 320 | resampleContext, |
| 321 | "out_sample_rate", |
| 322 | 0, |
| 323 | &value) < 0 || |
| 324 | value != sampleRate)) { |
| 325 | mismatch = true; |
| 326 | } |
| 327 |
| 328 | if (!mismatch && |
| 329 | (av_opt_get_sample_fmt( |
| 330 | resampleContext, |
| 331 | "in_sample_fmt", |
| 332 | 0, |
| 333 | reinterpret_cast<AVSampleFormat *>(&value)) < 0 || |
| 334 | static_cast<AVSampleFormat>(value) != inputFormat)) { |
| 335 | mismatch = true; |
| 336 | } |
| 337 |
| 338 | if (!mismatch && |
| 339 | (av_opt_get_sample_fmt( |
| 340 | resampleContext, |
| 341 | "out_sample_fmt", |
| 342 | 0, |
| 343 | reinterpret_cast<AVSampleFormat *>(&value)) < 0 || |
| 344 | static_cast<AVSampleFormat>(value) != outputFormat)) { |
| 345 | mismatch = true; |
| 346 | } |
| 347 |
| 348 | av_channel_layout_uninit(&inputLayout); |
| 349 | av_channel_layout_uninit(&outputLayout); |
| 350 |
| 351 | if (mismatch) { |
| 352 | swr_free(&resampleContext); |
| 353 | context->opaque = nullptr; |
| 354 | } |
| 355 | } |
| 356 |
| 357 | if (resampleContext == nullptr) { |
| 358 | int result = swr_alloc_set_opts2( |
| 359 | &resampleContext, |
| 360 | &context->ch_layout, |
| 361 | outputFormat, |
| 362 | sampleRate, |
| 363 | &context->ch_layout, |
| 364 | inputFormat, |
| 365 | sampleRate, |
| 366 | 0, |
| 367 | context |
| 368 | ); |
| 369 |
| 370 | if (result < 0) { |
| 371 | return result; |
| 372 | } |
| 373 |
| 374 | result = swr_init(resampleContext); |
| 375 | if (result < 0) { |
| 376 | swr_free(&resampleContext); |
| 377 | return result; |
| 378 | } |
| 379 | context->opaque = resampleContext; |
| 380 | } |
| 381 |
| 382 | *out = resampleContext; |
| 383 | return 0; |
| 384 | } |
| 385 |
| 386 | int decodePacket(AVCodecContext *context, AVPacket *packet, |
| 387 | uint8_t *outputBuffer, int outputSize) { |
| 388 | int result = 0; |
| 389 | // Queue input data. |
| 390 | result = avcodec_send_packet(context, packet); |
| 391 | if (result) { |
| 392 | logError("avcodec_send_packet", result); |
| 393 | return transformError(result); |
| 394 | } |
| 395 |
| 396 | // Dequeue output data until it runs out. |
| 397 | int outSize = 0; |
| 398 | while (true) { |
| 399 | AVFrame *frame = av_frame_alloc(); |
| 400 | if (!frame) { |
| 401 | LOGE("Failed to allocate output frame."); |
| 402 | return AUDIO_DECODER_ERROR_INVALID_DATA; |
| 403 | } |
| 404 | result = avcodec_receive_frame(context, frame); |
| 405 | if (result) { |
| 406 | av_frame_free(&frame); |
| 407 | if (result == AVERROR(EAGAIN)) { |
| 408 | break; |
| 409 | } |
| 410 | logError("avcodec_receive_frame", result); |
| 411 | return transformError(result); |
| 412 | } |
| 413 |
| 414 | // Resample output. |
| 415 | AVSampleFormat sampleFormat = context->sample_fmt; |
| 416 | int channelCount = context->ch_layout.nb_channels; |
| 417 | int sampleCount = frame->nb_samples; |
| 418 |
| 419 | SwrContext *resampleContext; |
| 420 | int result; |
| 421 | if ((result = get_swr_context(context, &resampleContext)) < 0) { |
| 422 | logError("swr_init", result); |
| 423 | av_frame_free(&frame); |
| 424 | return transformError(result); |
| 425 | } |
| 426 |
| 427 | int inSampleSize = av_get_bytes_per_sample(sampleFormat); |
| 428 | int outSampleSize = av_get_bytes_per_sample(context->request_sample_fmt); |
| 429 | int outSamples = swr_get_out_samples(resampleContext, sampleCount); |
| 430 | int bufferOutSize = outSampleSize * channelCount * outSamples; |
| 431 | if (outSize + bufferOutSize > outputSize) { |
| 432 | LOGE("Output buffer size (%d) too small for output data (%d).", |
| 433 | outputSize, outSize + bufferOutSize); |
| 434 | av_frame_free(&frame); |
| 435 | return AUDIO_DECODER_ERROR_INVALID_DATA; |
| 436 | } |
| 437 | result = swr_convert(resampleContext, &outputBuffer, bufferOutSize, |
| 438 | (const uint8_t **)frame->data, frame->nb_samples); |
| 439 | av_frame_free(&frame); |
| 440 | if (result < 0) { |
| 441 | logError("swr_convert", result); |
| 442 | return AUDIO_DECODER_ERROR_INVALID_DATA; |
| 443 | } |
| 444 | int available = swr_get_out_samples(resampleContext, 0); |
| 445 | if (available != 0) { |
| 446 | LOGE("Expected no samples remaining after resampling, but found %d.", |
| 447 | available); |
| 448 | return AUDIO_DECODER_ERROR_INVALID_DATA; |
| 449 | } |
| 450 | outputBuffer += bufferOutSize; |
| 451 | outSize += bufferOutSize; |
| 452 | } |
| 453 | return outSize; |
| 454 | } |
| 455 |
| 456 | int transformError(int errorNumber) { |
| 457 | return errorNumber == AVERROR_INVALIDDATA ? AUDIO_DECODER_ERROR_INVALID_DATA |
| 458 | : AUDIO_DECODER_ERROR_OTHER; |
| 459 | } |
| 460 |
| 461 | void logError(const char *functionName, int errorNumber) { |
| 462 | char *buffer = (char *)malloc(ERROR_STRING_BUFFER_LENGTH * sizeof(char)); |
| 463 | av_strerror(errorNumber, buffer, ERROR_STRING_BUFFER_LENGTH); |
| 464 | LOGE("Error in %s: %s", functionName, buffer); |
| 465 | free(buffer); |
| 466 | } |
| 467 |
| 468 | void releaseContext(AVCodecContext *context) { |
| 469 | if (!context) { |
| 470 | return; |
| 471 | } |
| 472 | SwrContext *swrContext; |
| 473 | if ((swrContext = (SwrContext *)context->opaque)) { |
| 474 | swr_free(&swrContext); |
| 475 | context->opaque = NULL; |
| 476 | } |
| 477 | avcodec_free_context(&context); |
| 478 | } |
| 479 |