| 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 <jni.h> |
| 17 | #include <stdlib.h> |
| 18 | #include <android/log.h> |
| 19 |
| 20 | extern "C" { |
| 21 | #ifdef __cplusplus |
| 22 | #ifdef _STDINT_H |
| 23 | #undef _STDINT_H |
| 24 | #endif |
| 25 | #include <stdint.h> |
| 26 | #endif |
| 27 | #include <libavcodec/avcodec.h> |
| 28 | #include <libavresample/avresample.h> |
| 29 | #include <libavutil/channel_layout.h> |
| 30 | #include <libavutil/error.h> |
| 31 | #include <libavutil/opt.h> |
| 32 | } |
| 33 |
| 34 | #define LOG_TAG "ffmpeg_jni" |
| 35 | #define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, \ |
| 36 | __VA_ARGS__)) |
| 37 |
| 38 | #define DECODER_FUNC(RETURN_TYPE, NAME, ...) \ |
| 39 | extern "C" { \ |
| 40 | JNIEXPORT RETURN_TYPE \ |
| 41 | Java_com_google_android_exoplayer2_ext_ffmpeg_FfmpegDecoder_ ## NAME \ |
| 42 | (JNIEnv* env, jobject thiz, ##__VA_ARGS__);\ |
| 43 | } \ |
| 44 | JNIEXPORT RETURN_TYPE \ |
| 45 | Java_com_google_android_exoplayer2_ext_ffmpeg_FfmpegDecoder_ ## NAME \ |
| 46 | (JNIEnv* env, jobject thiz, ##__VA_ARGS__)\ |
| 47 |
| 48 | #define LIBRARY_FUNC(RETURN_TYPE, NAME, ...) \ |
| 49 | extern "C" { \ |
| 50 | JNIEXPORT RETURN_TYPE \ |
| 51 | Java_com_google_android_exoplayer2_ext_ffmpeg_FfmpegLibrary_ ## NAME \ |
| 52 | (JNIEnv* env, jobject thiz, ##__VA_ARGS__);\ |
| 53 | } \ |
| 54 | JNIEXPORT RETURN_TYPE \ |
| 55 | Java_com_google_android_exoplayer2_ext_ffmpeg_FfmpegLibrary_ ## NAME \ |
| 56 | (JNIEnv* env, jobject thiz, ##__VA_ARGS__)\ |
| 57 |
| 58 | #define ERROR_STRING_BUFFER_LENGTH 256 |
| 59 |
| 60 | // Output format corresponding to AudioFormat.ENCODING_PCM_16BIT. |
| 61 | static const AVSampleFormat OUTPUT_FORMAT_PCM_16BIT = AV_SAMPLE_FMT_S16; |
| 62 | // Output format corresponding to AudioFormat.ENCODING_PCM_FLOAT. |
| 63 | static const AVSampleFormat OUTPUT_FORMAT_PCM_FLOAT = AV_SAMPLE_FMT_FLT; |
| 64 |
| 65 | // Error codes matching FfmpegDecoder.java. |
| 66 | static const int DECODER_ERROR_INVALID_DATA = -1; |
| 67 | static const int DECODER_ERROR_OTHER = -2; |
| 68 |
| 69 | /** |
| 70 | * Returns the AVCodec with the specified name, or NULL if it is not available. |
| 71 | */ |
| 72 | 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, 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 DECODER_ERROR constant value in the case of an error. |
| 86 | */ |
| 87 | int decodePacket(AVCodecContext *context, AVPacket *packet, |
| 88 | uint8_t *outputBuffer, int outputSize); |
| 89 |
| 90 | /** |
| 91 | * Outputs a log message describing the avcodec error number. |
| 92 | */ |
| 93 | void logError(const char *functionName, int errorNumber); |
| 94 |
| 95 | /** |
| 96 | * Releases the specified context. |
| 97 | */ |
| 98 | void releaseContext(AVCodecContext *context); |
| 99 |
| 100 | LIBRARY_FUNC(jstring, ffmpegGetVersion) { |
| 101 | return env->NewStringUTF(LIBAVCODEC_IDENT); |
| 102 | } |
| 103 |
| 104 | LIBRARY_FUNC(jboolean, ffmpegHasDecoder, jstring codecName) { |
| 105 | return getCodecByName(env, codecName) != NULL; |
| 106 | } |
| 107 |
| 108 | DECODER_FUNC(jlong, ffmpegInitialize, jstring codecName, jbyteArray extraData, |
| 109 | jboolean outputFloat, jint rawSampleRate, jint rawChannelCount) { |
| 110 | AVCodec *codec = getCodecByName(env, codecName); |
| 111 | if (!codec) { |
| 112 | LOGE("Codec not found."); |
| 113 | return 0L; |
| 114 | } |
| 115 | return (jlong)createContext(env, codec, extraData, outputFloat, rawSampleRate, |
| 116 | rawChannelCount); |
| 117 | } |
| 118 |
| 119 | DECODER_FUNC(jint, ffmpegDecode, jlong context, jobject inputData, |
| 120 | jint inputSize, jobject outputData, jint outputSize) { |
| 121 | if (!context) { |
| 122 | LOGE("Context must be non-NULL."); |
| 123 | return -1; |
| 124 | } |
| 125 | if (!inputData || !outputData) { |
| 126 | LOGE("Input and output buffers must be non-NULL."); |
| 127 | return -1; |
| 128 | } |
| 129 | if (inputSize < 0) { |
| 130 | LOGE("Invalid input buffer size: %d.", inputSize); |
| 131 | return -1; |
| 132 | } |
| 133 | if (outputSize < 0) { |
| 134 | LOGE("Invalid output buffer length: %d", outputSize); |
| 135 | return -1; |
| 136 | } |
| 137 | uint8_t *inputBuffer = (uint8_t *) env->GetDirectBufferAddress(inputData); |
| 138 | uint8_t *outputBuffer = (uint8_t *) env->GetDirectBufferAddress(outputData); |
| 139 | AVPacket packet; |
| 140 | av_init_packet(&packet); |
| 141 | packet.data = inputBuffer; |
| 142 | packet.size = inputSize; |
| 143 | return decodePacket((AVCodecContext *) context, &packet, outputBuffer, |
| 144 | outputSize); |
| 145 | } |
| 146 |
| 147 | DECODER_FUNC(jint, ffmpegGetChannelCount, jlong context) { |
| 148 | if (!context) { |
| 149 | LOGE("Context must be non-NULL."); |
| 150 | return -1; |
| 151 | } |
| 152 | return ((AVCodecContext *) context)->channels; |
| 153 | } |
| 154 |
| 155 | DECODER_FUNC(jint, ffmpegGetSampleRate, jlong context) { |
| 156 | if (!context) { |
| 157 | LOGE("Context must be non-NULL."); |
| 158 | return -1; |
| 159 | } |
| 160 | return ((AVCodecContext *) context)->sample_rate; |
| 161 | } |
| 162 |
| 163 | DECODER_FUNC(jlong, ffmpegReset, jlong jContext, jbyteArray extraData) { |
| 164 | AVCodecContext *context = (AVCodecContext *) jContext; |
| 165 | if (!context) { |
| 166 | LOGE("Tried to reset without a context."); |
| 167 | return 0L; |
| 168 | } |
| 169 |
| 170 | AVCodecID codecId = context->codec_id; |
| 171 | if (codecId == AV_CODEC_ID_TRUEHD) { |
| 172 | // Release and recreate the context if the codec is TrueHD. |
| 173 | // TODO: Figure out why flushing doesn't work for this codec. |
| 174 | releaseContext(context); |
| 175 | AVCodec *codec = avcodec_find_decoder(codecId); |
| 176 | if (!codec) { |
| 177 | LOGE("Unexpected error finding codec %d.", codecId); |
| 178 | return 0L; |
| 179 | } |
| 180 | jboolean outputFloat = |
| 181 | (jboolean)(context->request_sample_fmt == OUTPUT_FORMAT_PCM_FLOAT); |
| 182 | return (jlong)createContext(env, codec, extraData, outputFloat, |
| 183 | /* rawSampleRate= */ -1, |
| 184 | /* rawChannelCount= */ -1); |
| 185 | } |
| 186 |
| 187 | avcodec_flush_buffers(context); |
| 188 | return (jlong) context; |
| 189 | } |
| 190 |
| 191 | DECODER_FUNC(void, ffmpegRelease, jlong context) { |
| 192 | if (context) { |
| 193 | releaseContext((AVCodecContext *) context); |
| 194 | } |
| 195 | } |
| 196 |
| 197 | AVCodec *getCodecByName(JNIEnv* env, jstring codecName) { |
| 198 | if (!codecName) { |
| 199 | return NULL; |
| 200 | } |
| 201 | const char *codecNameChars = env->GetStringUTFChars(codecName, NULL); |
| 202 | AVCodec *codec = avcodec_find_decoder_by_name(codecNameChars); |
| 203 | env->ReleaseStringUTFChars(codecName, codecNameChars); |
| 204 | return codec; |
| 205 | } |
| 206 |
| 207 | AVCodecContext *createContext(JNIEnv *env, AVCodec *codec, jbyteArray extraData, |
| 208 | jboolean outputFloat, jint rawSampleRate, |
| 209 | jint rawChannelCount) { |
| 210 | AVCodecContext *context = avcodec_alloc_context3(codec); |
| 211 | if (!context) { |
| 212 | LOGE("Failed to allocate context."); |
| 213 | return NULL; |
| 214 | } |
| 215 | context->request_sample_fmt = |
| 216 | outputFloat ? OUTPUT_FORMAT_PCM_FLOAT : OUTPUT_FORMAT_PCM_16BIT; |
| 217 | if (extraData) { |
| 218 | jsize size = env->GetArrayLength(extraData); |
| 219 | context->extradata_size = size; |
| 220 | context->extradata = |
| 221 | (uint8_t *) av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE); |
| 222 | if (!context->extradata) { |
| 223 | LOGE("Failed to allocate extradata."); |
| 224 | releaseContext(context); |
| 225 | return NULL; |
| 226 | } |
| 227 | env->GetByteArrayRegion(extraData, 0, size, (jbyte *) context->extradata); |
| 228 | } |
| 229 | if (context->codec_id == AV_CODEC_ID_PCM_MULAW || |
| 230 | context->codec_id == AV_CODEC_ID_PCM_ALAW) { |
| 231 | context->sample_rate = rawSampleRate; |
| 232 | context->channels = rawChannelCount; |
| 233 | context->channel_layout = av_get_default_channel_layout(rawChannelCount); |
| 234 | } |
| 235 | context->err_recognition = AV_EF_IGNORE_ERR; |
| 236 | int result = avcodec_open2(context, codec, NULL); |
| 237 | if (result < 0) { |
| 238 | logError("avcodec_open2", result); |
| 239 | releaseContext(context); |
| 240 | return NULL; |
| 241 | } |
| 242 | return context; |
| 243 | } |
| 244 |
| 245 | int decodePacket(AVCodecContext *context, AVPacket *packet, |
| 246 | uint8_t *outputBuffer, int outputSize) { |
| 247 | int result = 0; |
| 248 | // Queue input data. |
| 249 | result = avcodec_send_packet(context, packet); |
| 250 | if (result) { |
| 251 | logError("avcodec_send_packet", result); |
| 252 | return result == AVERROR_INVALIDDATA ? DECODER_ERROR_INVALID_DATA |
| 253 | : DECODER_ERROR_OTHER; |
| 254 | } |
| 255 |
| 256 | // Dequeue output data until it runs out. |
| 257 | int outSize = 0; |
| 258 | while (true) { |
| 259 | AVFrame *frame = av_frame_alloc(); |
| 260 | if (!frame) { |
| 261 | LOGE("Failed to allocate output frame."); |
| 262 | return -1; |
| 263 | } |
| 264 | result = avcodec_receive_frame(context, frame); |
| 265 | if (result) { |
| 266 | av_frame_free(&frame); |
| 267 | if (result == AVERROR(EAGAIN)) { |
| 268 | break; |
| 269 | } |
| 270 | logError("avcodec_receive_frame", result); |
| 271 | return result; |
| 272 | } |
| 273 |
| 274 | // Resample output. |
| 275 | AVSampleFormat sampleFormat = context->sample_fmt; |
| 276 | int channelCount = context->channels; |
| 277 | int channelLayout = context->channel_layout; |
| 278 | int sampleRate = context->sample_rate; |
| 279 | int sampleCount = frame->nb_samples; |
| 280 | int dataSize = av_samples_get_buffer_size(NULL, channelCount, sampleCount, |
| 281 | sampleFormat, 1); |
| 282 | AVAudioResampleContext *resampleContext; |
| 283 | if (context->opaque) { |
| 284 | resampleContext = (AVAudioResampleContext *) context->opaque; |
| 285 | } else { |
| 286 | resampleContext = avresample_alloc_context(); |
| 287 | av_opt_set_int(resampleContext, "in_channel_layout", channelLayout, 0); |
| 288 | av_opt_set_int(resampleContext, "out_channel_layout", channelLayout, 0); |
| 289 | av_opt_set_int(resampleContext, "in_sample_rate", sampleRate, 0); |
| 290 | av_opt_set_int(resampleContext, "out_sample_rate", sampleRate, 0); |
| 291 | av_opt_set_int(resampleContext, "in_sample_fmt", sampleFormat, 0); |
| 292 | // The output format is always the requested format. |
| 293 | av_opt_set_int(resampleContext, "out_sample_fmt", |
| 294 | context->request_sample_fmt, 0); |
| 295 | result = avresample_open(resampleContext); |
| 296 | if (result < 0) { |
| 297 | logError("avresample_open", result); |
| 298 | av_frame_free(&frame); |
| 299 | return -1; |
| 300 | } |
| 301 | context->opaque = resampleContext; |
| 302 | } |
| 303 | int inSampleSize = av_get_bytes_per_sample(sampleFormat); |
| 304 | int outSampleSize = av_get_bytes_per_sample(context->request_sample_fmt); |
| 305 | int outSamples = avresample_get_out_samples(resampleContext, sampleCount); |
| 306 | int bufferOutSize = outSampleSize * channelCount * outSamples; |
| 307 | if (outSize + bufferOutSize > outputSize) { |
| 308 | LOGE("Output buffer size (%d) too small for output data (%d).", |
| 309 | outputSize, outSize + bufferOutSize); |
| 310 | av_frame_free(&frame); |
| 311 | return -1; |
| 312 | } |
| 313 | result = avresample_convert(resampleContext, &outputBuffer, bufferOutSize, |
| 314 | outSamples, frame->data, frame->linesize[0], |
| 315 | sampleCount); |
| 316 | av_frame_free(&frame); |
| 317 | if (result < 0) { |
| 318 | logError("avresample_convert", result); |
| 319 | return result; |
| 320 | } |
| 321 | int available = avresample_available(resampleContext); |
| 322 | if (available != 0) { |
| 323 | LOGE("Expected no samples remaining after resampling, but found %d.", |
| 324 | available); |
| 325 | return -1; |
| 326 | } |
| 327 | outputBuffer += bufferOutSize; |
| 328 | outSize += bufferOutSize; |
| 329 | } |
| 330 | return outSize; |
| 331 | } |
| 332 |
| 333 | void logError(const char *functionName, int errorNumber) { |
| 334 | char *buffer = (char *) malloc(ERROR_STRING_BUFFER_LENGTH * sizeof(char)); |
| 335 | av_strerror(errorNumber, buffer, ERROR_STRING_BUFFER_LENGTH); |
| 336 | LOGE("Error in %s: %s", functionName, buffer); |
| 337 | free(buffer); |
| 338 | } |
| 339 |
| 340 | void releaseContext(AVCodecContext *context) { |
| 341 | if (!context) { |
| 342 | return; |
| 343 | } |
| 344 | AVAudioResampleContext *resampleContext; |
| 345 | if ((resampleContext = (AVAudioResampleContext *) context->opaque)) { |
| 346 | avresample_free(&resampleContext); |
| 347 | context->opaque = NULL; |
| 348 | } |
| 349 | avcodec_free_context(&context); |
| 350 | } |
| 351 |
| 352 |