@@ -195,6 +195,7 @@ const spliceBuffer = (buffer, targetIndex, deleteCount, ...items) => {
195195
196196const restoreCorruptedMp3 = async ( filePath , debug ) => {
197197 let file = await readFile ( filePath ) ;
198+ let modifiedTit2BlockLastByteIndex = 0 ;
198199
199200 const hexString = file . toString ( 'hex' ) ;
200201 if ( hexString . slice ( 0 , 6 ) === '494433' ) {
@@ -207,12 +208,24 @@ const restoreCorruptedMp3 = async (filePath, debug) => {
207208 hexString . slice ( tit2Index + 8 , tit2Index + 16 ) ,
208209 16
209210 ) ;
210- const shiftJisTitle = file . slice (
211+ const rawTit2Title = file . slice (
211212 tit2Index / 2 + 11 ,
212213 tit2Index / 2 + 11 + tit2Size - 1
213214 ) ;
214- const decodedTitle = iconv . decode ( shiftJisTitle , 'SHIFT_JIS' ) ;
215+
216+ let encoding = 'SHIFT_JIS' ;
217+
218+ if (
219+ file . slice ( tit2Index / 2 + 10 , tit2Index / 2 + 11 ) . toString ( 'hex' ) ===
220+ '01'
221+ ) {
222+ console . log ( 'UTF-16 encoded tit2 found' ) ;
223+ encoding = 'utf-16' ;
224+ }
225+
226+ const decodedTitle = iconv . decode ( rawTit2Title , encoding ) ;
215227 const utf8Title = iconv . encode ( decodedTitle , 'utf-16' ) ;
228+
216229 file [ encodingByteIndex ] = 1 ;
217230 utf8Title . length
218231 . toString ( 16 )
@@ -226,18 +239,24 @@ const restoreCorruptedMp3 = async (filePath, debug) => {
226239 try {
227240 if ( tit2Size > 1024 ) throw Error ( 'TOO LARGE TIT2' ) ;
228241 file = spliceBuffer ( file , tit2Index / 2 + 11 , tit2Size , ...utf8Title ) ;
242+ modifiedTit2BlockLastByteIndex =
243+ tit2Index / 2 + 11 + utf8Title . length - tit2Size ;
229244 } catch ( err ) {
230245 console . log ( debug , tit2Index , tit2Size ) ;
231246 }
232247 }
233248 }
234249
235- let byteIndex = file . toString ( 'hex' ) . indexOf ( '7ffb' ) / 2 ;
250+ let byteIndex =
251+ file . toString ( 'hex' ) . indexOf ( '7ffb' , modifiedTit2BlockLastByteIndex * 2 ) /
252+ 2 ;
236253
237254 while ( byteIndex < file . byteLength ) {
238255 const header = file . slice ( byteIndex , byteIndex + 4 ) . toString ( 'hex' ) ;
239256 const binaryHeader = hexesToBin ( header ) ;
240257 if ( ! / ^ 7 f / . test ( header ) ) {
258+ console . log ( byteIndex ) ;
259+ console . log ( 'Wrong header' , header ) ;
241260 break ;
242261 }
243262 file [ byteIndex ] = 255 ;
0 commit comments