false, 'error' => 'Invalid or incomplete MP3 audio received.' ); while ( $offset < $size ) { if ( 'ID3' === substr( $content, $offset, 3 ) ) { if ( $size - $offset < 10 ) { return $bad; } $version = ord( $content[ $offset + 3 ] ); $flags = ord( $content[ $offset + 5 ] ); if ( ! in_array( $version, array( 2, 3, 4 ), true ) || 0xFF === ord( $content[ $offset + 4 ] ) ) { return $bad; } $length = 0; for ( $i = 6; $i < 10; ++$i ) { $part = ord( $content[ $offset + $i ] ); if ( $part & 0x80 ) { return $bad; } $length = ( $length << 7 ) | $part; } $footer = 4 === $version && ( $flags & 0x10 ) ? 10 : 0; if ( $offset + 10 + $length + $footer > $size ) { return $bad; } if ( $footer && '3DI' !== substr( $content, $offset + 10 + $length, 3 ) ) { return $bad; } $offset += 10 + $length + $footer; continue; } if ( 'TAG' === substr( $content, $offset, 3 ) ) { if ( $size - $offset < 128 || 0 === $frames ) { return $bad; } $offset += 128; continue; } if ( $size - $offset < 4 ) { return $bad; } $a = ord( $content[ $offset ] ); $b = ord( $content[ $offset + 1 ] ); $c = ord( $content[ $offset + 2 ] ); $version = ( $b >> 3 ) & 3; $layer = ( $b >> 1 ) & 3; $rate_index = ( $c >> 4 ) & 15; $sample_index = ( $c >> 2 ) & 3; if ( 0xFF !== $a || 0xE0 !== ( $b & 0xE0 ) || 1 === $version || 1 !== $layer || 0 === $rate_index || 15 === $rate_index || 3 === $sample_index ) { return $bad; } $rates = 3 === $version ? array( 0,32,40,48,56,64,80,96,112,128,160,192,224,256,320 ) : array( 0,8,16,24,32,40,48,56,64,80,96,112,128,144,160 ); $sample_rates = array( 44100, 48000, 32000 ); $sample_rate = $sample_rates[ $sample_index ] / ( 3 === $version ? 1 : ( 2 === $version ? 2 : 4 ) ); $length = (int) floor( ( 3 === $version ? 144000 : 72000 ) * $rates[ $rate_index ] / $sample_rate ) + ( ( $c >> 1 ) & 1 ); if ( $length < 4 || $offset + $length > $size ) { return $bad; } $offset += $length; ++$frames; $duration += ( 3 === $version ? 1152 : 576 ) / $sample_rate; } return $frames > 0 ? array( 'valid' => true, 'frames' => $frames, 'duration' => $duration ) : $bad; } public static function valid_mp3( string $content ): bool { return self::inspect_mp3( $content )['valid']; } /** Require actual frames even when an upstream server labels arbitrary bytes audio. */ public static function valid_mp3_response( array $response ): bool { $type = strtolower( trim( explode( ';', (string) ( $response['content_type'] ?? '' ) )[0] ) ); return ! empty( $response['success'] ) && in_array( $type, array( 'audio/mpeg', 'audio/mp3' ), true ) && isset( $response['body'] ) && is_string( $response['body'] ) && self::valid_mp3( $response['body'] ); } }