
Recherche avancée
Autres articles (89)
-
MediaSPIP v0.2
21 juin 2013, parMediaSPIP 0.2 est la première version de MediaSPIP stable.
Sa date de sortie officielle est le 21 juin 2013 et est annoncée ici.
Le fichier zip ici présent contient uniquement les sources de MediaSPIP en version standalone.
Comme pour la version précédente, il est nécessaire d’installer manuellement l’ensemble des dépendances logicielles sur le serveur.
Si vous souhaitez utiliser cette archive pour une installation en mode ferme, il vous faudra également procéder à d’autres modifications (...) -
Le profil des utilisateurs
12 avril 2011, parChaque utilisateur dispose d’une page de profil lui permettant de modifier ses informations personnelle. Dans le menu de haut de page par défaut, un élément de menu est automatiquement créé à l’initialisation de MediaSPIP, visible uniquement si le visiteur est identifié sur le site.
L’utilisateur a accès à la modification de profil depuis sa page auteur, un lien dans la navigation "Modifier votre profil" est (...) -
MediaSPIP version 0.1 Beta
16 avril 2011, parMediaSPIP 0.1 beta est la première version de MediaSPIP décrétée comme "utilisable".
Le fichier zip ici présent contient uniquement les sources de MediaSPIP en version standalone.
Pour avoir une installation fonctionnelle, il est nécessaire d’installer manuellement l’ensemble des dépendances logicielles sur le serveur.
Si vous souhaitez utiliser cette archive pour une installation en mode ferme, il vous faudra également procéder à d’autres modifications (...)
Sur d’autres sites (7912)
-
FFMpeg CUDA yuvj420p frame conversion to cv::Mat layers shifted
26 février 2023, par AcidTonicI am trying to retrieve hardware decoded H264 frames from the cuda backend of ffmpeg and display them as a cv::Mat. I got decently far and was able to get color images but it seems the conversion is not quite right as the image I get has a green bar at the top and if you look closely the blue parts of the image are offset down and to the right a little bit making everything look a little wonky.


Correct Image as shown by ffplay using the same driver


Image I am getting



Here is the full source code in the hopes someone can help me to get the correct image here...


#include 

#include 

#include 

#include 

#include 

#include 

#include <iostream>

#include <fstream>

#include <cstdlib>

#include <chrono>

#include <cstring>

extern "C" {

 //Linker errors if not inside extern. FFMPEG headers are not C++ aware
 #include <libavcodec></libavcodec>avcodec.h>

 #include <libavformat></libavformat>avformat.h>

 #include <libavutil></libavutil>pixdesc.h>

 #include <libavutil></libavutil>hwcontext.h>

 #include <libavutil></libavutil>opt.h>

 #include <libavutil></libavutil>avassert.h>

 #include <libavutil></libavutil>imgutils.h>

}

#include <iomanip>

#include <string>

#include <sstream>

#include <opencv2></opencv2>opencv.hpp>

#ifdef __cplusplus
extern "C" {
 #endif // __cplusplus
 #include <libavdevice></libavdevice>avdevice.h>

 #include <libavfilter></libavfilter>avfilter.h>

 #include <libavformat></libavformat>avio.h>

 #include <libavutil></libavutil>avutil.h>

 #include <libpostproc></libpostproc>postprocess.h>

 #include <libswresample></libswresample>swresample.h>

 #include <libswscale></libswscale>swscale.h>

 #ifdef __cplusplus
} // end extern "C".
#endif // __cplusplus

static AVBufferRef * hw_device_ctx = NULL;
static enum AVPixelFormat hw_pix_fmt;
static FILE * output_file_fd = NULL;
cv::Mat output_mat;
int bgr_size;

static int hw_decoder_init(AVCodecContext * ctx,
 const enum AVHWDeviceType type) {
 int err = 0;

 if ((err = av_hwdevice_ctx_create( & hw_device_ctx, type,
 NULL, NULL, 0)) < 0) {
 fprintf(stderr, "Failed to create specified HW device.\n");
 return err;
 }
 ctx -> hw_device_ctx = av_buffer_ref(hw_device_ctx);

 return err;
}

static enum AVPixelFormat get_hw_format(AVCodecContext * ctx,
 const enum AVPixelFormat * pix_fmts) {
 const enum AVPixelFormat * p;

 for (p = pix_fmts;* p != -1; p++) {
 if ( * p == hw_pix_fmt)
 return * p;
 }

 fprintf(stderr, "Failed to get HW surface format.\n");
 return AV_PIX_FMT_NONE;
}

static int decode_write(AVCodecContext * avctx, AVPacket * packet) {
 AVFrame * frame = NULL, * sw_frame = NULL;
 AVFrame * tmp_frame = NULL;
 uint8_t * buffer = NULL;
 int size;
 int ret = 0;

 ret = avcodec_send_packet(avctx, packet);
 if (ret < 0) {
 fprintf(stderr, "Error during decoding\n");
 return ret;
 }

 while (1) {
 if (!(frame = av_frame_alloc()) || !(sw_frame = av_frame_alloc())) {
 fprintf(stderr, "Can not alloc frame\n");
 ret = AVERROR(ENOMEM);
 av_frame_free( & frame);
 av_frame_free( & sw_frame);
 av_freep( & buffer);
 if (ret < 0) {
 return ret;
 }

 }

 ret = avcodec_receive_frame(avctx, frame);
 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
 av_frame_free( & frame);
 av_frame_free( & sw_frame);
 return 0;
 } else if (ret < 0) {
 fprintf(stderr, "Error while decoding\n");
 av_frame_free( & frame);
 av_frame_free( & sw_frame);
 av_freep( & buffer);
 if (ret < 0) {
 return ret;
 }

 }

 if (frame -> format == hw_pix_fmt) {
 /* retrieve data from GPU to CPU */
 if ((ret = av_hwframe_transfer_data(sw_frame, frame, 0)) < 0) {
 fprintf(stderr, "Error transferring the data to system memory\n");
 av_frame_free( & frame);
 av_frame_free( & sw_frame);
 av_freep( & buffer);
 if (ret < 0) {
 return ret;
 }

 }
 tmp_frame = sw_frame;
 } else {
 tmp_frame = frame;
 }

 AVPixelFormat format_to_use = AV_PIX_FMT_YUVJ420P;
 cv::Mat mat_src = cv::Mat(sw_frame -> height + (sw_frame -> height / 2), sw_frame -> width, CV_8UC1, sw_frame -> data[0]);
 cv::Mat out_mat;
 cv::cvtColor(mat_src, out_mat, cv::COLOR_YUV2RGB_NV21);

 output_mat = out_mat;

 if (output_mat.empty() == false) {
 cv::imshow("image", output_mat);
 cv::waitKey(1);
 }

 av_frame_free( & frame);
 av_frame_free( & sw_frame);
 av_freep( & buffer);
 return ret;
 }
}

TEST_CASE("CUDAH264", "Tests hardware h264 decoding") {

 AVFormatContext * input_ctx = NULL;
 int video_stream, ret;
 AVStream * video = NULL;
 AVCodecContext * decoder_ctx = NULL;
 AVCodec * decoder = NULL;
 AVPacket * packet = NULL;
 enum AVHWDeviceType type;
 int i;

 std::string device_type = "cuda";
 std::string input_file = "rtsp://10.100.2.152"; //My H264 network stream here...

 /* The stream data is below...
 Input #0, rtsp, from 'rtsp://10.100.2.152':
 Metadata:
 title : VCP IPC Realtime stream
 Duration: N/A, start: 0.000000, bitrate: N/A
 Stream #0:0: Video: h264 (High), yuvj420p(pc, bt709, progressive), 1920x1080, 10 fps, 10 tbr, 90k tbn, 20 tbc
 */

 type = av_hwdevice_find_type_by_name(device_type.c_str());
 if (type == AV_HWDEVICE_TYPE_NONE) {
 fprintf(stderr, "Device type %s is not supported.\n", device_type.c_str());
 fprintf(stderr, "Available device types:");
 while ((type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE)
 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
 fprintf(stderr, "\n");
 throw std::runtime_error("Error");
 }

 packet = av_packet_alloc();
 if (!packet) {
 fprintf(stderr, "Failed to allocate AVPacket\n");
 throw std::runtime_error("Error");
 }

 /* open the input file */
 if (avformat_open_input( & input_ctx, input_file.c_str(), NULL, NULL) != 0) {
 fprintf(stderr, "Cannot open input file '%s'\n", input_file.c_str());
 throw std::runtime_error("Error");
 }

 if (avformat_find_stream_info(input_ctx, NULL) < 0) {
 fprintf(stderr, "Cannot find input stream information.\n");
 throw std::runtime_error("Error");
 }

 av_dump_format(input_ctx, 0, input_file.c_str(), 0);

 for (int i = 0; i < input_ctx -> nb_streams; i++) {
 auto pCodec = avcodec_find_decoder(input_ctx -> streams[i] -> codecpar -> codec_id);
 auto pCodecCtx = avcodec_alloc_context3(pCodec);
 avcodec_parameters_to_context(pCodecCtx, input_ctx -> streams[i] -> codecpar);

 printf("Found Video stream with ID: %d\n", input_ctx -> streams[i] -> id);
 printf("\t Stream Index: %d\n", input_ctx -> streams[i] -> index);

 AVCodecParameters * codecpar = input_ctx -> streams[i] -> codecpar;
 printf("\t Codec Type: %s\n", av_get_media_type_string(codecpar -> codec_type));
 printf("\t Side data count: %d\n", input_ctx -> streams[i] -> nb_side_data);
 printf("\t Pixel format: %i\n", input_ctx -> streams[i] -> codecpar -> format);
 printf("\t Pixel Format Name: %s\n", av_get_pix_fmt_name((AVPixelFormat) input_ctx -> streams[i] -> codecpar -> format));
 printf("\t Metadata count: %d\n", av_dict_count(input_ctx -> streams[i] -> metadata));
 }

 /* find the video stream information */
 ret = av_find_best_stream(input_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, & decoder, 0);
 if (ret < 0) {
 fprintf(stderr, "Cannot find a video stream in the input file\n");
 throw std::runtime_error("Error");
 }

 video_stream = ret;

 for (i = 0;; i++) {
 const AVCodecHWConfig * config = avcodec_get_hw_config(decoder, i);
 if (!config) {
 fprintf(stderr, "Decoder %s does not support device type %s.\n",
 decoder -> name, av_hwdevice_get_type_name(type));
 throw std::runtime_error("Error");
 }
 if (config -> methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
 config -> device_type == type) {
 hw_pix_fmt = config -> pix_fmt;
 break;
 }
 }

 if (!(decoder_ctx = avcodec_alloc_context3(decoder))) {
 throw std::runtime_error("NO MEMORY");
 }

 video = input_ctx -> streams[video_stream];
 if (avcodec_parameters_to_context(decoder_ctx, video -> codecpar) < 0) {
 throw std::runtime_error("Error");
 }

 decoder_ctx -> get_format = get_hw_format;

 if (hw_decoder_init(decoder_ctx, type) < 0) {
 throw std::runtime_error("Error");
 }

 if ((ret = avcodec_open2(decoder_ctx, decoder, NULL)) < 0) {
 fprintf(stderr, "Failed to open codec for stream #%u\n", video_stream);
 throw std::runtime_error("Error");
 }

 /* actual decoding and dump the raw data */
 while (ret >= 0) {
 if ((ret = av_read_frame(input_ctx, packet)) < 0)
 break;

 if (video_stream == packet -> stream_index)
 ret = decode_write(decoder_ctx, packet);

 av_packet_unref(packet);
 }

 /* flush the decoder */
 ret = decode_write(decoder_ctx, NULL);

 if (output_file_fd) {
 fclose(output_file_fd);
 }
 av_packet_free( & packet);
 avcodec_free_context( & decoder_ctx);
 avformat_close_input( & input_ctx);
 av_buffer_unref( & hw_device_ctx);

}
</sstream></string></iomanip></cstring></chrono></cstdlib></fstream></iostream>


-
What permission ffmpeg-static need in AWS Lambda ?
17 février 2023, par JánosI have this code. It download a image, made a video from it and upload it to S3. It runs on Lambda. Added packages, intalled, zipped, uploaded.


npm install --production
zip -r my-lambda-function.zip ./



But get an
error code 126


2023-02-17T09:27:55.236Z 5c845bb6-02c1-41b0-8759-4459591b57b0 INFO Error: ffmpeg exited with code 126
 at ChildProcess.<anonymous> (/var/task/node_modules/fluent-ffmpeg/lib/processor.js:182:22)
 at ChildProcess.emit (node:events:513:28)
 at ChildProcess._handle.onexit (node:internal/child_process:291:12)
2023-02-17T09:27:55.236Z 5c845bb6-02c1-41b0-8759-4459591b57b0 INFO Error: ffmpeg exited with code 126 at ChildProcess.<anonymous> (/var/task/node_modules/fluent-ffmpeg/lib/processor.js:182:22) at ChildProcess.emit (node:events:513:28) at ChildProcess._handle.onexit (node:internal/child_process:291:12)
</anonymous></anonymous>


Do I need to set a specific premission for ffmpeg ?


import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3'
import { fromNodeProviderChain } from '@aws-sdk/credential-providers'
import axios from 'axios'
import pathToFfmpeg from 'ffmpeg-static'
import ffmpeg from 'fluent-ffmpeg'
import fs from 'fs'
ffmpeg.setFfmpegPath(pathToFfmpeg)
const credentials = fromNodeProviderChain({
 clientConfig: {
 region: 'eu-central-1',
 },
})
const client = new S3Client({ credentials })

export const handler = async (event, context) => {
 try {
 let body
 let statusCode = 200
 const query = event?.queryStringParameters
 if (!query?.imgId && !query?.video1Id && !query?.video2Id) {
 return
 }

 const imgId = query?.imgId
 const video1Id = query?.video1Id
 const video2Id = query?.video2Id
 console.log(
 `Parameters received, imgId: ${imgId}, video1Id: ${video1Id}, video2Id: ${video2Id}`
 )
 const imgURL = getFileURL(imgId)
 const video1URL = getFileURL(`${video1Id}.mp4`)
 const video2URL = getFileURL(`${video2Id}.mp4`)
 const imagePath = `/tmp/${imgId}`
 const video1Path = `/tmp/${video1Id}.mp4`
 const video2Path = `/tmp/${video2Id}.mp4`
 const outputPath = `/tmp/${imgId}.mp4`
 await Promise.all([
 downloadFile(imgURL, imagePath),
 downloadFile(video1URL, video1Path),
 downloadFile(video2URL, video2Path),
 ])
 await new Promise((resolve, reject) => {
 console.log('Input files downloaded')
 ffmpeg()
 .input(imagePath)
 .inputFormat('image2')
 .inputFPS(30)
 .loop(1)
 .size('1080x1080')
 .videoCodec('libx264')
 .format('mp4')
 .outputOptions([
 '-tune animation',
 '-pix_fmt yuv420p',
 '-profile:v baseline',
 '-level 3.0',
 '-preset medium',
 '-crf 23',
 '-movflags +faststart',
 '-y',
 ])
 .output(outputPath)
 .on('end', () => {
 console.log('Output file generated')
 resolve()
 })
 .on('error', (e) => {
 console.log(e)
 reject()
 })
 .run()
 
 })
 await uploadFile(outputPath, imgId + '.mp4')
 .then((url) => {
 body = JSON.stringify({
 url,
 })
 })
 .catch((error) => {
 console.error(error)
 statusCode = 400
 body = error?.message ?? error
 })
 console.log(`File uploaded to S3`)
 const headers = {
 'Content-Type': 'application/json',
 'Access-Control-Allow-Headers': 'Content-Type',
 'Access-Control-Allow-Origin': 'https://tikex.com, https://borespiac.hu',
 'Access-Control-Allow-Methods': 'GET',
 }
 return {
 statusCode,
 body,
 headers,
 }
 } catch (error) {
 console.error(error)
 return {
 statusCode: 500,
 body: JSON.stringify('Error fetching data'),
 }
 }
}

const downloadFile = async (url, path) => {
 try {
 console.log(`Download will start: ${url}`)
 const response = await axios(url, {
 responseType: 'stream',
 })
 if (response.status !== 200) {
 throw new Error(
 `Failed to download file, status code: ${response.status}`
 )
 }
 response.data
 .pipe(fs.createWriteStream(path))
 .on('finish', () => console.log(`File downloaded to ${path}`))
 .on('error', (e) => {
 throw new Error(`Failed to save file: ${e}`)
 })
 } catch (e) {
 console.error(`Error downloading file: ${e}`)
 }
}
const uploadFile = async (path, id) => {
 const buffer = fs.readFileSync(path)
 const params = {
 Bucket: 't44-post-cover',
 ACL: 'public-read',
 Key: id,
 ContentType: 'video/mp4',
 Body: buffer,
 }
 await client.send(new PutObjectCommand(params))
 return getFileURL(id)
}
const getFileURL = (id) => {
 const bucket = 't44-post-cover'
 const url = `https://${bucket}.s3.eu-central-1.amazonaws.com/${id}`
 return url
}



Added
AWSLambdaBasicExecutionRole-16e770c8-05fa-4c42-9819-12c468cb5b49
permission, with policy :

{
 "Version": "2012-10-17",
 "Statement": [
 {
 "Effect": "Allow",
 "Action": "logs:CreateLogGroup",
 "Resource": "arn:aws:logs:eu-central-1:634617701827:*"
 },
 {
 "Effect": "Allow",
 "Action": [
 "logs:CreateLogStream",
 "logs:PutLogEvents"
 ],
 "Resource": [
 "arn:aws:logs:eu-central-1:634617701827:log-group:/aws/lambda/promo-video-composer-2:*"
 ]
 },
 {
 "Effect": "Allow",
 "Action": [
 "s3:GetObject",
 "s3:PutObject",
 "s3:ListBucket"
 ],
 "Resource": [
 "arn:aws:s3:::example-bucket",
 "arn:aws:s3:::example-bucket/*"
 ]
 },
 {
 "Effect": "Allow",
 "Action": [
 "logs:CreateLogGroup",
 "logs:CreateLogStream",
 "logs:PutLogEvents"
 ],
 "Resource": [
 "arn:aws:logs:*:*:*"
 ]
 },
 {
 "Effect": "Allow",
 "Action": [
 "ec2:DescribeNetworkInterfaces"
 ],
 "Resource": [
 "*"
 ]
 },
 {
 "Effect": "Allow",
 "Action": [
 "sns:*"
 ],
 "Resource": [
 "*"
 ]
 },
 {
 "Effect": "Allow",
 "Action": [
 "cloudwatch:*"
 ],
 "Resource": [
 "*"
 ]
 },
 {
 "Effect": "Allow",
 "Action": [
 "kms:Decrypt"
 ],
 "Resource": [
 "*"
 ]
 }
 ]
}



What do I miss ?


janoskukoda@Janoss-MacBook-Pro promo-video-composer-2 % ls -l $(which ffmpeg)
lrwxr-xr-x 1 janoskukoda admin 35 Feb 10 12:50 /opt/homebrew/bin/ffmpeg -> ../Cellar/ffmpeg/5.1.2_4/bin/ffmpeg



-
Node.js readable maximize throughput/performance for compute intense readable - Writable doesn't pull data fast enough
31 décembre 2022, par flohallGeneral setup


I developed an application using AWS Lambda node.js 14.
I use a custom
Readable
implementationFrameCreationStream
that uses node-canvas to draw images, svgs and more on a canvas. This result is then extracted as a raw image buffer in BGRA. A single image buffer contains 1920 * 1080 * 4 Bytes = 8294400 Bytes 8 MB.
This is then piped tostdin
of achild_process
runningffmpeg
.
ThehighWaterMark
of myReadable
inobjectMode:true
is set to 25 so that the internal buffer can use up to 8 MB * 25 = 200 MB.

All this works fine and also doesn't contain too much RAM. But I noticed after some time, that the performance is not ideally.


Performance not optimal


I have an example input that generates a video of 315 frames. If I set
highWaterMark
to a value above 25 the performance increases to the point, when I set to a value of 315 or above.

For some reason
ffmpeg
doesn't start to pull any data untilhighWaterMark
is reached. Obviously thats not what I want.ffmpeg
should always consume data if minimum 1 frame is cached in theReadable
and if it has finished processing the frame before. And theReadable
should produce more frames as longhighWaterMark
isn't reached or the last frame has been reached. So ideally theReadable
and theWriteable
are busy all the time.

I found another way to improve the speed. If I add a timeout in the
_read()
method of theReadable
after let's say every tenth frame for 100 ms. Then theffmpeg
-Writable
will use this timeout to write some frames toffmpeg
.

It seems like frames aren't passed to
ffmpeg
during frame creation because some node.js main thread is busy ?

The fastest result I have if I increase
highWaterMark
above the amount of frames - which doesn't work for longer videos as this would make the AWS Lambda RAM explode. And this makes the whole streaming idea useless. Using timeouts always gives me stomach pain. Also depending on the execution on different environments a good fitting timeout might differ. Any ideas ?

FrameCreationStream


import canvas from 'canvas';
import {Readable} from 'stream';
import {IMAGE_STREAM_BUFFER_SIZE, PerformanceUtil, RenderingLibraryError, VideoRendererInput} from 'vm-rendering-backend-commons';
import {AnimationAssets, BufferType, DrawingService, FullAnimationData} from 'vm-rendering-library';

/**
 * This is a proper back pressure compatible implementation of readable for a having a stream to read single frames from.
 * Whenever read() is called a new frame is created and added to the stream.
 * read() will be called internally until options.highWaterMark has been reached.
 * then calling read will be paused until one frame is read from the stream.
 */
export class FrameCreationStream extends Readable {

 drawingService: DrawingService;
 endFrameIndex: number;
 currentFrameIndex: number = 0;
 startFrameIndex: number;
 frameTimer: [number, number];
 readTimer: [number, number];
 fullAnimationData: FullAnimationData;

 constructor(animationAssets: AnimationAssets, fullAnimationData: FullAnimationData, videoRenderingInput: VideoRendererInput, frameTimer: [number, number]) {
 super({highWaterMark: IMAGE_STREAM_BUFFER_SIZE, objectMode: true});

 this.frameTimer = frameTimer;
 this.readTimer = PerformanceUtil.startTimer();

 this.fullAnimationData = fullAnimationData;

 this.startFrameIndex = Math.floor(videoRenderingInput.startFrameId);
 this.currentFrameIndex = this.startFrameIndex;
 this.endFrameIndex = Math.floor(videoRenderingInput.endFrameId);

 this.drawingService = new DrawingService(animationAssets, fullAnimationData, videoRenderingInput, canvas);
 console.time("read");
 }

 /**
 * this method is only overwritten for debugging
 * @param size
 */
 read(size?: number): string | Buffer {

 console.log("read("+size+")");
 const buffer = super.read(size);
 console.log(buffer);
 console.log(buffer?.length);
 if(buffer) {
 console.timeLog("read");
 }
 return buffer;
 }

 // _read() will be called when the stream wants to pull more data in.
 // _read() will be called again after each call to this.push(dataChunk) once the stream is ready to accept more data. https://nodejs.org/api/stream.html#readable_readsize
 // this way it is ensured, that even though this.createImageBuffer() is async, only one frame is created at a time and the order is kept
 _read(): void {
 // as frame numbers are consecutive and unique, we have to draw each frame number (also the first and the last one)
 if (this.currentFrameIndex <= this.endFrameIndex) {
 PerformanceUtil.logTimer(this.readTimer, 'WAIT -> READ\t');
 this.createImageBuffer()
 .then(buffer => this.optionalTimeout(buffer))
 // push means adding a buffered raw frame to the stream
 .then((buffer: Buffer) => {
 this.readTimer = PerformanceUtil.startTimer();
 // the following two frame numbers start with 1 as first value
 const processedFrameNumberOfScene = 1 + this.currentFrameIndex - this.startFrameIndex;
 const totalFrameNumberOfScene = 1 + this.endFrameIndex - this.startFrameIndex;
 // the overall frameId or frameIndex starts with frameId 0
 const processedFrameIndex = this.currentFrameIndex;
 this.currentFrameIndex++;
 this.push(buffer); // nothing besides logging should happen after calling this.push(buffer)
 console.log(processedFrameNumberOfScene + ' of ' + totalFrameNumberOfScene + ' processed - full video frameId: ' + processedFrameIndex + ' - buffered frames: ' + this.readableLength);
 })
 .catch(err => {
 // errors will be finally handled, when subscribing to frameCreation stream in ffmpeg service
 // this log is just generated for tracing errors and if for some reason the handling in ffmpeg service doesn't work
 console.log("createImageBuffer: ", err);
 this.emit("error", err);
 });
 } else {
 // push(null) makes clear that this stream has ended
 this.push(null);
 PerformanceUtil.logTimer(this.frameTimer, 'FRAME_STREAM');
 }
 }

 private optionalTimeout(buffer: Buffer): Promise<buffer> {
 if(this.currentFrameIndex % 10 === 0) {
 return new Promise(resolve => setTimeout(() => resolve(buffer), 140));
 }
 return Promise.resolve(buffer);
 }

 // prevent memory leaks - without this lambda memory will increase with every call
 _destroy(): void {
 this.drawingService.destroyStage();
 }

 /**
 * This creates a raw pixel buffer that contains a single frame of the video drawn by the rendering library
 *
 */
 public async createImageBuffer(): Promise<buffer> {

 const drawTimer = PerformanceUtil.startTimer();
 try {
 await this.drawingService.drawForFrame(this.currentFrameIndex);
 } catch (err: any) {
 throw new RenderingLibraryError(err);
 }

 PerformanceUtil.logTimer(drawTimer, 'DRAW -> FRAME\t');

 const bufferTimer = PerformanceUtil.startTimer();
 // Creates a raw pixel buffer, containing simple binary data
 // the exact same information (BGRA/screen ratio) has to be provided to ffmpeg, because ffmpeg cannot detect format for raw input
 const buffer = await this.drawingService.toBuffer(BufferType.RAW);
 PerformanceUtil.logTimer(bufferTimer, 'CANVAS -> BUFFER');

 return buffer;
 }
}
</buffer></buffer>


FfmpegService


import {ChildProcess, execFile} from 'child_process';
import {Readable} from 'stream';
import {FPS, StageSize} from 'vm-rendering-library';
import {
 FfmpegError,
 LOCAL_MERGE_VIDEOS_TEXT_FILE, LOCAL_SOUND_FILE_PATH,
 LOCAL_VIDEO_FILE_PATH,
 LOCAL_VIDEO_SOUNDLESS_MERGE_FILE_PATH
} from "vm-rendering-backend-commons";

/**
 * This class bundles all ffmpeg usages for rendering one scene.
 * FFmpeg is a console program which can transcode nearly all types of sounds, images and videos from one to another.
 */
export class FfmpegService {

 ffmpegPath: string = null;


 constructor(ffmpegPath: string) {
 this.ffmpegPath = ffmpegPath;
 }

 /**
 * Convert a stream of raw images into an .mp4 video using the command line program ffmpeg.
 *
 * @param inputStream an input stream containing images in raw format BGRA
 * @param stageSize the size of a single frame in pixels (minimum is 2*2)
 * @param outputPath the filepath to write the resulting video to
 */
 public imageToVideo(inputStream: Readable, stageSize: StageSize, outputPath: string): Promise<void> {
 const args: string[] = [
 '-f',
 'rawvideo',
 '-r',
 `${FPS}`,
 '-pix_fmt',
 'bgra',
 '-s',
 `${stageSize.width}x${stageSize.height}`,
 '-i',
 // input "-" means input will be passed via pipe (streamed)
 '-',
 // codec that also QuickTime player can understand
 '-vcodec',
 'libx264',
 '-pix_fmt',
 'yuv420p',
 /*
 * "-movflags faststart":
 * metadata at beginning of file
 * needs more RAM
 * file will be broken, if not finished properly
 * higher application compatibility
 * better for browser streaming
 */
 '-movflags',
 'faststart',
 // "-preset ultrafast", //use this to speed up compression, but quality/compression ratio gets worse
 // don't overwrite an existing file here,
 // but delete file in the beginning of execution index.ts
 // (this is better for local testing believe me)
 outputPath
 ];

 return this.execFfmpegPromise(args, inputStream);
 }

 private execFfmpegPromise(args: string[], inputStream?: Readable): Promise<void> {
 const ffmpegServiceSelf = this;
 return new Promise(function (resolve, reject) {
 const executionProcess: ChildProcess = execFile(ffmpegServiceSelf.ffmpegPath, args, (err) => {
 if (err) {
 reject(new FfmpegError(err));
 } else {
 console.log('ffmpeg finished');
 resolve();
 }
 });
 if (inputStream) {
 // it's important to listen on errors of input stream before piping it into the write stream
 // if we don't do this here, we get an unhandled promise exception for every issue in the input stream
 inputStream.on("error", err => {
 reject(err);
 });
 // don't reject promise here as the error will also be thrown inside execFile and will contain more debugging info
 // this log is just generated for tracing errors and if for some reason the handling in execFile doesn't work
 inputStream.pipe(executionProcess.stdin).on("error", err => console.log("pipe stream: " , err));
 }
 });
 }
}
</void></void>