| 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 | #include "include/flac_parser.h" |
| 18 |
| 19 | #include <jni.h> |
| 20 |
| 21 | #include <android/log.h> |
| 22 |
| 23 | #include <cassert> |
| 24 | #include <cstdlib> |
| 25 | #include <cstring> |
| 26 |
| 27 | #define LOG_TAG "FLACParser" |
| 28 | #define ALOGE(...) \ |
| 29 | ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)) |
| 30 | #define ALOGV(...) \ |
| 31 | ((void)__android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) |
| 32 |
| 33 | #define LOG_ALWAYS_FATAL(...) \ |
| 34 | (__android_log_assert(NULL, LOG_TAG, ##__VA_ARGS__)) |
| 35 |
| 36 | #define LITERAL_TO_STRING_INTERNAL(x) #x |
| 37 | #define LITERAL_TO_STRING(x) LITERAL_TO_STRING_INTERNAL(x) |
| 38 |
| 39 | #define TRESPASS() \ |
| 40 | LOG_ALWAYS_FATAL(__FILE__ \ |
| 41 | ":" LITERAL_TO_STRING(__LINE__) " Should not be here."); |
| 42 | #define CHECK(x) \ |
| 43 | if (!(x)) ALOGE("Check failed: %s ", #x) |
| 44 |
| 45 | const int endian = 1; |
| 46 | #define isBigEndian() (*(reinterpret_cast<const char *>(&endian)) == 0) |
| 47 |
| 48 | // The FLAC parser calls our C++ static callbacks using C calling conventions, |
| 49 | // inside FLAC__stream_decoder_process_until_end_of_metadata |
| 50 | // and FLAC__stream_decoder_process_single. |
| 51 | // We immediately then call our corresponding C++ instance methods |
| 52 | // with the same parameter list, but discard redundant information. |
| 53 |
| 54 | FLAC__StreamDecoderReadStatus FLACParser::read_callback( |
| 55 | const FLAC__StreamDecoder * /* decoder */, FLAC__byte buffer[], |
| 56 | size_t *bytes, void *client_data) { |
| 57 | return reinterpret_cast<FLACParser *>(client_data) |
| 58 | ->readCallback(buffer, bytes); |
| 59 | } |
| 60 |
| 61 | FLAC__StreamDecoderSeekStatus FLACParser::seek_callback( |
| 62 | const FLAC__StreamDecoder * /* decoder */, |
| 63 | FLAC__uint64 absolute_byte_offset, void *client_data) { |
| 64 | return reinterpret_cast<FLACParser *>(client_data) |
| 65 | ->seekCallback(absolute_byte_offset); |
| 66 | } |
| 67 |
| 68 | FLAC__StreamDecoderTellStatus FLACParser::tell_callback( |
| 69 | const FLAC__StreamDecoder * /* decoder */, |
| 70 | FLAC__uint64 *absolute_byte_offset, void *client_data) { |
| 71 | return reinterpret_cast<FLACParser *>(client_data) |
| 72 | ->tellCallback(absolute_byte_offset); |
| 73 | } |
| 74 |
| 75 | FLAC__StreamDecoderLengthStatus FLACParser::length_callback( |
| 76 | const FLAC__StreamDecoder * /* decoder */, FLAC__uint64 *stream_length, |
| 77 | void *client_data) { |
| 78 | return reinterpret_cast<FLACParser *>(client_data) |
| 79 | ->lengthCallback(stream_length); |
| 80 | } |
| 81 |
| 82 | FLAC__bool FLACParser::eof_callback(const FLAC__StreamDecoder * /* decoder */, |
| 83 | void *client_data) { |
| 84 | return reinterpret_cast<FLACParser *>(client_data)->eofCallback(); |
| 85 | } |
| 86 |
| 87 | FLAC__StreamDecoderWriteStatus FLACParser::write_callback( |
| 88 | const FLAC__StreamDecoder * /* decoder */, const FLAC__Frame *frame, |
| 89 | const FLAC__int32 *const buffer[], void *client_data) { |
| 90 | return reinterpret_cast<FLACParser *>(client_data) |
| 91 | ->writeCallback(frame, buffer); |
| 92 | } |
| 93 |
| 94 | void FLACParser::metadata_callback(const FLAC__StreamDecoder * /* decoder */, |
| 95 | const FLAC__StreamMetadata *metadata, |
| 96 | void *client_data) { |
| 97 | reinterpret_cast<FLACParser *>(client_data)->metadataCallback(metadata); |
| 98 | } |
| 99 |
| 100 | void FLACParser::error_callback(const FLAC__StreamDecoder * /* decoder */, |
| 101 | FLAC__StreamDecoderErrorStatus status, |
| 102 | void *client_data) { |
| 103 | reinterpret_cast<FLACParser *>(client_data)->errorCallback(status); |
| 104 | } |
| 105 |
| 106 | // These are the corresponding callbacks with C++ calling conventions |
| 107 |
| 108 | FLAC__StreamDecoderReadStatus FLACParser::readCallback(FLAC__byte buffer[], |
| 109 | size_t *bytes) { |
| 110 | size_t requested = *bytes; |
| 111 | ssize_t actual = mDataSource->readAt(mCurrentPos, buffer, requested); |
| 112 | if (0 > actual) { |
| 113 | *bytes = 0; |
| 114 | return FLAC__STREAM_DECODER_READ_STATUS_ABORT; |
| 115 | } else if (0 == actual) { |
| 116 | *bytes = 0; |
| 117 | mEOF = true; |
| 118 | return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM; |
| 119 | } else { |
| 120 | assert(actual <= requested); |
| 121 | *bytes = actual; |
| 122 | mCurrentPos += actual; |
| 123 | return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE; |
| 124 | } |
| 125 | } |
| 126 |
| 127 | FLAC__StreamDecoderSeekStatus FLACParser::seekCallback( |
| 128 | FLAC__uint64 absolute_byte_offset) { |
| 129 | mCurrentPos = absolute_byte_offset; |
| 130 | mEOF = false; |
| 131 | return FLAC__STREAM_DECODER_SEEK_STATUS_OK; |
| 132 | } |
| 133 |
| 134 | FLAC__StreamDecoderTellStatus FLACParser::tellCallback( |
| 135 | FLAC__uint64 *absolute_byte_offset) { |
| 136 | *absolute_byte_offset = mCurrentPos; |
| 137 | return FLAC__STREAM_DECODER_TELL_STATUS_OK; |
| 138 | } |
| 139 |
| 140 | FLAC__StreamDecoderLengthStatus FLACParser::lengthCallback( |
| 141 | FLAC__uint64 *stream_length) { |
| 142 | return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED; |
| 143 | } |
| 144 |
| 145 | FLAC__bool FLACParser::eofCallback() { return mEOF; } |
| 146 |
| 147 | FLAC__StreamDecoderWriteStatus FLACParser::writeCallback( |
| 148 | const FLAC__Frame *frame, const FLAC__int32 *const buffer[]) { |
| 149 | if (mWriteRequested) { |
| 150 | mWriteRequested = false; |
| 151 | // FLAC parser doesn't free or realloc buffer until next frame or finish |
| 152 | mWriteHeader = frame->header; |
| 153 | mWriteBuffer = buffer; |
| 154 | mWriteCompleted = true; |
| 155 | return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; |
| 156 | } else { |
| 157 | ALOGE("FLACParser::writeCallback unexpected"); |
| 158 | return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; |
| 159 | } |
| 160 | } |
| 161 |
| 162 | void FLACParser::metadataCallback(const FLAC__StreamMetadata *metadata) { |
| 163 | switch (metadata->type) { |
| 164 | case FLAC__METADATA_TYPE_STREAMINFO: |
| 165 | if (!mStreamInfoValid) { |
| 166 | mStreamInfo = metadata->data.stream_info; |
| 167 | mStreamInfoValid = true; |
| 168 | } else { |
| 169 | ALOGE("FLACParser::metadataCallback unexpected STREAMINFO"); |
| 170 | } |
| 171 | break; |
| 172 | case FLAC__METADATA_TYPE_SEEKTABLE: |
| 173 | mSeekTable = &metadata->data.seek_table; |
| 174 | break; |
| 175 | default: |
| 176 | ALOGE("FLACParser::metadataCallback unexpected type %u", metadata->type); |
| 177 | break; |
| 178 | } |
| 179 | } |
| 180 |
| 181 | void FLACParser::errorCallback(FLAC__StreamDecoderErrorStatus status) { |
| 182 | ALOGE("FLACParser::errorCallback status=%d", status); |
| 183 | mErrorStatus = status; |
| 184 | } |
| 185 |
| 186 | // Copy samples from FLAC native 32-bit non-interleaved to |
| 187 | // correct bit-depth (non-zero padded), interleaved. |
| 188 | // These are candidates for optimization if needed. |
| 189 | static void copyToByteArrayBigEndian(int8_t *dst, const int *const *src, |
| 190 | unsigned bytesPerSample, unsigned nSamples, |
| 191 | unsigned nChannels) { |
| 192 | for (unsigned i = 0; i < nSamples; ++i) { |
| 193 | for (unsigned c = 0; c < nChannels; ++c) { |
| 194 | // point to the first byte of the source address |
| 195 | // and then skip the first few bytes (most significant bytes) |
| 196 | // depending on the bit depth |
| 197 | const int8_t *byteSrc = |
| 198 | reinterpret_cast<const int8_t *>(&src[c][i]) + 4 - bytesPerSample; |
| 199 | memcpy(dst, byteSrc, bytesPerSample); |
| 200 | dst = dst + bytesPerSample; |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 |
| 205 | static void copyToByteArrayLittleEndian(int8_t *dst, const int *const *src, |
| 206 | unsigned bytesPerSample, |
| 207 | unsigned nSamples, unsigned nChannels) { |
| 208 | for (unsigned i = 0; i < nSamples; ++i) { |
| 209 | for (unsigned c = 0; c < nChannels; ++c) { |
| 210 | // with little endian, the most significant bytes will be at the end |
| 211 | // copy the bytes in little endian will remove the most significant byte |
| 212 | // so we are good here. |
| 213 | memcpy(dst, &(src[c][i]), bytesPerSample); |
| 214 | dst = dst + bytesPerSample; |
| 215 | } |
| 216 | } |
| 217 | } |
| 218 |
| 219 | static void copyTrespass(int8_t * /* dst */, const int *const * /* src */, |
| 220 | unsigned /* bytesPerSample */, unsigned /* nSamples */, |
| 221 | unsigned /* nChannels */) { |
| 222 | TRESPASS(); |
| 223 | } |
| 224 |
| 225 | // FLACParser |
| 226 |
| 227 | FLACParser::FLACParser(DataSource *source) |
| 228 | : mDataSource(source), |
| 229 | mCopy(copyTrespass), |
| 230 | mDecoder(NULL), |
| 231 | mSeekTable(NULL), |
| 232 | firstFrameOffset(0LL), |
| 233 | mCurrentPos(0LL), |
| 234 | mEOF(false), |
| 235 | mStreamInfoValid(false), |
| 236 | mWriteRequested(false), |
| 237 | mWriteCompleted(false), |
| 238 | mWriteBuffer(NULL), |
| 239 | mErrorStatus((FLAC__StreamDecoderErrorStatus)-1) { |
| 240 | ALOGV("FLACParser::FLACParser"); |
| 241 | memset(&mStreamInfo, 0, sizeof(mStreamInfo)); |
| 242 | memset(&mWriteHeader, 0, sizeof(mWriteHeader)); |
| 243 | } |
| 244 |
| 245 | FLACParser::~FLACParser() { |
| 246 | ALOGV("FLACParser::~FLACParser"); |
| 247 | if (mDecoder != NULL) { |
| 248 | FLAC__stream_decoder_delete(mDecoder); |
| 249 | mDecoder = NULL; |
| 250 | } |
| 251 | } |
| 252 |
| 253 | bool FLACParser::init() { |
| 254 | // setup libFLAC parser |
| 255 | mDecoder = FLAC__stream_decoder_new(); |
| 256 | if (mDecoder == NULL) { |
| 257 | // The new should succeed, since probably all it does is a malloc |
| 258 | // that always succeeds in Android. But to avoid dependence on the |
| 259 | // libFLAC internals, we check and log here. |
| 260 | ALOGE("new failed"); |
| 261 | return false; |
| 262 | } |
| 263 | FLAC__stream_decoder_set_md5_checking(mDecoder, false); |
| 264 | FLAC__stream_decoder_set_metadata_ignore_all(mDecoder); |
| 265 | FLAC__stream_decoder_set_metadata_respond(mDecoder, |
| 266 | FLAC__METADATA_TYPE_STREAMINFO); |
| 267 | FLAC__stream_decoder_set_metadata_respond(mDecoder, |
| 268 | FLAC__METADATA_TYPE_SEEKTABLE); |
| 269 | FLAC__StreamDecoderInitStatus initStatus; |
| 270 | initStatus = FLAC__stream_decoder_init_stream( |
| 271 | mDecoder, read_callback, seek_callback, tell_callback, length_callback, |
| 272 | eof_callback, write_callback, metadata_callback, error_callback, |
| 273 | reinterpret_cast<void *>(this)); |
| 274 | if (initStatus != FLAC__STREAM_DECODER_INIT_STATUS_OK) { |
| 275 | // A failure here probably indicates a programming error and so is |
| 276 | // unlikely to happen. But we check and log here similarly to above. |
| 277 | ALOGE("init_stream failed %d", initStatus); |
| 278 | return false; |
| 279 | } |
| 280 | return true; |
| 281 | } |
| 282 |
| 283 | bool FLACParser::decodeMetadata() { |
| 284 | // parse all metadata |
| 285 | if (!FLAC__stream_decoder_process_until_end_of_metadata(mDecoder)) { |
| 286 | ALOGE("metadata decoding failed"); |
| 287 | return false; |
| 288 | } |
| 289 | // store first frame offset |
| 290 | FLAC__stream_decoder_get_decode_position(mDecoder, &firstFrameOffset); |
| 291 |
| 292 | if (mStreamInfoValid) { |
| 293 | // check channel count |
| 294 | if (getChannels() == 0 || getChannels() > 8) { |
| 295 | ALOGE("unsupported channel count %u", getChannels()); |
| 296 | return false; |
| 297 | } |
| 298 | // check bit depth |
| 299 | switch (getBitsPerSample()) { |
| 300 | case 8: |
| 301 | case 16: |
| 302 | case 24: |
| 303 | case 32: |
| 304 | break; |
| 305 | default: |
| 306 | ALOGE("unsupported bits per sample %u", getBitsPerSample()); |
| 307 | return false; |
| 308 | } |
| 309 | // check sample rate |
| 310 | switch (getSampleRate()) { |
| 311 | case 8000: |
| 312 | case 11025: |
| 313 | case 12000: |
| 314 | case 16000: |
| 315 | case 22050: |
| 316 | case 24000: |
| 317 | case 32000: |
| 318 | case 44100: |
| 319 | case 48000: |
| 320 | case 88200: |
| 321 | case 96000: |
| 322 | case 176400: |
| 323 | case 192000: |
| 324 | break; |
| 325 | default: |
| 326 | ALOGE("unsupported sample rate %u", getSampleRate()); |
| 327 | return false; |
| 328 | } |
| 329 | // configure the appropriate copy function based on device endianness. |
| 330 | if (isBigEndian()) { |
| 331 | mCopy = copyToByteArrayBigEndian; |
| 332 | } else { |
| 333 | mCopy = copyToByteArrayLittleEndian; |
| 334 | } |
| 335 | } else { |
| 336 | ALOGE("missing STREAMINFO"); |
| 337 | return false; |
| 338 | } |
| 339 | return true; |
| 340 | } |
| 341 |
| 342 | size_t FLACParser::readBuffer(void *output, size_t output_size) { |
| 343 | mWriteRequested = true; |
| 344 | mWriteCompleted = false; |
| 345 |
| 346 | if (!FLAC__stream_decoder_process_single(mDecoder)) { |
| 347 | ALOGE("FLACParser::readBuffer process_single failed. Status: %s", |
| 348 | getDecoderStateString()); |
| 349 | return -1; |
| 350 | } |
| 351 | if (!mWriteCompleted) { |
| 352 | if (FLAC__stream_decoder_get_state(mDecoder) != |
| 353 | FLAC__STREAM_DECODER_END_OF_STREAM) { |
| 354 | ALOGE("FLACParser::readBuffer write did not complete. Status: %s", |
| 355 | getDecoderStateString()); |
| 356 | } |
| 357 | return -1; |
| 358 | } |
| 359 |
| 360 | // verify that block header keeps the promises made by STREAMINFO |
| 361 | unsigned blocksize = mWriteHeader.blocksize; |
| 362 | if (blocksize == 0 || blocksize > getMaxBlockSize()) { |
| 363 | ALOGE("FLACParser::readBuffer write invalid blocksize %u", blocksize); |
| 364 | return -1; |
| 365 | } |
| 366 | if (mWriteHeader.sample_rate != getSampleRate() || |
| 367 | mWriteHeader.channels != getChannels() || |
| 368 | mWriteHeader.bits_per_sample != getBitsPerSample()) { |
| 369 | ALOGE( |
| 370 | "FLACParser::readBuffer write changed parameters mid-stream: %d/%d/%d " |
| 371 | "-> %d/%d/%d", |
| 372 | getSampleRate(), getChannels(), getBitsPerSample(), |
| 373 | mWriteHeader.sample_rate, mWriteHeader.channels, |
| 374 | mWriteHeader.bits_per_sample); |
| 375 | return -1; |
| 376 | } |
| 377 |
| 378 | unsigned bytesPerSample = getBitsPerSample() >> 3; |
| 379 | size_t bufferSize = blocksize * getChannels() * bytesPerSample; |
| 380 | if (bufferSize > output_size) { |
| 381 | ALOGE( |
| 382 | "FLACParser::readBuffer not enough space in output buffer " |
| 383 | "%zu < %zu", |
| 384 | output_size, bufferSize); |
| 385 | return -1; |
| 386 | } |
| 387 |
| 388 | // copy PCM from FLAC write buffer to our media buffer, with interleaving. |
| 389 | (*mCopy)(reinterpret_cast<int8_t *>(output), mWriteBuffer, bytesPerSample, |
| 390 | blocksize, getChannels()); |
| 391 |
| 392 | // fill in buffer metadata |
| 393 | CHECK(mWriteHeader.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER); |
| 394 |
| 395 | return bufferSize; |
| 396 | } |
| 397 |
| 398 | int64_t FLACParser::getSeekPosition(int64_t timeUs) { |
| 399 | if (!mSeekTable) { |
| 400 | return -1; |
| 401 | } |
| 402 |
| 403 | int64_t sample = (timeUs * getSampleRate()) / 1000000LL; |
| 404 | if (sample >= getTotalSamples()) { |
| 405 | sample = getTotalSamples(); |
| 406 | } |
| 407 |
| 408 | FLAC__StreamMetadata_SeekPoint* points = mSeekTable->points; |
| 409 | for (unsigned i = mSeekTable->num_points; i > 0; ) { |
| 410 | i--; |
| 411 | if (points[i].sample_number <= sample) { |
| 412 | return firstFrameOffset + points[i].stream_offset; |
| 413 | } |
| 414 | } |
| 415 | return firstFrameOffset; |
| 416 | } |
| 417 |