1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 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 17 //#define LOG_NDEBUG 0 18 #define LOG_TAG "FLACDecoder" 19 #include <utils/Log.h> 20 21 #include "FLACDecoder.h" 22 23 #include <media/stagefright/foundation/ADebug.h> 24 #include <media/stagefright/foundation/hexdump.h> 25 #include <media/stagefright/MediaDefs.h> 26 #include <media/stagefright/MediaErrors.h> 27 #include <media/stagefright/MetaData.h> 28 29 namespace android { 30 31 // These are the corresponding callbacks with C++ calling conventions 32 FLAC__StreamDecoderReadStatus FLACDecoder::readCallback( 33 FLAC__byte buffer[], size_t *bytes) { 34 if (mBuffer == nullptr || mBufferLen == 0) { 35 *bytes = 0; 36 return FLAC__STREAM_DECODER_READ_STATUS_ABORT; 37 } 38 39 size_t actual = *bytes; 40 if (actual > mBufferDataSize - mBufferPos) { 41 actual = mBufferDataSize - mBufferPos; 42 } 43 memcpy(buffer, mBuffer + mBufferPos, actual); 44 mBufferPos += actual; 45 *bytes = actual; 46 return (actual == 0 ? FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM 47 : FLAC__STREAM_DECODER_READ_STATUS_CONTINUE); 48 } 49 50 FLAC__StreamDecoderWriteStatus FLACDecoder::writeCallback( 51 const FLAC__Frame *frame, const FLAC__int32 * const buffer[]) 52 { 53 if (!mWriteRequested) { 54 ALOGE("writeCallback: unexpected"); 55 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; 56 } 57 58 mWriteRequested = false; 59 // FLAC decoder doesn't free or realloc buffer until next frame or finish 60 mWriteHeader = frame->header; 61 memmove(mWriteBuffer, buffer, sizeof(const FLAC__int32 * const) * getChannels()); 62 mWriteCompleted = true; 63 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; 64 } 65 66 void FLACDecoder::metadataCallback(const FLAC__StreamMetadata *metadata) 67 { 68 switch (metadata->type) { 69 case FLAC__METADATA_TYPE_STREAMINFO: 70 { 71 if (mStreamInfoValid) { 72 ALOGE("metadataCallback: unexpected STREAMINFO"); 73 } else { 74 mStreamInfo = metadata->data.stream_info; 75 mStreamInfoValid = true; 76 } 77 break; 78 } 79 80 /* TODO: enable metadata parsing below. 81 case FLAC__METADATA_TYPE_VORBIS_COMMENT: 82 { 83 const FLAC__StreamMetadata_VorbisComment *vc; 84 vc = &metadata->data.vorbis_comment; 85 for (FLAC__uint32 i = 0; i < vc->num_comments; ++i) { 86 FLAC__StreamMetadata_VorbisComment_Entry *vce; 87 vce = &vc->comments[i]; 88 if (mFileMetadata != 0 && vce->entry != NULL) { 89 parseVorbisComment(mFileMetadata, (const char *) vce->entry, 90 vce->length); 91 } 92 } 93 break; 94 } 95 96 case FLAC__METADATA_TYPE_PICTURE: 97 { 98 if (mFileMetadata != 0) { 99 const FLAC__StreamMetadata_Picture *p = &metadata->data.picture; 100 mFileMetadata->setData(kKeyAlbumArt, 101 MetaData::TYPE_NONE, p->data, p->data_length); 102 mFileMetadata->setCString(kKeyAlbumArtMIME, p->mime_type); 103 } 104 break; 105 } 106 */ 107 108 default: 109 ALOGW("metadataCallback: unexpected type %u", metadata->type); 110 break; 111 } 112 } 113 114 void FLACDecoder::errorCallback(FLAC__StreamDecoderErrorStatus status) 115 { 116 ALOGE("errorCallback: status=%d", status); 117 mErrorStatus = status; 118 } 119 120 // Copy samples from FLAC native 32-bit non-interleaved to 16-bit interleaved. 121 // These are candidates for optimization if needed. 122 static void copyMono8( 123 short *dst, 124 const int * src[FLACDecoder::kMaxChannels], 125 unsigned nSamples, 126 unsigned /* nChannels */) { 127 for (unsigned i = 0; i < nSamples; ++i) { 128 *dst++ = src[0][i] << 8; 129 } 130 } 131 132 static void copyStereo8( 133 short *dst, 134 const int * src[FLACDecoder::kMaxChannels], 135 unsigned nSamples, 136 unsigned /* nChannels */) { 137 for (unsigned i = 0; i < nSamples; ++i) { 138 *dst++ = src[0][i] << 8; 139 *dst++ = src[1][i] << 8; 140 } 141 } 142 143 static void copyMultiCh8( 144 short *dst, 145 const int * src[FLACDecoder::kMaxChannels], 146 unsigned nSamples, 147 unsigned nChannels) { 148 for (unsigned i = 0; i < nSamples; ++i) { 149 for (unsigned c = 0; c < nChannels; ++c) { 150 *dst++ = src[c][i] << 8; 151 } 152 } 153 } 154 155 static void copyMono16( 156 short *dst, 157 const int * src[FLACDecoder::kMaxChannels], 158 unsigned nSamples, 159 unsigned /* nChannels */) { 160 for (unsigned i = 0; i < nSamples; ++i) { 161 *dst++ = src[0][i]; 162 } 163 } 164 165 static void copyStereo16( 166 short *dst, 167 const int * src[FLACDecoder::kMaxChannels], 168 unsigned nSamples, 169 unsigned /* nChannels */) { 170 for (unsigned i = 0; i < nSamples; ++i) { 171 *dst++ = src[0][i]; 172 *dst++ = src[1][i]; 173 } 174 } 175 176 static void copyMultiCh16( 177 short *dst, 178 const int * src[FLACDecoder::kMaxChannels], 179 unsigned nSamples, 180 unsigned nChannels) { 181 for (unsigned i = 0; i < nSamples; ++i) { 182 for (unsigned c = 0; c < nChannels; ++c) { 183 *dst++ = src[c][i]; 184 } 185 } 186 } 187 188 // TODO: 24-bit versions should do dithering or noise-shaping, here or in AudioFlinger 189 static void copyMono24( 190 short *dst, 191 const int * src[FLACDecoder::kMaxChannels], 192 unsigned nSamples, 193 unsigned /* nChannels */) { 194 for (unsigned i = 0; i < nSamples; ++i) { 195 *dst++ = src[0][i] >> 8; 196 } 197 } 198 199 static void copyStereo24( 200 short *dst, 201 const int * src[FLACDecoder::kMaxChannels], 202 unsigned nSamples, 203 unsigned /* nChannels */) { 204 for (unsigned i = 0; i < nSamples; ++i) { 205 *dst++ = src[0][i] >> 8; 206 *dst++ = src[1][i] >> 8; 207 } 208 } 209 210 static void copyMultiCh24( 211 short *dst, 212 const int * src[FLACDecoder::kMaxChannels], 213 unsigned nSamples, 214 unsigned nChannels) { 215 for (unsigned i = 0; i < nSamples; ++i) { 216 for (unsigned c = 0; c < nChannels; ++c) { 217 *dst++ = src[c][i] >> 8; 218 } 219 } 220 } 221 222 // static 223 sp<FLACDecoder> FLACDecoder::Create() { 224 sp<FLACDecoder> decoder = new FLACDecoder(); 225 if (decoder->init() != OK) { 226 return NULL; 227 } 228 return decoder; 229 } 230 231 FLACDecoder::FLACDecoder() 232 : mDecoder(NULL), 233 mBuffer(NULL), 234 mBufferLen(0), 235 mBufferPos(0), 236 mBufferDataSize(0), 237 mStreamInfoValid(false), 238 mWriteRequested(false), 239 mWriteCompleted(false), 240 mErrorStatus((FLAC__StreamDecoderErrorStatus) -1), 241 mCopy(nullptr) { 242 ALOGV("ctor:"); 243 memset(&mStreamInfo, 0, sizeof(mStreamInfo)); 244 memset(&mWriteHeader, 0, sizeof(mWriteHeader)); 245 memset(&mWriteBuffer, 0, sizeof(mWriteBuffer)); 246 } 247 248 FLACDecoder::~FLACDecoder() { 249 ALOGV("dtor:"); 250 if (mDecoder != NULL) { 251 FLAC__stream_decoder_delete(mDecoder); 252 mDecoder = NULL; 253 } 254 if (mBuffer != NULL) { 255 free(mBuffer); 256 } 257 } 258 259 status_t FLACDecoder::init() { 260 ALOGV("init:"); 261 // setup libFLAC stream decoder 262 mDecoder = FLAC__stream_decoder_new(); 263 if (mDecoder == NULL) { 264 ALOGE("init: failed to create libFLAC stream decoder"); 265 return NO_INIT; 266 } 267 FLAC__stream_decoder_set_md5_checking(mDecoder, false); 268 FLAC__stream_decoder_set_metadata_ignore_all(mDecoder); 269 FLAC__stream_decoder_set_metadata_respond( 270 mDecoder, FLAC__METADATA_TYPE_STREAMINFO); 271 /* 272 FLAC__stream_decoder_set_metadata_respond( 273 mDecoder, FLAC__METADATA_TYPE_PICTURE); 274 FLAC__stream_decoder_set_metadata_respond( 275 mDecoder, FLAC__METADATA_TYPE_VORBIS_COMMENT); 276 */ 277 static auto read_callback = 278 [] (const FLAC__StreamDecoder * /* decoder */, 279 FLAC__byte buffer[], 280 size_t *bytes, 281 void *client_data) -> FLAC__StreamDecoderReadStatus { 282 return ((FLACDecoder *) client_data)->readCallback(buffer, bytes); }; 283 284 static auto write_callback = 285 [] (const FLAC__StreamDecoder * /* decoder */, 286 const FLAC__Frame *frame, 287 const FLAC__int32 * const buffer[], 288 void *client_data) -> FLAC__StreamDecoderWriteStatus { 289 return ((FLACDecoder *) client_data)->writeCallback(frame, buffer); }; 290 291 static auto metadata_callback = 292 [] (const FLAC__StreamDecoder * /* decoder */, 293 const FLAC__StreamMetadata *metadata, 294 void *client_data) { 295 ((FLACDecoder *) client_data)->metadataCallback(metadata); }; 296 297 static auto error_callback = 298 [] (const FLAC__StreamDecoder * /* decoder */, 299 FLAC__StreamDecoderErrorStatus status, 300 void *client_data) { 301 ((FLACDecoder *) client_data)->errorCallback(status); }; 302 303 FLAC__StreamDecoderInitStatus initStatus = 304 FLAC__stream_decoder_init_stream( 305 mDecoder, 306 read_callback, 307 NULL /* seek_callback */, 308 NULL /* tell_callback */, 309 NULL /* length_callback */, 310 NULL /* eof_callback */, 311 write_callback, 312 metadata_callback, 313 error_callback, 314 (void *)this); 315 if (initStatus != FLAC__STREAM_DECODER_INIT_STATUS_OK) { 316 ALOGE("init: init_stream failed, returned %d", initStatus); 317 return NO_INIT; 318 } 319 return OK; 320 } 321 322 void FLACDecoder::flush() { 323 ALOGV("flush:"); 324 mBufferPos = 0; 325 mBufferDataSize = 0; 326 mStreamInfoValid = false; 327 if (!FLAC__stream_decoder_reset(mDecoder)) { 328 ALOGE("flush: failed to reset FLAC stream decoder"); 329 } 330 } 331 332 status_t FLACDecoder::parseMetadata(const uint8_t *inBuffer, size_t inBufferLen) { 333 ALOGV("parseMetadata: input size(%zu)", inBufferLen); 334 //hexdump(inBuffer, inBufferLen); 335 336 if (mStreamInfoValid) { 337 ALOGE("parseMetadata: already have full metadata blocks"); 338 return ERROR_MALFORMED; 339 } 340 341 status_t err = addDataToBuffer(inBuffer, inBufferLen); 342 if (err != OK) { 343 ALOGE("parseMetadata: addDataToBuffer returns error %d", err); 344 return err; 345 } 346 347 if (!FLAC__stream_decoder_process_until_end_of_metadata(mDecoder)) { 348 if (!FLAC__stream_decoder_reset(mDecoder)) { 349 ALOGE("parseMetadata: failed to reset FLAC stream decoder"); 350 return FAILED_TRANSACTION; 351 } 352 mBufferPos = 0; 353 ALOGV("parseMetadata: do not have full metadata blocks yet"); 354 return WOULD_BLOCK; 355 } 356 357 if (!mStreamInfoValid) { 358 ALOGE("parseMetadata: missing STREAMINFO"); 359 return ERROR_MALFORMED; 360 } 361 362 // check block size 363 if (getMaxBlockSize() == 0) { 364 ALOGE("wrong max blocksize %u", getMaxBlockSize()); 365 mStreamInfoValid = false; 366 return ERROR_MALFORMED; 367 } 368 369 // check channel count 370 if (getChannels() == 0 || getChannels() > kMaxChannels) { 371 ALOGE("unsupported channel count %u", getChannels()); 372 mStreamInfoValid = false; 373 return ERROR_MALFORMED; 374 } 375 376 // check bit depth 377 switch (getBitsPerSample()) { 378 case 8: 379 case 16: 380 case 24: 381 break; 382 383 default: 384 ALOGE("parseMetadata: unsupported bits per sample %u", getBitsPerSample()); 385 mStreamInfoValid = false; 386 return ERROR_MALFORMED; 387 } 388 389 // configure the appropriate copy function, defaulting to trespass 390 static const struct { 391 unsigned mChannels; 392 unsigned mBitsPerSample; 393 void (*mCopy)(short *dst, const int * src[kMaxChannels], 394 unsigned nSamples, unsigned nChannels); 395 } table[] = { 396 { 1, 8, copyMono8 }, 397 { 2, 8, copyStereo8 }, 398 { 8, 8, copyMultiCh8 }, 399 { 1, 16, copyMono16 }, 400 { 2, 16, copyStereo16 }, 401 { 8, 16, copyMultiCh16 }, 402 { 1, 24, copyMono24 }, 403 { 2, 24, copyStereo24 }, 404 { 8, 24, copyMultiCh24 }, 405 }; 406 for (const auto &entry : table) { 407 if (entry.mChannels >= getChannels() && 408 entry.mBitsPerSample == getBitsPerSample()) { 409 mCopy = entry.mCopy; 410 break; 411 } 412 } 413 414 // Now we have all metadata blocks. 415 mBufferPos = 0; 416 mBufferDataSize = 0; 417 418 return OK; 419 } 420 421 status_t FLACDecoder::decodeOneFrame(const uint8_t *inBuffer, size_t inBufferLen, 422 short *outBuffer, size_t *outBufferLen) { 423 ALOGV("decodeOneFrame: input size(%zu)", inBufferLen); 424 425 if (inBufferLen == 0) { 426 ALOGV("decodeOneFrame: no input data"); 427 if (outBufferLen) { 428 *outBufferLen = 0; 429 } 430 return OK; 431 } 432 433 if (!mStreamInfoValid) { 434 ALOGW("decodeOneFrame: no streaminfo metadata block"); 435 } 436 437 status_t err = addDataToBuffer(inBuffer, inBufferLen); 438 if (err != OK) { 439 ALOGW("decodeOneFrame: addDataToBuffer returns error %d", err); 440 return err; 441 } 442 443 mWriteRequested = true; 444 mWriteCompleted = false; 445 if (!FLAC__stream_decoder_process_single(mDecoder)) { 446 ALOGE("decodeOneFrame: process_single failed"); 447 return ERROR_MALFORMED; 448 } 449 if (!mWriteCompleted) { 450 ALOGV("decodeOneFrame: write did not complete"); 451 if (outBufferLen) { 452 *outBufferLen = 0; 453 } 454 return OK; 455 } 456 457 // frame header should be consistent with STREAMINFO 458 unsigned blocksize = mWriteHeader.blocksize; 459 if (blocksize == 0 || blocksize > getMaxBlockSize()) { 460 ALOGE("decodeOneFrame: write invalid blocksize %u", blocksize); 461 return ERROR_MALFORMED; 462 } 463 if (mWriteHeader.sample_rate != getSampleRate() || 464 mWriteHeader.channels != getChannels() || 465 mWriteHeader.bits_per_sample != getBitsPerSample()) { 466 ALOGE("decodeOneFrame: parameters are changed mid-stream: %d/%d/%d -> %d/%d/%d", 467 getSampleRate(), getChannels(), getBitsPerSample(), 468 mWriteHeader.sample_rate, mWriteHeader.channels, mWriteHeader.bits_per_sample); 469 return ERROR_MALFORMED; 470 } 471 if (mWriteHeader.number_type != FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER) { 472 ALOGE("decodeOneFrame: number type is %d, expected %d", 473 mWriteHeader.number_type, FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER); 474 return ERROR_MALFORMED; 475 } 476 477 size_t bufferSize = blocksize * getChannels() * sizeof(short); 478 if (bufferSize > *outBufferLen) { 479 ALOGW("decodeOneFrame: output buffer holds only partial frame %zu:%zu", 480 *outBufferLen, bufferSize); 481 blocksize = *outBufferLen / (getChannels() * sizeof(short)); 482 bufferSize = blocksize * getChannels() * sizeof(short); 483 } 484 485 if (mCopy == nullptr) { 486 ALOGE("decodeOneFrame: format is not supported: channels(%d), BitsPerSample(%d)", 487 getChannels(), getBitsPerSample()); 488 return ERROR_UNSUPPORTED; 489 } 490 // copy PCM from FLAC write buffer to output buffer, with interleaving 491 (*mCopy)(outBuffer, mWriteBuffer, blocksize, getChannels()); 492 *outBufferLen = bufferSize; 493 return OK; 494 } 495 496 status_t FLACDecoder::addDataToBuffer(const uint8_t *inBuffer, size_t inBufferLen) { 497 // mBufferPos should be no larger than mBufferDataSize 498 if (inBufferLen > SIZE_MAX - (mBufferDataSize - mBufferPos)) { 499 ALOGE("addDataToBuffer: input buffer is too large"); 500 return ERROR_MALFORMED; 501 } 502 503 if (inBufferLen > mBufferLen - mBufferDataSize) { 504 if (mBufferPos > 0) { 505 memmove(mBuffer, mBuffer + mBufferPos, mBufferDataSize - mBufferPos); 506 mBufferDataSize -= mBufferPos; 507 mBufferPos = 0; 508 } 509 if (inBufferLen > mBufferLen - mBufferDataSize) { 510 mBuffer = (uint8_t*)realloc(mBuffer, mBufferDataSize + inBufferLen); 511 if (mBuffer == nullptr) { 512 mBufferDataSize = 0; 513 mBufferLen = 0; 514 ALOGE("decodeOneFrame: failed to allocate memory for input buffer"); 515 return NO_MEMORY; 516 } 517 mBufferLen = mBufferDataSize + inBufferLen; 518 } 519 } 520 521 memcpy(mBuffer + mBufferDataSize, inBuffer, inBufferLen); 522 mBufferDataSize += inBufferLen; 523 return OK; 524 } 525 526 } // namespace android 527