import { Readable } from 'node:stream' ; import prism from 'prism-media' ; import { noop } from './util' ; import { StreamType } from '..' ; param opusHead returns export function validateDiscordOpusHead ( opusHead ) { const channels = opusHead . readUInt8 ( 9 ) ; const sampleRate = opusHead . readUInt32LE ( 12 ) ; return channels === 2 && sampleRate === 48000 ; } /**
 * The resulting information after probing an audio stream
 */ export interface ProbeInfo { /**
     * The readable audio stream to use. You should use this rather than the input stream, as the probing
     * function can sometimes read the input stream to its end and cause the stream to close.
     */ stream : Readable ; /**
     * The recommended stream type for this audio stream.
     */ type : StreamType ; } param stream param probeSize param validator experimental export function demuxProbe ( stream , probeSize = 1024 , validator = validateDiscordOpusHead ) { return new Promise ( ( resolve , reject ) => { if ( stream . readableObjectMode ) reject ( new Error ( 'Cannot probe a readable stream in object mode' ) ) ; if ( stream . readableEnded ) reject ( new Error ( 'Cannot probe a stream that has ended' ) ) ; let readBuffer = Buffer . alloc ( 0 ) ; let resolved = undefined ; const finish = ( type ) => { stream . off ( 'data' , onData ) ; stream . off ( 'close' , onClose ) ; stream . off ( 'end' , onClose ) ; stream . pause ( ) ; resolved = type ; if ( stream . readableEnded ) { resolve ( { stream : Readable . from ( readBuffer ) , type , } ) ; } else { if ( readBuffer . length > 0 ) { stream . push ( readBuffer ) ; } resolve ( { stream , type , } ) ; } } ; const foundHead = ( type ) => ( head ) => { if ( validator ( head ) ) { finish ( type ) ; } } ; const webm = new prism . opus . WebmDemuxer ( ) ; webm . once ( 'error' , noop ) ; webm . on ( 'head' , foundHead ( StreamType . WebmOpus ) ) ; const ogg = new prism . opus . OggDemuxer ( ) ; ogg . once ( 'error' , noop ) ; ogg . on ( 'head' , foundHead ( StreamType . OggOpus ) ) ; const onClose = ( ) => { if ( ! resolved ) { finish ( StreamType . Arbitrary ) ; } } ; const onData = ( buffer ) => { readBuffer = Buffer . concat ( [ readBuffer , buffer ] ) ; webm . write ( buffer ) ; ogg . write ( buffer ) ; if ( readBuffer . length >= probeSize ) { stream . off ( 'data' , onData ) ; stream . pause ( ) ; process . nextTick ( onClose ) ; } } ; stream . once ( 'error' , reject ) ; stream . on ( 'data' , onData ) ; stream . once ( 'close' , onClose ) ; stream . once ( 'end' , onClose ) ; } ) ; }