3737namespace android {
3838
3939// Everything must match except for
40- // protection, bitrate, padding, private bits, mode extension,
40+ // protection, bitrate, padding, private bits, mode, mode extension,
4141// copyright bit, original bit and emphasis.
4242// Yes ... there are things that must indeed match...
43- static const uint32_t kMask = 0xfffe0cc0 ;
43+ static const uint32_t kMask = 0xfffe0c00 ;
4444
4545static bool get_mp3_frame_size (
4646 uint32_t header, size_t *frame_size,
@@ -344,22 +344,55 @@ static bool Resync(
344344
345345 off_t pos = *inout_pos;
346346 bool valid = false ;
347+
348+ const size_t kMaxReadBytes = 1024 ;
349+ const off_t kMaxBytesChecked = 128 * 1024 ;
350+ uint8_t buf[kMaxReadBytes ];
351+ ssize_t bytesToRead = kMaxReadBytes ;
352+ ssize_t totalBytesRead = 0 ;
353+ ssize_t remainingBytes = 0 ;
354+ bool reachEOS = false ;
355+ uint8_t *tmp = buf;
356+
347357 do {
348- if (pos >= *inout_pos + 128 * 1024 ) {
358+ if (pos >= *inout_pos + kMaxBytesChecked ) {
349359 // Don't scan forever.
350360 LOGV (" giving up at offset %ld" , pos);
351361 break ;
352362 }
353363
354- uint8_t tmp[4 ];
355- if (source->readAt (pos, tmp, 4 ) != 4 ) {
356- break ;
364+ if (remainingBytes < 4 ) {
365+ if (reachEOS) {
366+ break ;
367+ } else {
368+ memcpy (buf, tmp, remainingBytes);
369+ bytesToRead = kMaxReadBytes - remainingBytes;
370+
371+ /*
372+ * The next read position should start from the end of
373+ * the last buffer, and thus should include the remaining
374+ * bytes in the buffer.
375+ */
376+ totalBytesRead = source->readAt (pos + remainingBytes,
377+ buf + remainingBytes,
378+ bytesToRead);
379+ if (totalBytesRead <= 0 ) {
380+ break ;
381+ }
382+ reachEOS = (totalBytesRead != bytesToRead);
383+ totalBytesRead += remainingBytes;
384+ remainingBytes = totalBytesRead;
385+ tmp = buf;
386+ continue ;
387+ }
357388 }
358389
359390 uint32_t header = U32_AT (tmp);
360391
361392 if (match_header != 0 && (header & kMask ) != (match_header & kMask )) {
362393 ++pos;
394+ ++tmp;
395+ --remainingBytes;
363396 continue ;
364397 }
365398
@@ -368,6 +401,8 @@ static bool Resync(
368401 if (!get_mp3_frame_size (header, &frame_size,
369402 &sample_rate, &num_channels, &bitrate)) {
370403 ++pos;
404+ ++tmp;
405+ --remainingBytes;
371406 continue ;
372407 }
373408
@@ -417,6 +452,8 @@ static bool Resync(
417452 }
418453
419454 ++pos;
455+ ++tmp;
456+ --remainingBytes;
420457 } while (!valid);
421458
422459 return valid;
0 commit comments