import { demux_packet } from "./packet" ; import { PMT } from "./pmt" ; import { ContentTypes , Packet , Stream , StreamTypes } from "./stream" ; import { ErrCodes , PACKET_LEN , SYNC_BYTE } from "./util" ; export { Packet , Stream , StreamTypes , ContentTypes , PACKET_LEN , ErrCodes } ; export type DemuxOptions = { copy ? : boolean ; } ; export class TSDemuxer { private pmt = new PMT ( ) ; private leftover = new Uint8Array ( PACKET_LEN ) ; private lview = new DataView ( this . leftover . buffer ) ; private ptr = 0 ; private copy : boolean ; public offset = 0 ; public readonly pids = new Map < number , Stream > ( ) ; constructor ( private cb , opts ? ) { this . copy = ! ! ( opts ?. copy ) ; } static resync ( buffer , offset = 0 ) { const l = buffer . length ; for ( ; offset < l ; offset ++ ) { if ( buffer [ offset ] === SYNC_BYTE ) { return offset ; } } return - 1 ; } process ( buffer , offset = 0 , len = buffer . length - offset ) { const { pmt , pids , cb , copy } = this ; const remainder = ( PACKET_LEN - this . ptr ) % PACKET_LEN ; if ( remainder > 0 ) { if ( len < remainder ) { this . leftover . set ( buffer . subarray ( offset , offset + len ) , this . ptr ) ; this . ptr += len ; this . offset = 0 ; return 1 ; } this . leftover . set ( buffer . subarray ( offset , offset + remainder ) , this . ptr ) ; this . ptr = 0 ; this . offset = offset ; const n = demux_packet ( pmt , this . lview , 0 , pids , cb , true ) ; if ( n ) { return n ; } } len += offset ; offset += remainder ; this . offset = 0 ; const mem = new DataView ( buffer . buffer , buffer . byteOffset ) ; for ( let ptr = offset ; ; ptr += PACKET_LEN ) { const datalen = len - ptr ; this . ptr = datalen ; if ( datalen === 0 ) { return 0 ; } if ( datalen < PACKET_LEN ) { this . leftover . set ( buffer . subarray ( ptr , ptr + datalen ) ) ; return 1 ; } const n = demux_packet ( pmt , mem , ptr , pids , cb , copy ) ; if ( n ) { this . ptr = 0 ; this . offset = ptr ; return n ; } } } finalize ( ) { const { pids , cb } = this ; for ( const s of pids . values ( ) ) { const packet = s . finalize ( ) ; if ( packet ) { cb ( packet ) ; } } } }