Giter VIP home page Giter VIP logo

prism-media's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

prism-media's Issues

Docs page is not working, returned 404

Issue:

Docs page returned 404

Steps to reproduce:

Simple, go to docs page

Further details:

  • Operating System: N/A
  • Node.js version: N/A
  • Commit I'm using: N/A

Example of how to read an opus file and get packets?

I cannot get how can I get the packets from an opus file.
I need them one by one.
Also I need some meta data from the decoder like:

  • frames per second
  • packet duration
  • sample rate

So I start with:

const prism = require('prism-media');
const fs = require('fs');

fs.createReadStream('../32k.opus')
    .pipe(new prism.opus.OggDemuxer())

But then - what and how?

Thanks in advance.

Docs link on NPM leads to 404 page

Issue:

The "Documentation" link on NPM leads to a 404 error page.

The link that's currently on there is: https://hydrabolt.me/prism-media
It should be: https://amishshah.github.io/prism-media/

Also, the link to the Prism website on your website, https://hydrabolt.me, needs to be updated.

Or make https://hydrabolt.me/prism-media redirect to https://amishshah.github.io/prism-media/ to make it a bit less confusing for new users :)

Steps to reproduce:

  1. Click the documentation link in the README on NPM
    or
  2. Go to https://hydrabolt.me

Further details:

  • Operating System: N/A
  • Node.js version: N/A
  • Commit I'm using: v1.3.1 as posted on NPM

EDIT: Documentation link on README at https://amishshah.github.io/prism-media/ is also broken.

Error when installing prism-media

Issue:

I'm not being able to install prism-media as it returns the following error:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: @discordjs/[email protected]
npm ERR! node_modules/@discordjs/opus
npm ERR!   @discordjs/opus@"^0.6.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peerOptional @discordjs/opus@"^0.5.0" from [email protected]
npm ERR! node_modules/prism-media
npm ERR!   prism-media@"*" from the root project
npm ERR!   prism-media@"^1.3.1" from @discordjs/[email protected]
npm ERR!   node_modules/@discordjs/voice
npm ERR!     @discordjs/voice@"^0.6.0" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: @discordjs/[email protected]
npm ERR! node_modules/@discordjs/opus
npm ERR!   peerOptional @discordjs/opus@"^0.5.0" from [email protected]
npm ERR!   node_modules/prism-media
npm ERR!     prism-media@"*" from the root project
npm ERR!     node_modules/@discordjs/voice
npm ERR!       @discordjs/voice@"^0.6.0" from the root project

Steps to reproduce:

npm install prism-media

Further details:

  • Operating System: Windows 10
  • Node.js version: 16.8.0

ffmpeg window discord bot

Issue:

Hello, i don't speak English very well, i hope you understand me.
When i run my discord bot with pm2 on windows, a window with ffmpeg pops up and only disappears when the song ends.

Adding { windowsHide: true } in ChildProcess.spawn inside FfmpegProcess.js and Ffmpeg.js
this.process = ChildProcess.spawn(ffmpegTranscoder.command, options.ffmpegArguments, { windowsHide: true });
if (!ChildProcess.spawnSync(command, ['-h'], { windowsHide: true }).error) return command;
stopped appearing the ffmpeg window.

Steps to reproduce:

npm i -g pm2
npm i discord.js opusscript ytdl-core
pm2 start index.js
index.js can be this example
++play
image

Further details:

  • Operating System: Windows 10 (10.0.17763.737)
  • Node.js version: v10.16.3
  • Commit I'm using:

write EPIPE error for certain arguments

Issue:

Hey Amish - appreciate all the work on this!

I'm using discord-ytdl-core to effectively trim a youtube clip with a start & end time (-ss / -to flags in FFmpeg).

Some flags work okay, but those two together consistently throws a write EPIPE error, which I can't handle gracefully. Seems like an error with the readable stream upon after the ffmpeg process.

Wondering if you know what this might be?

Steps to reproduce:

Originally opened an issue in the above mentioned repo but apparently is happening directly with prism-media.

Code snippet inside this issue:
twlite/discord-ytdl-core#20

Further details:

  • Operating System: OSX 10.13.6
  • Node.js version: 14.15.5
  • FFmpeg version: 4.0.2
  • prism-media version (in node modules): 1.2.8
  • @discordjs/opus version (node modules): 0.4.0

prism-media/src/transcoders/ffmpeg/Ff

Hi there,
my BOT gives me the following error.

at new VoiceConnection (/root/Musik/node_modules/discord.js/src/client/voice/VoiceConnection.js:46:18)
at Promise (/root/Musik/node_modules/discord.js/src/client/voice/ClientVoiceManager.js:63:22)
at new Promise ()
at ClientVoiceManager.joinChannel (/root/Musik/node_modules/discord.js/src/client/voice/ClientVoiceManager.js:45:12)
at VoiceChannel.join (/root/Musik/node_modules/discord.js/src/structures/VoiceChannel.js:130:30)
at Object.module.exports.addToQueue (/root/Musik/tools.js:93:51)
at search (/root/Musik/commands/play.js:148:27)
at /root/Musik/node_modules/youtube-search/index.js:106:14 process._tickCallback (internal/process/next_tick.js:68:7)

best regards

TypeError: failed to downcast any to number

Issue:

I was trying to use prism-media to be able to record the discord.js call using discord.js and when I use prism.opus.OggLogicalBitstream I get an error

Steps to reproduce:

My code:

const opusStream = connection.receiver.subscribe(userReciver, {
            end: {
                behavior: EndBehaviorType.Manual
            },
        });
        const oggWriter = new prism.opus.OggLogicalBitstream({
            opusHead: new prism.opus.OpusHead({
                channelCount: 2,
                sampleRate: 48000,
            }),
            pageSizeControl: {
                maxPackets: Number(10),
            }
        });
        pipeline(oggWriter, opusStream, createWriteStream(`./records/${message.guild.id}/record.ogg`), (err) => {
            if (err) {
                console.warn(`โŒ Error recording file record.ogg - ${err.message}`);
            } else {
                console.log(`โœ… Recorded record.ogg`);
            }
        });

Further details:

  • Operating System: Windows 10
  • Node.js version: 18.0.0
  • Commit I'm using: "prism-media": "^2.0.0-alpha.0",

Make FFmpeg codec info available

After running tests, it was found that the audio preparation process for Discord.js could be sped up by around 10% by encoding the audio with Opus directly in FFmpeg. To facilitate this, prism-media will need to show the available codecs in FFmpeg.

Update of dependent package "@discordjs/opus"

Issue:

It uses the dependency package "ansi-regex" (GHSA-93q8-gq69-wqmw),
which is vulnerable due to an outdated version of the dependency package "@discordjs/opus".
The version of the dependent package "@discordjs/opus" needs to be updated.

# npm audit report

ansi-regex  >2.1.1 <5.0.1
Severity: moderate
 Inefficient Regular Expression Complexity in chalk/ansi-regex - https://github.com/advisories/GHSA-93q8-gq69-wqmw
fix available via `npm audit fix`
node_modules/ansi-regex
  strip-ansi  4.0.0 - 5.2.0
  Depends on vulnerable versions of ansi-regex
  node_modules/strip-ansi
    string-width  2.1.0 - 4.1.0
    Depends on vulnerable versions of strip-ansi
    node_modules/string-width
`-- @discordjs/opus@0.5.3
  `-- @discordjs/node-pre-gyp@0.4.2
    `-- npmlog@5.0.1
      `-- gauge@3.0.1
        `-- strip-ansi@4.0.0
          `-- ansi-regex@3.0.0

Further details:

Could not find an Opus module! Please install node-opus or opusscript

Issue:

I have installed opusscript, but still it shows Could not find an Opus module! Please install node-opus or opusscript. I am using this on a discord bot. First it works fine. No error is there, then after sometime, this error starts arising even though opusscript is installed. Then when i restart the bot, it starts working again. Then after sometime the same thing happens again.

Further details:

  • Operating System: Linux
  • Node.js version: 10.x
  • Commit I'm using: prism-media-1.1.0

Edit: My opusscript version is 0.0.7, is that supposed to be the cause of problem.

The value of "sourceEnd" is out of range error in 2.0.0-alpha.0

Issue:

RangeError [ERR_OUT_OF_RANGE]: The value of "sourceEnd" is out of range. It must be >= 0 && <= 3. Received 8 
  at validateOffset (node:buffer:113:3)
  at Buffer.compare (node:buffer:895:5) 
  at Decoder._transform (/Users/tony/Projects/aoede-bot/node_modules/prism-media/src/opus/Decoder.ts:23:13)
  ...

I get the aforementioned error when working with opus.Decoder from prism-media version 2.0.0-alpha.0. It originates there at chunk.compare call. I guess it is because of a small chunk with a length of 3. Any ideas how to fix?

Steps to reproduce:

const listenStream = connection.receiver.subscribe(userId, {
  end: {
    behavior: EndBehaviorType.AfterSilence,
    duration: 1000,
  },
})

const opusDecoder = new prism.opus.Decoder({
  frameSize: 960,
  channels: 1,
  rate: 48000,
})

inputStream.pipe(opusDecoder)

Further details:

  • Operating System: MacOS 11.5.2
  • Node.js version: 16.14.2
  • Commit I'm using: 2.0.0-alpha.0

`read()` returning `null`

Issue:

The .read() method on an FFmpeg transcoder only returns null.

For my use case I need to control the size of the Buffer that I'm sending out (<=320b), as well as the timing (every ~20ms), so I'm doing a transcoder.read(<size>) but it only every returns a null value. Furthermore, the transcoder.readableLength never changes from 0.

Steps to reproduce:

Create a short wav file. In my case I encoded it as pcm_s16le named mywav.wav and place it in the same directory as this code.

Run the code with node <name of file containing the code>.

const fs = require('fs');
const prism = require('prism-media');

// mywav.wav is encoded as pcm_s16le.
const input = fs.createReadStream('./mywav.wav');

// Just changing the encoding to pcm_s8.
const transcoder = new prism.FFmpeg({
  args: [
    '-loglevel', '0',
    '-analyzeduration', '0',
    '-acodec', 'pcm_s8',
    '-f', 'wav',
  ],
  highWaterMark: input.highWaterMark,
});

let status = true;
transcoder.on('drain', () => {
  console.log('drain event fired');
  status = true;
});

// More control is desired over size of outputChunk, so using
// the `.read` and `.write` methods on the `transcoder`.
setInterval(() => {
  let inputChunk;
  let outputChunk;

  if (input.readable && status) {
    inputChunk = input.read();
    console.log('inputChunk: ', inputChunk);
  }

  if (inputChunk && transcoder.writable && status) {
    status = transcoder.write(inputChunk);
    console.log('transcoder.write status: ', status);
  }

  if (transcoder.readable) {
    console.log('transcoder.readableLength: ', transcoder.readableLength);
    outputChunk = transcoder.read(320);
    console.log('outputChunk: ', outputChunk);
  }
}, 20);

Further details:

  • Operating System: MacOS Mojave (10.14.3)
  • Node.js version: v10.15.3
  • Commit I'm using: commit installed by npm install [email protected].

RangeError: Source is too large

Issue:

I had this issue when I use with discord.js v12.

0|index  | RangeError: Source is too large
0|index  |     at Uint16Array.set (<anonymous>)
0|index  |     at OpusScript.encode (C:\Users\com\Desktop\build\node_modules\opusscript\index.js:51:16)
0|index  |     at Encoder._encode (C:\Users\com\Desktop\build\node_modules\prism-media\src\opus\Opus.js:54:25)
0|index  |     at Encoder._transform (C:\Users\com\Desktop\build\node_modules\prism-media\src\opus\Opus.js:137:30)
0|index  |     at Encoder.Transform._read (_stream_transform.js:190:10)
0|index  |     at Encoder.Transform._write (_stream_transform.js:178:12)
0|index  |     at doWrite (_stream_writable.js:410:12)
0|index  |     at writeOrBuffer (_stream_writable.js:394:5)
0|index  |     at Encoder.Writable.write (_stream_writable.js:294:11)
0|index  |     at VolumeTransformer.ondata (_stream_readable.js:689:20)
0|index  |     at VolumeTransformer.emit (events.js:189:13)
0|index  |     at VolumeTransformer.EventEmitter.emit (domain.js:459:23)
0|index  |     at addChunk (_stream_readable.js:284:12)
0|index  |     at readableAddChunk (_stream_readable.js:265:11)
0|index  |     at VolumeTransformer.Readable.push (_stream_readable.js:220:10)
0|index  |     at VolumeTransformer.Transform.push (_stream_transform.js:151:32)

Steps to reproduce:

I think it happens when repeat requests with short interval is happened.

Further details:

  • Operating System: macOS 10.14.3 (Happens in mac, windows)
  • Node.js version: v10.15.3
  • Commit I'm using:

Thank you. Always appreciate your work.

FFMPEG streams still prematurely closing on Windows

Issue:

FFMPEG streams still prematurely closing on Windows.

Steps to reproduce:

Created an opus stream, which instantly closes after initialization. I have made no changes to my code, except for jumping from prism-media 1.2.4 to 1.2.7.

Further details:

  • Operating System: Windows 10 build 20H2
  • Node.js version: 14.15.0
  • Commit I'm using: 1.2.7 (361cb91)
  • FFMPEG version: 4.3.1 (Using ffmpeg-static version 4.2.7)

`end` event fired without any Output & error

Issue:

end event fired without any input & error. (In Yonle/openradio#4)

Steps to reproduce:

  1. Make sure you have a .m4a files that has their metadata (Like Artist, Album, Thumbnail or etc)
  2. Do this:
// ffmpeg is from prism-media. I replace it with some variable as well.
require('fs').createReadStream("aacfiles.m4a").pipe(new ffmpeg({
                args: ["-analyzeduration", "0", "-loglevel", "0", "-f", "mp3", "-ar", "48000", "-ac", "2", "-ab", "192k", "-map", "0:a", "-map_metadata", "-1"]
})).pipe(require("fs").createWriteStream("output.mp3"));

Expected behavior

No output.

When i test it in bash, It works well:
Screenshot_2021_0504_121236

Further details:

  • Operating System: Android 8.1
  • Node.js version: v14.15.4
  • Commit I'm using: -

Add an example for uses in discord.js

It'd be nice if there was some more examples, especially around discord.js/voice since that's what I'm currently working with, and the current example code states that it can be used in discord.js however, it never states what method is to be used.

Update peer dependency for @discordjs/opus

Issue:

When writing a discord bot using discord.js and @discordjs/opus, the npm install command fails since it can't satisfy the prism-media peer dependency for @discordjs/opus when using "@discordjs/opus": "0.3.3" in package.json

Steps to reproduce:

Add "discord.js": "^12.4.1" and "@discordjs/opus": "0.3.3" to package.json and run npm i.

Further details:

  • Operating System: Ubuntu
  • Node.js version: 15.2.1
  • prism-media requirement: ^1.2.2 from discord.js version ^12.4.1

Transcoder end event not firing

const Prism = require('prism-media')
const prism = new Prism();

const start = Date.now();
const transcoder = prism.transcode({
  type: 'ffmpeg',
  media: require('ytdl-core')('https://www.youtube.com/watch?v=3Ktn6r02dEo', { filter: 'audioonly' }),
  ffmpegArguments: [
    '-analyzeduration', '0',
    '-loglevel', '0',
    '-f', 's16le',
    '-ar', '48000',
    '-ac', '2',
  ],
});

transcoder.output.pipe(require('fs').createWriteStream('test.pcm'));
transcoder.output.on('data', console.log);
transcoder.on('debug', console.log);
transcoder.on('warn', console.log);
transcoder.on('error', console.log);

transcoder.output.on('end', () => {
  respond(`encoding took ${Date.now() - start}ms`);
  console.log(`encoding took ${Date.now() - start}ms`);
}

Typescript error: No declarations for duplex-child-process

Issue:

The library throws a typescript error when being used:

node_modules/prism-media/dist/ffmpeg/index.d.ts:3:32 - error TS7016: Could not find a declaration file for module 'duplex-child-process'. '/Users/tony/Projects/discord.js/packages/voice/examples/recorder/node_modules/duplex-child-process/index.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/duplex-child-process` if it exists or add a new declaration (.d.ts) file containing `declare module 'duplex-child-process';`

3 import DuplexChildProcess from 'duplex-child-process';

Steps to reproduce:

  1. Install the library via npm
  2. Use this code:
	const oggStream = new prism.opus.OggLogicalBitstream({
		opusHead: new prism.opus.OpusHead({
			channelCount: 2,
			sampleRate: 48000,
		}),
		pageSizeControl: {
			maxPackets: 10,
		},
	});
  1. Run and get a typescript error

Further details:

  • Operating System: MacOS Big Sur 11.5.2
  • Node.js version: 16.14.2
  • Commit I'm using: 2.0.0-alpha.0

FFMPEG Not working, due to broken ffmpeg package

Issue:

ffmpeg not found due to node-ffmpeg-binaries links removed.

Steps to reproduce:

Further details:

  • Operating System: Linux x64
  • Node.js version: v10.15.3
  • Commit I'm using: 9f7970f3497b12a26fb00a9d98fb3fc0a412a9ee

not sure if this is important, but...

Issue:

So I am using this package for a discordjs bot to play music. And sometimes (when i pause the streamDispatcher for a while, and resume), I get the following errors:

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at StreamDispatcher.write (_stream_writable.js:292:11)
    at Encoder.ondata (_stream_readable.js:717:22)
    at Encoder.emit (events.js:314:20)
    at addChunk (_stream_readable.js:307:12)
    at readableAddChunk (_stream_readable.js:282:9)
    at Encoder.push (_stream_readable.js:221:10)
    at Encoder.push (_stream_transform.js:166:32)
    at Encoder._transform (/usr/app/node_modules/prism-media/src/opus/Opus.js:144:12)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  code: 'ERR_STREAM_WRITE_AFTER_END'
}
TypeError: Cannot read property 'length' of null
    at Encoder._transform (/usr/app/node_modules/prism-media/src/opus/Opus.js:142:25)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5) Promise {
  <rejected> TypeError: Cannot read property 'length' of null
      at Encoder._transform (/usr/app/node_modules/prism-media/src/opus/Opus.js:142:25)       
      at runMicrotasks (<anonymous>)
      at processTicksAndRejections (internal/process/task_queues.js:93:5)
}

Steps to reproduce:

Sometimes it happens randomly when playing music; other times is when pausing the StreamDispatcher for a while then resume using Discord.js.

Further details:

  • Operating System:
  • Node.js version:
  • Commit I'm using:

Is it possible to change frames per packets?

I might be wrong but in my tests prims.opus.Encoder generates stream with only 1 frame per packet.
I tried rates of 48000/20 and 16000/60 and different bitrates.
In all the cases I received a stream with only one frame per packet.
I also reviewed the list of Encoder.set* methods and didn't find there anything related.
Can we control this parameter or not?

List of allowed rates and frameSizes? (Segmentation faults otherwise)

I wonder what is the allowed combinations of rate and frameSize options for prism.opus.Encoder?

From my experiments just a limited list is actually allowed, step left or right - and it's crashing with segmentation fault error.

Here is a code for example which crashes:

import prism from 'prism-media';
import fs from 'fs';
import { PassThrough } from 'stream';

const samplingRate = 32000; // (1)
const frameSize = 60; // (2)

const stream = fs.createReadStream('01.wav');
const transcoderStream = new prism.FFmpeg({
  args: ['-i', '-', '-f', 's16le', '-filter:a', `aresample=${samplingRate}`, '-channel_layout', 'mono'],
});

const encoderOptions = {
  rate: samplingRate,
  channels: 1,
  frameSize: Math.round((frameSize / 1000) * samplingRate),
};
console.log(encoderOptions, 'Encoder options');

const encodeStream = new prism.opus.Encoder(encoderOptions);

stream.pipe(transcoderStream).pipe(encodeStream).pipe(new PassThrough());

If you change lines (1) and (2) to:

const samplingRate = 48000; // (1)
const frameSize = 20; // (2)

or

const samplingRate = 16000; // (1)
const frameSize = 60; // (2)

it won't crash.

I would like to have a helper function for generating appropriate inputs for prism.opus.Encoder.

Crashing with opusscript

Following a simple tutorial like this causes a null exception that crashes the whole streaming.

Reproduce:

  1. Install opusscript
  2. Call conn.play(what_ever_source)
  3. You get
TypeError: Cannot convert "null" to int
TypeError: Cannot convert "null" to int
at (anonymous) (file:///c:/Users/pc/Documents/Discord%20Bot/node_modules/opusscript/build/opusscript_native_wasm.js:8:1741)

This is caused by Opus.js:55 passing a null as framesize which later crashesopusscript. In my case, this._options.frameSize === 960` so it's correctly filled.

  _encode(buffer) {
    return this.encoder.encode(buffer, Opus.name === 'opusscript' ? null : this._options.frameSize);
  }

I have no deeper insight why there is this name check, but after I deleted it, it worked like a charm. Could you please fix that? This works fine

  _encode(buffer) {
    return this.encoder.encode(buffer, tthis._options.frameSize);
  }

throw Error(`capture_pattern is not ${OGGS_HEADER}`)

Issue:

Aloha All!

I migrated over to V12 with the hope that all issues with Opus playback would go away. Running into the same issues.

I pull in an MP3 file from cloudFront. I then save this file locally to convert it to opus.

I run the routines as shown into the "mp3 to opus" example. I label the suffix ".ogg" and everything seems to work as planned. I can play the MP3 file without any issues. It is my understanding that Prism uses FFmpeg to convert an MP3 file to opus on the fly. Since any MP3 submitted for playback works flawlessly, I am assuming that the behind the scene conversion does work. I am attempting to convert the files to save on response time to the users. The MP3 files can become quite large. I am currently testing with a 14 second MP3.

I run into a wall anytime I am trying to convert, store, then retrieve the "opus/ogg" file for playback.

When I go to actually play the Opus Ogg file, it blows up with this error:

throw Error(capture_pattern is not ${OGGS_HEADER})

Here is the full trace:

Error: capture_pattern is not OggS
at OggDemuxer._readPage (/home/centos/discord/v12/node_modules/prism-media/src/opus/OggDemuxer.js:56:13)
at OggDemuxer._transform (/home/centos/discord/v12/node_modules/prism-media/src/opus/OggDemuxer.js:36:27)
at OggDemuxer.Transform._read (_stream_transform.js:191:10)
at OggDemuxer.Transform._write (_stream_transform.js:179:12)
at doWrite (_stream_writable.js:454:12)
at writeOrBuffer (_stream_writable.js:436:5)
at OggDemuxer.Writable.write (_stream_writable.js:327:11)
at ReadStream.ondata (_stream_readable.js:708:22)
at ReadStream.emit (events.js:321:20)
at addChunk (_stream_readable.js:297:12)
at readableAddChunk (_stream_readable.js:273:9)
at ReadStream.Readable.push (_stream_readable.js:214:10)
at internal/fs/streams.js:242:14
at FSReqCallback.wrapper [as oncomplete] (fs.js:496:5)

Steps to reproduce:

Here is the convert code following the "mp3 to opus" example:

const convert = fs.createReadStream(mp3File);
const opus = new prism.opus.Encoder({ rate: 48000, channels: 2, frameSize: 960 });

const transcoder = new prism.FFmpeg({
args: [
'-analyzeduration', '0',
'-loglevel', '0',
'-f', 's16le',
'-ar', '48000',
'-ac', '2',
],
});

let test = __dirname + '/podcasts/' + identifier + '.ogg';

convert.pipe(transcoder).pipe(opus).pipe(fs.createWriteStream(test));

The above code successfully writes out the conversion, even though the format appears to be incorrect.

I have tried:

convert.pipe(transcoder).pipe(fs.createWriteStream(test));

convert.pipe(opus).pipe(fs.createWriteStream(test));

with the same results.

Here is the code for the playback following new V12 conventions:

const dispatcher = connection.play(fs.createReadStream(audioFile), { type: 'ogg/opus' });

Help!

Thanks in advance!

Further details:

  • Operating System: CENTOS 7
  • Node.js version: 13.9
  • Commit I'm using:

Calling some YT-Vids brings Error FFmpeg/avconv not found!

Issue:

C:\Users\Chris\IdeaProjects\uwuBot\node_modules\ytdl-core-discord\node_modules\prism-media\src\core\FFmpeg.js:130
    throw new Error('FFmpeg/avconv not found!');
    ^

Error: FFmpeg/avconv not found!
    at Function.getInfo (C:\Users\Chris\IdeaProjects\uwuBot\node_modules\ytdl-core-discord\node_modules\prism-media\src\core\FFmpeg.js:130:11)
    at Function.create (C:\Users\Chris\IdeaProjects\uwuBot\node_modules\ytdl-core-discord\node_modules\prism-media\src\core\FFmpeg.js:143:38)
    at new FFmpeg (C:\Users\Chris\IdeaProjects\uwuBot\node_modules\ytdl-core-discord\node_modules\prism-media\src\core\FFmpeg.js:44:27)
    at C:\Users\Chris\IdeaProjects\uwuBot\node_modules\ytdl-core-discord\index.js:35:24
    at C:\Users\Chris\IdeaProjects\uwuBot\node_modules\ytdl-core\lib\info.js:337:9
    at C:\Users\Chris\IdeaProjects\uwuBot\node_modules\ytdl-core\lib\info.js:220:11
    at checkDone (C:\Users\Chris\IdeaProjects\uwuBot\node_modules\ytdl-core\lib\util.js:373:7)
    at SAXParser.parser.onend (C:\Users\Chris\IdeaProjects\uwuBot\node_modules\ytdl-core\lib\info.js:262:26)
    at emit (C:\Users\Chris\IdeaProjects\uwuBot\node_modules\sax\lib\sax.js:624:35)
    at end (C:\Users\Chris\IdeaProjects\uwuBot\node_modules\sax\lib\sax.js:667:5)
    at SAXParser.write (C:\Users\Chris\IdeaProjects\uwuBot\node_modules\sax\lib\sax.js:975:14)
    at SAXParser.close (C:\Users\Chris\IdeaProjects\uwuBot\node_modules\sax\lib\sax.js:157:38)
    at PassThrough.emit (events.js:223:5)
    at endReadableNT (_stream_readable.js:1185:12)
    at processTicksAndRejections (internal/process/task_queues.js:81:21)

Using ytdl-core-discord, 'https://www.youtube.com/watch?v=8e16Cu5S660' will crash the DiscordBot. Could be more Videos but i only found this until now. 'https://www.youtube.com/watch?v=zQ4LiyFF8RU' for Example works fine.

Steps to reproduce:

Probably just install ytdl-core-discord and call ytdl(url) will crash with given Error

Further details:

  • Operating System: Windows 10
  • Node.js version: 12.14.1
  • Commit I'm using: ?

The compressed data passed is corrupted

Issue:

I'm trying to get a audio packet from a user, and when i try and run my code it shows up as

the picture

or

/home/row/alexa_bot_testing/node_modules/prism-media/src/opus/Opus.js:64
    return this.encoder.decode(buffer, Opus.name === 'opusscript' ? null : this._options.frameSize);
                        ^

TypeError: The compressed data passed is corrupted
    at Decoder._decode (/home/row/alexa_bot_testing/node_modules/prism-media/src/opus/Opus.js:64:25)
    at Decoder._transform (/home/row/alexa_bot_testing/node_modules/prism-media/src/opus/Opus.js:203:20)
    at Decoder.Transform._read (_stream_transform.js:205:10)
    at Decoder.Transform._write (_stream_transform.js:193:12)
    at writeOrBuffer (_stream_writable.js:352:12)
    at Decoder.Writable.write (_stream_writable.js:303:10)
    at Readable.ondata (_stream_readable.js:719:22)
    at Readable.emit (events.js:315:20)
    at addChunk (_stream_readable.js:309:12)
    at readableAddChunk (_stream_readable.js:284:9)

I'm running this for a discord bot, it might be a discord thing but wanted to check first

node version - v14.15.1
npm version - 6.14.8
prism-media version - 1.2.3

So how to specify the only thing which matters - the bitrate?

After playing for a while I now see that the options we pass to the encoder/decoder don't really matter.
The only thing which does matter would be the bitrate, but there is no such an option.
How is that?

Also, I checked out the underlying @deiscordjs/opus lib and well... it doesn't even have the Frame Size option, only the sampling rate (which should always be 48kHz according to the RFC) and the number of channels.

So now I'm really confused with all that.
If this lib is using @deiscordjs/opus under the cover, then why requiring from us to provide the frameSize at all?

Error: spawn ENOMEM

Issue:

I am getting this error, seemingly at random, after trying to start a stream:

(node:14009) UnhandledPromiseRejectionWarning: Error: spawn ENOMEM
    at ChildProcess.spawn (internal/child_process.js:408:11)
    at Object.spawn (child_process.js:553:9)
    at Function.create (/home/br88c/github/peter/node_modules/prism-media/src/core/FFmpeg.js:155:25)
    at new FFmpeg (/home/br88c/github/peter/node_modules/prism-media/src/core/FFmpeg.js:44:27)
    at StreamDownloader (/home/br88c/github/peter/node_modules/discord-ytdl-core/index.js:45:24)
    at Object.play (/home/br88c/github/peter/src/modules/streamhandler.js:57:22)
    at Object.execute (/home/br88c/github/peter/src/commands/play.js:135:27)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

It appears it's having trouble with starting FFMPEG, but I am unsure of the cause. Normally it works completely fine, then it'll start throwing this error and will continue to throw this error until I restart my code. Help is greatly appreciated!

Further details:

  • Operating System: Debian 10
  • Node.js version: 12.20.0
  • Commit I'm using: 1.2.3

[minor] FFmpeg blocks node from exiting

It seems like basic creation of a prism.FFmpeg stream makes node to think it should wait.

// ...
const transcoderStream = new prism.FFmpeg({
   args: ['-i', '-', '-f', 's16le', '-ar', '16000', '-channel_layout', 'mono'],
});
// ...

When launched, it's continuing to wait upon finishing everything else.

Running it with wtfnode:

$ wtfnode script.js

results to:

...
[WTF Node?] open handles:
- File descriptors: (note: stdio always exists)
  - fd 2 (tty) (stdio)
  - fd 1 (tty) (stdio)
- Child processes
  - PID 24331
    - Entry point: /projects/custom/ts-zello/node_modules/prism-media/src/core/FFmpeg.js:156
    - STDIO file descriptors: 22, 24, 26

Feature request: Enable volume fading functionality in VolumeTransformer

Problem

It is currently impossible, using VolumeTransformer, to make a smooth transition between volumes.

Ideal solution

  • Add fadeTime or fadeSpeed to options, change this.volume to semantically mean "target volume", and add logic for smoothly transitioning between target volumes in the _transform method.
  • Make setVolume async, to be resolved or rejected when the transition is complete.
  • Add setFadeTime, etc. methods.

Other alternatives

Make a new VolumeTransformer variant, SmoothVolumeTransformer, which implements the above functionality.

[BUG] TypeError: failed to downcast any to number

Issue: When recording the audio of a user, it causes an error (discord.js)

Steps to reproduce:

Install nodejs, use Discord, initiate your discord bot, use theses packages:

 "dependencies": {
    "@discordjs/opus": "^0.6.0",
    "@discordjs/voice": "^0.6.0",
    "axios": "^0.21.3",
    "bufferutil": "^4.0.3",
    "colors": "^1.4.0",
    "crypto": "^1.0.1",
    "discord.js": "^13.1.0",
    "ffmpeg-static": "^4.4.0",
    "fs": "^0.0.1-security",
    "libsodium-wrappers": "^0.7.9",
    "moment": "^2.29.1",
    "ms": "^2.1.3",
    "node-crc": "^2.0.11",
    "nodemon": "^2.0.12",
    "prism-media": "^2.0.0-alpha.0",
    "stream": "^0.0.2",
    "utf-8-validate": "^5.0.5",
    "youtube-dl-exec": "^1.2.5",
    "ytdl-core": "^4.9.1"
  }

Use this code to initiate a connection betwwen the bot and the user, and so to record his voice :

//if user send message ".record" then, join voice channel and send info to prism-media to record and export to .ogg file
                console.log("Got a record call")
                console.log(message.guildId)
                if (message.guildId) {
                    console.log("This server doesn't have any subscription [voice registered]")
                    /**
                     * @type {DiscordVoice.VoiceConnection}
                     */
                    var connection;
                    if (!connection) {
                        if (message.member instanceof Discord.GuildMember && message.member.voice.channel) {
                            const channel = message.member.voice.channel;
                            connection = await util.voiceconnectToChannel(channel);
                        } else {
                            await message.channel.send('Join a voice channel and then try that again!');
                            return;
                        }
                    }

                    try {
                        await DiscordVoice.entersState(connection, DiscordVoice.VoiceConnectionStatus.Ready, 20_000);
                        const receiver = connection.receiver;

                        receiver.speaking.on('start', (userId) => {
                            console.log(receiver)
                            console.log(userId)
                            console.log(client.users.cache.get(userId))
                            util.createListeningStream(receiver, userId, client.users.cache.get(userId));
                        });
                    } catch (error) {
                        console.warn(error);
                        await message.channel.send('Failed to join voice channel within 20 seconds, please try again later!');
                    }

                }

const oggStream = new opus.OggLogicalBitstream(
            {
                opusHead: new opus.OpusHead({
                    channelCount: 2,
                    sampleRate: 48000,
                }),
                pageSizeControl: {
                    maxPackets: 10,
                },
            }
        );

I'm using the exact same code here : https://github.com/discordjs/voice/blob/main/examples/recorder/src/createListeningStream.ts
but using it in javascript, installed typescript to have compatibility working, returning me this error when speaking:
image

Further details:

  • Operating System:
    Linux Debian 10 x86_64
  • Node.js version:
    16.6.0
  • Commit I'm using:
    "prism-media": "^2.0.0-alpha.0",

Missing Opus Module

Hello folks,

Issue:

I'm trying to program a small discord bot in javascript. The bot is supposed to join in a voice server if someone types "-snus", that works. After that it should play a sound and leave the voice channel again. So i'm a bit familiar with javascript so i coded this little script:

const Discord = require('discord.js');
const bot = new Discord.Client();

const token = 'XXXXX';

bot.on('ready', () => {
    console.log("Er is online!!");
});

bot.on('message',async message=>{
    if(message.content === "-snus")
    {
        if(message.member.voice.channel)
        {
            const connection = await message.member.voice.channel.join();
            const ytdl = require('ytdl-core');
            connection.play(ytdl('XXX', { filter: 'audioonly' }));
        }
        else
        {
            message.reply('Geh in an voice channel du kek');
        }
    }
})
bot.login(token);

On windows this just works fine i installed a nodejs environment and downloaded via npm discord.js, ytdl-core and opusscript. To make it run 24/7 i want to make it run on a raspberry pi 3b. Again same procedure moved the script to my raspberry downloaded the packages and than this error occures:

Er is online!!
TypeError: Cannot convert "null" to int
TypeError: Cannot convert "null" to int /var/www/dcbots/node_modules/opusscript/build/opusscript_native_wasm.js:8 var Module=typeof Module!=="undefined"?Module:{};var moduleOverrides={};var key;for(key_

and so on i don't think this is important soo fast forward after some googleing i found out that this is due to the opusscript packet, it shouldn't be used for discord voice bots so I uninstalled it and than this error pops out:

(node:24615) UnhandledPromiseRejectionWarning: Error: Could not find an Opus module! Please install @discordjs/opus, node-opus, or opusscript.

Ok so this and basically everyone else on the internet tells me to install @discordjs/opus and it
seems to work for everyone expect me. When I try to install this via npm i get this error message:
so i type $npm install @discordjs/opus

@discordjs/[email protected] install /var/www/dcbots/node_modules/@discordjs/opus
> node-pre-gyp install --fallback-to-build
node-pre-gyp WARN Using needle for node-pre-gyp https download 
node-pre-gyp WARN Pre-built binaries not installable for @discordjs/[email protected] and [email protected] (node-v79 ABI, glibc) (falling back to source compile with node-gyp) 
node-pre-gyp WARN Hit error EACCES: permission denied, mkdir '/var/www/dcbots/node_modules/@discordjs/opus/prebuild' 
gyp WARN EACCES current user ("Alexander") does not have permission to access the dev dir "/root/.cache/node-gyp/13.11.0"
gyp WARN EACCES attempting to reinstall using temporary dev dir "/var/www/dcbots/node_modules/@discordjs/opus/.node-gyp"
gyp WARN install got an error, rolling back install
gyp WARN install got an error, rolling back install
gyp ERR! configure error 
gyp ERR! stack Error: EACCES: permission denied, mkdir '/var/www/dcbots/node_modules/@discordjs/opus/.node-gyp'
gyp ERR! System Linux 4.19.97-v7+
gyp ERR! command "/opt/nodejs/bin/node" "/opt/nodejs/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "configure" "--fallback-to-build" "--module=/var/www/dcbots/node_modules/@discordjs/opus/prebuild/node-v79-linux-arm/opus.node" "--module_name=opus" "--module_path=/var/www/dcbots/node_modules/@discordjs/opus/prebuild/node-v79-linux-arm" "--napi_version=6" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=node-v79"
gyp ERR! cwd /var/www/dcbots/node_modules/@discordjs/opus
gyp ERR! node -v v13.11.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok 
node-pre-gyp ERR! build error 
node-pre-gyp ERR! stack Error: Failed to execute '/opt/nodejs/bin/node /opt/nodejs/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/var/www/dcbots/node_modules/@discordjs/opus/prebuild/node-v79-linux-arm/opus.node --module_name=opus --module_path=/var/www/dcbots/node_modules/@discordjs/opus/prebuild/node-v79-linux-arm --napi_version=6 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v79' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/var/www/dcbots/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:1026:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
node-pre-gyp ERR! System Linux 4.19.97-v7+
node-pre-gyp ERR! command "/opt/nodejs/bin/node" "/var/www/dcbots/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /var/www/dcbots/node_modules/@discordjs/opus
node-pre-gyp ERR! node -v v13.11.0
node-pre-gyp ERR! node-pre-gyp -v v0.14.0
node-pre-gyp ERR! not ok 
Failed to execute '/opt/nodejs/bin/node /opt/nodejs/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/var/www/dcbots/node_modules/@discordjs/opus/prebuild/node-v79-linux-arm/opus.node --module_name=opus --module_path=/var/www/dcbots/node_modules/@discordjs/opus/prebuild/node-v79-linux-arm --napi_version=6 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v79' (1)
npm WARN [email protected] No repository field.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @discordjs/[email protected] install: `node-pre-gyp install --fallback-to-build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the @discordjs/[email protected] install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     _/root/.npm/_logs/2020-04-10T17_56_40_347Z-debug.log

I'm not getting much wiser with these logs either. So bacically my probleam is that i am unable to install the @discordjs/opus module for my raspberry.
I don't get why I can't install this module is it just for windows?

Steps to reproduce:

try to install @discordjs/opus on linux

Further details:

  • Operating System:

  • PRETTY_NAME="Raspbian GNU/Linux 10 (buster)"

  • NAME="Raspbian GNU/Linux"

  • VERSION_ID="10"

  • VERSION="10 (buster)"

  • VERSION_CODENAME=buster

  • ID=raspbian

  • ID_LIKE=debian

  • Node.js version: v13.11.0
    npm: '6.14.4',

  • Commit I'm using:

Decoding in real-time becomes gaped

My question may look a little unrelated to the usage of this particular library.

Basically, I receive an Opus stream from the internet, decode it with prism.opus.Decoder, get PCM packets and stream them forward to the speakers:

    events.onAudioData(async ({ event, opusInfo, getStream }) => {
        // A stream with Opus packets
        const stream = getStream(undefined, false);

        const frameSize = (opusInfo.inputSampleRate * opusInfo.frameSize) / 1000;
        const opusOpt = {
          rate: opusInfo.inputSampleRate,
          channels: opusInfo.channels,
          frameSize,
        };
        const opusDecoder = new prism.opus.Decoder(opusOpt);

        const normalizer = new NormalizeRateStream({
          bufferLengthMs: 2 * 1000,
          packetLengthMs: event.packet_duration,
        });

        const speaker = new Speaker({
          channels: opusInfo.channels,
          bitDepth: 16,
          sampleRate: opusInfo.inputSampleRate,
        });

        stream.pipe(getOpusStatsStream(pinoLogger)).pipe(opusDecoder).pipe(normalizer).pipe(speaker);
    });

There is also a duplex normalizing stream which ensures requested rate of packets per time.

The problem is that sound becomes gaped and I cannot find a way to glue pieces in one steady stream.

I recorded a helping video which demonstrates the problem:

https://www.youtube.com/watch?v=O7Fv3GTMjKQ

Do you have any idea why it's happening?

How to calculate frameSize when encoding?

Currently Encoder requires from us to provide the proper frameSize parameter:

  const opus = new prism.opus.Encoder({ rate: 48000, channels: 1, frameSize: 960 });

I assume 'requires' in the TypeScript meaning, as there's no way to omit it.

There are few concerns.

  1. The official Opus docs say:

frame_size is the duration of the frame in samples (per channel).

while prism applies a different meaning to the same thing:

the frame size in bytes to use (e.g. 960 for stereo audio at 48KHz with a frame duration of 20ms)

which I believe brings some confusion.

  1. And what is more important, is that it's not clear how to calculate it.
    Obviously, if it can be calculated automatically then it doesn't need to be required, does it?
    If not - then please, explain how to calc it.

properly destroying ffmpeg

Issue:

im getting Cannot call write after a stream was destroyed in discord.js after doing <prism ffmpeg>.destroy() on dispatcher finish event

Steps to reproduce:

use prism ffmpeg and pass it into dispatcher, then destroy this ffmpeg on disaptcher finish (without it, ffmpegs does not despawn)

Further details:

  • Operating System: windows 10 home
  • Node.js version: 12.4.1
  • Commit I'm using: prism 1.2.0 (that one that comes with discord.js master)

My reason of creating this issue

i cant seem to destroy ffmpeg without errors so my question is how can i destroy it properly
// it happens only while piping ytdl to transcoder, using -i url in ffmpeg doesnt throw that

Error: write EPIPE

events.js:291
      throw er; // Unhandled 'error' event
      ^

Error: write EPIPE
    at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:94:16)
Emitted 'error' event on FFmpeg instance at:
    at errorOrDestroy (internal/streams/destroy.js:108:12)
    at FFmpeg.onerror (_stream_readable.js:755:7)
    at FFmpeg.emit (events.js:314:20)
    at Socket.processError (/Volumes/Extreme SSD/Projects/Discord_Bots/music_bot/node_modules/prism-media/src/core/FFmpeg.js:64:40)
    at Socket.emit (events.js:314:20)
    at errorOrDestroy (internal/streams/destroy.js:108:12)
    at onwriteError (_stream_writable.js:424:5)
    at onwrite (_stream_writable.js:445:5)
    at internal/streams/destroy.js:50:7
    at Socket._destroy (net.js:681:5) {
  errno: 'EPIPE',
  code: 'EPIPE',
  syscall: 'write'
}

I am unable to use this library. I get the error above.

"Error: FFmpeg/avconv not found!" although ffmpeg-static is installed

Issue:

When users attempt to play certain videos, it errors Error: FFmpeg/avconv not found!, although ffmpeg-static v4.2.7 is installed in the project.

After using apt install ffmpeg, it works fine.

Steps to reproduce:

Try to play a video such as this (reported by a user) with ffmpeg-static v4.2.7 and without ffmpeg installed normally on the system

Further details:

  • Operating System: Ubuntu 18.04.4 LTS x86_64
  • Node.js version: v14.6.0
  • Commit I'm using: 1.2.2_20d841fc779176bec97aa2e7b2e5e880

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.