Recherche avancée

Médias (0)

Mot : - Tags -/auteurs

Aucun média correspondant à vos critères n’est disponible sur le site.

Autres articles (55)

  • Contribute to documentation

    13 avril 2011

    Documentation is vital to the development of improved technical capabilities.
    MediaSPIP welcomes documentation by users as well as developers - including : critique of existing features and functions articles contributed by developers, administrators, content producers and editors screenshots to illustrate the above translations of existing documentation into other languages
    To contribute, register to the project users’ mailing (...)

  • Ajouter notes et légendes aux images

    7 février 2011, par

    Pour pouvoir ajouter notes et légendes aux images, la première étape est d’installer le plugin "Légendes".
    Une fois le plugin activé, vous pouvez le configurer dans l’espace de configuration afin de modifier les droits de création / modification et de suppression des notes. Par défaut seuls les administrateurs du site peuvent ajouter des notes aux images.
    Modification lors de l’ajout d’un média
    Lors de l’ajout d’un média de type "image" un nouveau bouton apparait au dessus de la prévisualisation (...)

  • Encoding and processing into web-friendly formats

    13 avril 2011, par

    MediaSPIP automatically converts uploaded files to internet-compatible formats.
    Video files are encoded in MP4, Ogv and WebM (supported by HTML5) and MP4 (supported by Flash).
    Audio files are encoded in MP3 and Ogg (supported by HTML5) and MP3 (supported by Flash).
    Where possible, text is analyzed in order to retrieve the data needed for search engine detection, and then exported as a series of image files.
    All uploaded files are stored online in their original format, so you can (...)

Sur d’autres sites (8715)

  • Why does My Discord bot stop playing music

    27 septembre 2021, par Konglnwza

    So My Discord bot will be able to play music for a while then it will stop and i have to restart the bot to fix it.
And if it stopped then i use command skip it will crash the bot with the errors below

    


    C:\Users\User\Desktop\Discord bot\Song\play.js:96&#xA;    server_queue.connection.dispatcher.end();&#xA;                                       ^&#xA;&#xA;TypeError: Cannot read property &#x27;end&#x27; of null&#xA;    at skip_song (C:\Users\User\Desktop\Discord bot\Song\play.js:96:40)&#xA;    at Object.execute (C:\Users\User\Desktop\Discord bot\Song\play.js:65:47)&#xA;    at Client.<anonymous> (C:\Users\User\Desktop\Discord bot\bot.js:78:74)&#xA;    at Client.emit (node:events:394:28)&#xA;    at MessageCreateAction.handle (C:\Users\User\Desktop\Discord bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)&#xA;    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\User\Desktop\Discord bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)&#xA;    at WebSocketManager.handlePacket (C:\Users\User\Desktop\Discord bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)&#xA;    at WebSocketShard.onPacket (C:\Users\User\Desktop\Discord bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)&#xA;    at WebSocketShard.onMessage (C:\Users\User\Desktop\Discord bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)&#xA;    at WebSocket.onMessage (C:\Users\User\Desktop\Discord bot\node_modules\ws\lib\event-target.js:132:16)&#xA;</anonymous>

    &#xA;

    I guess the problem is something with ffmpeg or i must have some npms more.

    &#xA;

    npm i already installed

    &#xA;

      &#xA;
    • discord.js
    • &#xA;

    • ytdl-core
    • &#xA;

    • ytdl-search&#xA;and also i already installed ffmpeg in my computer and set the path
    • &#xA;

    &#xA;

    i want to ask that do i have to install any npms more ? or anyone know how to fixed this problem ?

    &#xA;

    const ytdl = require(&#x27;ytdl-core&#x27;);&#xA;const ytSearch = require(&#x27;yt-search&#x27;);&#xA;&#xA;const queue = new Map();&#xA;&#xA;module.exports = {&#xA;    name: &#x27;play&#x27;,&#xA;    aliases: [&#x27;skip&#x27;, &#x27;stop&#x27;, &#x27;queue&#x27;, &#x27;leave&#x27;, &#x27;join&#x27;],&#xA;    description: &#x27;Joins and play&#x27;,&#xA;    async execute(message, args , cmd, client, Discord){&#xA;        const voice_channel = message.member.voice.channel;&#xA;        if(!voice_channel) return message.channel.send(&#x27;เข้าไปอยู่ในดิสก่อนดิวะ :angry: &#x27;);//you must in voice channel&#xA;        &#xA;        &#xA;        const server_queue = queue.get(message.guild.id);&#xA;        if(cmd===&#x27;play&#x27; || cmd===&#x27;p&#x27;){&#xA;            if(!args.length) return message.channel.send(&#x27;จะเปิดอะไรล่ะพี่ :triumph:&#x27;);//you must have argument&#xA;            let song = {};&#xA;&#xA;            if(ytdl.validateURL(args[0])){&#xA;                const song_info = await ytdl.getInfo(args[0]);&#xA;                song = {title: song_info.videoDetails.title, url: song_info.videoDetails.video_url}&#xA;            } else {&#xA;                const videoFinder = async (query) => {&#xA;                    const videoResult = await ytSearch(query);&#xA;                    return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;&#xA;                }&#xA;&#xA;                const video = await videoFinder(args.join(&#x27; &#x27;));&#xA;                if(video){&#xA;                    song = {title: video.title, url: video.url}&#xA;                &#xA;                } else{&#xA;                    message.channel.send(&#x27;หาไม่เจอ :cry: &#x27;);//cant find song&#xA;                }&#xA;            }&#xA;            //const connection = await voiceChannel.join(); &#xA;            if(!server_queue){&#xA;                const queue_constructor = {&#xA;                    voice_channel: voice_channel,&#xA;                    text_channel: message.channel,&#xA;                    connection: null,&#xA;                    songs: []&#xA;                }&#xA;&#xA;                queue.set(message.guild.id, queue_constructor);&#xA;                queue_constructor.songs.push(song);&#xA;&#xA;                try{&#xA;                    const connection = await voice_channel.join();&#xA;                    queue_constructor.connection = connection;&#xA;                    video_player(message.guild, queue_constructor.songs[0]);&#xA;                } catch (err) {&#xA;                    queue.delete(message.guild.id);&#xA;                    message.channel.send(&#x27;error&#x27;);&#xA;                    throw err;&#xA;                }&#xA;            } else{&#xA;                server_queue.songs.push(song);&#xA;                return message.channel.send(`:regional_indicator_k: :regional_indicator_o: :regional_indicator_n: :regional_indicator_g: :star_struck: **${song.title}** ใส่เข้าคิวแล้ว`)//added to queue&#xA;            }&#xA;            &#xA;&#xA;        }&#xA;        else if(cmd === &#x27;skip&#x27; || cmd ===&#x27;s&#x27;) skip_song(message, server_queue);&#xA;        else if(cmd === &#x27;clear&#x27; || cmd===&#x27;c&#x27;) clear_song(message, server_queue);&#xA;        else if(cmd === &#x27;join&#x27;) join_song(message);&#xA;        else if(cmd === &#x27;leave&#x27;) leave_song(message);&#xA;        else if(cmd === &#x27;queue&#x27; || cmd ===&#x27;q&#x27;) queue_show(message,server_queue,Discord);&#xA;&#xA;&#xA;    }&#xA;}&#xA;&#xA;const video_player = async (guild, song) => {&#xA;    const song_queue = queue.get(guild.id);&#xA;&#xA;    if(!song){&#xA;        //song_queue.text_channel.send(&#x27;ไปละบาย :kissing_heart: &#x27;);&#xA;        song_queue.voice_channel.leave();&#xA;        queue.delete(guild.id);&#xA;        return;&#xA;    }&#xA;    const stream = ytdl(song.url,{filter: &#x27;audioonly&#x27;},{ highWaterMark: 1&lt;&lt;25 });&#xA;    song_queue.connection.play(stream, { seek: 0, volume: 0.5 })&#xA;    .on(&#x27;finish&#x27;, () => {&#xA;        song_queue.songs.shift();&#xA;        video_player(guild, song_queue.songs[0]);&#xA;    });&#xA;    await song_queue.text_channel.send(`:regional_indicator_k: :regional_indicator_o: :regional_indicator_n: :regional_indicator_g: :sunglasses: กำลังเล่นเด็ก ***${song.title}***`);//playing song&#xA;}&#xA;&#xA;const skip_song = (message, server_queue) => {&#xA;    if(!message.member.voice.channel) return message.channel.send(&#x27;เข้าดิสก่อนดิ :angry: &#x27;);//you must be in voice channel&#xA;    if(!server_queue) return message.channel.send(&#x27;ไม่มีเพลงในคิวแล้ว :relieved: &#x27;);//no song in queue&#xA;    server_queue.connection.dispatcher.end();&#xA;}&#xA;&#xA;const clear_song = (message, server_queue) => {&#xA;    if(!message.member.voice.channel) return message.channel.send(&#x27;เข้าดิสก่อนดิ :angry: &#x27;);//you must be in voice channel&#xA;    if(!server_queue) return message.channel.send(&#x27;ไม่มีเพลงในคิวแล้ว :relieved: &#x27;);//no song in queue&#xA;    server_queue.songs = [];&#xA;    server_queue.connection.dispatcher.end();&#xA;}&#xA;&#xA;const join_song = (message) => {&#xA;    if(!message.member.voice.channel) return message.channel.send(&#x27;เข้าดิสก่อนดิ :angry: &#x27;);//you must be in voice channel&#xA;    message.member.voice.channel.join();&#xA;}&#xA;&#xA;const leave_song = (message) => {&#xA;    if(!message.member.voice.channel) return message.channel.send(&#x27;เข้าดิสก่อนดิ :angry: &#x27;);//you must be in voice channel&#xA;    message.member.voice.channel.leave();&#xA;}&#xA;&#xA;const queue_show =  (message,server_queue,Discord) => {&#xA;    if(!server_queue) return message.channel.send(&#x27;ไม่มีเพลงในคิวแล้ว :relieved: &#x27;);//no song in queue&#xA;    const queueList = server_queue.songs.map((song, i) => `[${&#x2B;&#x2B;i}] - ${song.title}`);&#xA;    const queueEmbed = new Discord.MessageEmbed()&#xA;    .setDescription(queueList);&#xA;    message.channel.send(queueEmbed);&#xA;}```&#xA;

    &#xA;

  • record mediasoup RTP stream using FFmpeg for Firefox

    30 juillet 2024, par Hadi Aghandeh

    I am trying to record WebRTC stream using mediasoup. I could record successfully on chrome and safari 13/14/15. However on Firefox the does not work.

    &#xA;

    Client side code is a vue js component which gets rtp-compabilities using socket.io and create producers after the server creates the transports. This works good on chrome and safari.

    &#xA;

    const { connect , createLocalTracks } = require(&#x27;twilio-video&#x27;);&#xA;const SocketClient = require("socket.io-client");&#xA;const SocketPromise = require("socket.io-promise").default;&#xA;const MediasoupClient = require("mediasoup-client");&#xA;&#xA;export default {&#xA;    data() {&#xA;        return {&#xA;            errors: [],&#xA;            isReady: false,&#xA;            isRecording: false,&#xA;            loading: false,&#xA;            sapio: {&#xA;                token: null,&#xA;                connectionId: 0&#xA;            },&#xA;            server: {&#xA;                host: &#x27;https://rtc.test&#x27;,&#xA;                ws: &#x27;/server&#x27;,&#xA;                socket: null,&#xA;            },&#xA;            peer: {},&#xA;        }&#xA;    },&#xA;    mounted() {&#xA;        this.init();&#xA;    },&#xA;    methods: {&#xA;        async init() {&#xA;            await this.startCamera();&#xA;&#xA;            if (this.takeId) {&#xA;                await this.recordBySapioServer();&#xA;            }&#xA;        },&#xA;        startCamera() {&#xA;            return new Promise( (resolve, reject) => {&#xA;                if (window.videoMediaStreamObject) {&#xA;                    this.setVideoElementStream(window.videoMediaStreamObject);&#xA;                    resolve();&#xA;                } else {&#xA;                    // Get user media as required&#xA;                    try {&#xA;                        this.localeStream = navigator.mediaDevices.getUserMedia({&#xA;                            audio: true,&#xA;                            video: true,&#xA;                        }).then((stream) => {&#xA;                            this.setVideoElementStream(stream);&#xA;                            resolve();&#xA;                        })&#xA;                    } catch (err) {&#xA;                        console.error(err);&#xA;                        reject();&#xA;                    }&#xA;                }&#xA;            })&#xA;        },&#xA;        setVideoElementStream(stream) {&#xA;            this.localStream = stream;&#xA;            this.$refs.video.srcObject = stream;&#xA;            this.$refs.video.muted = true;&#xA;            this.$refs.video.play().then((video) => {&#xA;                this.isStreaming = true;&#xA;                this.height = this.$refs.video.videoHeight;&#xA;                this.width = this.$refs.video.videoWidth;&#xA;            });&#xA;        },&#xA;        // first thing we need is connecting to websocket&#xA;        connectToSocket() {&#xA;            const serverUrl = this.server.host;&#xA;            console.log("Connect with sapio rtc server:", serverUrl);&#xA;&#xA;            const socket = SocketClient(serverUrl, {&#xA;                path:  this.server.ws,&#xA;                transports: ["websocket"],&#xA;            });&#xA;            this.socket = socket;&#xA;&#xA;            socket.on("connect", () => {&#xA;                console.log("WebSocket connected");&#xA;                // we ask for rtp-capabilities from server to send to us&#xA;                socket.emit(&#x27;send-rtp-capabilities&#x27;);&#xA;            });&#xA;&#xA;            socket.on("error", (err) => {&#xA;                this.loading = true;&#xA;                console.error("WebSocket error:", err);&#xA;            });&#xA;&#xA;            socket.on("router-rtp-capabilities", async (msg) => {&#xA;                const { routerRtpCapabilities, sessionId, externalId } = msg;&#xA;                console.log(&#x27;[rtpCapabilities:%o]&#x27;, routerRtpCapabilities);&#xA;                this.routerRtpCapabilities = routerRtpCapabilities;&#xA;&#xA;                try {&#xA;                    const device = new MediasoupClient.Device();&#xA;                    // Load the mediasoup device with the router rtp capabilities gotten from the server&#xA;                    await device.load({ routerRtpCapabilities });&#xA;&#xA;                    this.peer.sessionId = sessionId;&#xA;                    this.peer.externalId = externalId;&#xA;                    this.peer.device = device;&#xA;&#xA;                    this.createTransport();&#xA;                } catch (error) {&#xA;                    console.error(&#x27;failed to init device [error:%o]&#x27;, error);&#xA;                    socket.disconnect();&#xA;                }&#xA;            });&#xA;&#xA;            socket.on("create-transport", async (msg) => {&#xA;                console.log(&#x27;handleCreateTransportRequest() [data:%o]&#x27;, msg);&#xA;&#xA;                try {&#xA;                    // Create the local mediasoup send transport&#xA;                    this.peer.sendTransport = await this.peer.device.createSendTransport(msg);&#xA;                    console.log(&#x27;send transport created [id:%s]&#x27;, this.peer.sendTransport.id);&#xA;&#xA;                    // Set the transport listeners and get the users media stream&#xA;                    this.handleSendTransportListeners();&#xA;                    this.setTracks();&#xA;                    this.loading = false;&#xA;                } catch (error) {&#xA;                    console.error(&#x27;failed to create transport [error:%o]&#x27;, error);&#xA;                    socket.disconnect();&#xA;                }&#xA;            });&#xA;&#xA;            socket.on("connect-transport", async (msg) => {&#xA;                console.log(&#x27;handleTransportConnectRequest()&#x27;);&#xA;                try {&#xA;                    const action = this.connectTransport;&#xA;&#xA;                    if (!action) {&#xA;                        throw new Error(&#x27;transport-connect action was not found&#x27;);&#xA;                    }&#xA;&#xA;                    await action(msg);&#xA;                } catch (error) {&#xA;                    console.error(&#x27;ailed [error:%o]&#x27;, error);&#xA;                }&#xA;            });&#xA;&#xA;            socket.on("produce", async (msg) => {&#xA;                console.log(&#x27;handleProduceRequest()&#x27;);&#xA;                try {&#xA;                    if (!this.produce) {&#xA;                        throw new Error(&#x27;produce action was not found&#x27;);&#xA;                    }&#xA;                    await this.produce(msg);&#xA;                } catch (error) {&#xA;                    console.error(&#x27;failed [error:%o]&#x27;, error);&#xA;                }&#xA;            });&#xA;&#xA;            socket.on("recording", async (msg) => {&#xA;                this.isRecording = true;&#xA;            });&#xA;&#xA;            socket.on("recording-error", async (msg) => {&#xA;                this.isRecording = false;&#xA;                console.error(msg);&#xA;            });&#xA;&#xA;            socket.on("recording-closed", async (msg) => {&#xA;                this.isRecording = false;&#xA;                console.warn(msg)&#xA;            });&#xA;&#xA;        },&#xA;        createTransport() {&#xA;            console.log(&#x27;createTransport()&#x27;);&#xA;&#xA;            if (!this.peer || !this.peer.device.loaded) {&#xA;                throw new Error(&#x27;Peer or device is not initialized&#x27;);&#xA;            }&#xA;&#xA;            // First we must create the mediasoup transport on the server side&#xA;            this.socket.emit(&#x27;create-transport&#x27;,{&#xA;                sessionId: this.peer.sessionId&#xA;            });&#xA;        },&#xA;        handleSendTransportListeners() {&#xA;            this.peer.sendTransport.on(&#x27;connect&#x27;, this.handleTransportConnectEvent);&#xA;            this.peer.sendTransport.on(&#x27;produce&#x27;, this.handleTransportProduceEvent);&#xA;            this.peer.sendTransport.on(&#x27;connectionstatechange&#x27;, connectionState => {&#xA;                console.log(&#x27;send transport connection state change [state:%s]&#x27;, connectionState);&#xA;            });&#xA;        },&#xA;        handleTransportConnectEvent({ dtlsParameters }, callback, errback) {&#xA;            console.log(&#x27;handleTransportConnectEvent()&#x27;);&#xA;            try {&#xA;                this.connectTransport = (msg) => {&#xA;                    console.log(&#x27;connect-transport action&#x27;);&#xA;                    callback();&#xA;                    this.connectTransport = null;&#xA;                };&#xA;&#xA;                this.socket.emit(&#x27;connect-transport&#x27;,{&#xA;                    sessionId: this.peer.sessionId,&#xA;                    transportId: this.peer.sendTransport.id,&#xA;                    dtlsParameters&#xA;                });&#xA;&#xA;            } catch (error) {&#xA;                console.error(&#x27;handleTransportConnectEvent() failed [error:%o]&#x27;, error);&#xA;                errback(error);&#xA;            }&#xA;        },&#xA;        handleTransportProduceEvent({ kind, rtpParameters }, callback, errback)  {&#xA;            console.log(&#x27;handleTransportProduceEvent()&#x27;);&#xA;            try {&#xA;                this.produce = jsonMessage => {&#xA;                    console.log(&#x27;handleTransportProduceEvent callback [data:%o]&#x27;, jsonMessage);&#xA;                    callback({ id: jsonMessage.id });&#xA;                    this.produce = null;&#xA;                };&#xA;&#xA;                this.socket.emit(&#x27;produce&#x27;, {&#xA;                    sessionId: this.peer.sessionId,&#xA;                    transportId: this.peer.sendTransport.id,&#xA;                    kind,&#xA;                    rtpParameters&#xA;                });&#xA;            } catch (error) {&#xA;                console.error(&#x27;handleTransportProduceEvent() failed [error:%o]&#x27;, error);&#xA;                errback(error);&#xA;            }&#xA;        },&#xA;        async recordBySapioServer() {&#xA;            this.loading = true;&#xA;            this.connectToSocket();&#xA;        },&#xA;        async setTracks() {&#xA;            // Start mediasoup-client&#x27;s WebRTC producers&#xA;            const audioTrack = this.localStream.getAudioTracks()[0];&#xA;            this.peer.audioProducer = await this.peer.sendTransport.produce({&#xA;                track: audioTrack,&#xA;                codecOptions :&#xA;                    {&#xA;                        opusStereo : 1,&#xA;                        opusDtx    : 1&#xA;                    }&#xA;            });&#xA;&#xA;&#xA;            let encodings;&#xA;            let codec;&#xA;            const codecOptions = {videoGoogleStartBitrate : 1000};&#xA;&#xA;            codec = this.peer.device.rtpCapabilities.codecs.find((c) => c.kind.toLowerCase() === &#x27;video&#x27;);&#xA;            if (codec.mimeType.toLowerCase() === &#x27;video/vp9&#x27;) {&#xA;                encodings = { scalabilityMode: &#x27;S3T3_KEY&#x27; };&#xA;            } else {&#xA;                encodings = [&#xA;                    { scaleResolutionDownBy: 4, maxBitrate: 500000 },&#xA;                    { scaleResolutionDownBy: 2, maxBitrate: 1000000 },&#xA;                    { scaleResolutionDownBy: 1, maxBitrate: 5000000 }&#xA;                ];&#xA;            }&#xA;            const videoTrack = this.localStream.getVideoTracks()[0];&#xA;            this.peer.videoProducer =await this.peer.sendTransport.produce({&#xA;                track: videoTrack,&#xA;                encodings,&#xA;                codecOptions,&#xA;                codec&#xA;            });&#xA;&#xA;        },&#xA;        startRecording() {&#xA;            this.Q.answer.recordingId = this.peer.externalId;&#xA;            this.socket.emit("start-record", {&#xA;                sessionId: this.peer.sessionId&#xA;            });&#xA;        },&#xA;        stopRecording() {&#xA;            this.socket.emit("stop-record" , {&#xA;                sessionId: this.peer.sessionId&#xA;            });&#xA;        },&#xA;    },&#xA;&#xA;}&#xA;&#xA;&#xA;&#xA;

    &#xA;

    console.log of my ffmpeg process :

    &#xA;

    // sdp string&#xA;[sdpString:v=0&#xA;  o=- 0 0 IN IP4 127.0.0.1&#xA;  s=FFmpeg&#xA;  c=IN IP4 127.0.0.1&#xA;  t=0 0&#xA;  m=video 25549 RTP/AVP 101 &#xA;  a=rtpmap:101 VP8/90000&#xA;  a=sendonly&#xA;  m=audio 26934 RTP/AVP 100 &#xA;  a=rtpmap:100 opus/48000/2&#xA;  a=sendonly&#xA;  ]&#xA;&#xA;// ffmpeg args&#xA;commandArgs:[&#xA;  &#x27;-loglevel&#x27;,&#xA;  &#x27;debug&#x27;,&#xA;  &#x27;-protocol_whitelist&#x27;,&#xA;  &#x27;pipe,udp,rtp&#x27;,&#xA;  &#x27;-fflags&#x27;,&#xA;  &#x27;&#x2B;genpts&#x27;,&#xA;  &#x27;-f&#x27;,&#xA;  &#x27;sdp&#x27;,&#xA;  &#x27;-i&#x27;,&#xA;  &#x27;pipe:0&#x27;,&#xA;  &#x27;-map&#x27;,&#xA;  &#x27;0:v:0&#x27;,&#xA;  &#x27;-c:v&#x27;,&#xA;  &#x27;copy&#x27;,&#xA;  &#x27;-map&#x27;,&#xA;  &#x27;0:a:0&#x27;,&#xA;  &#x27;-strict&#x27;,&#xA;  &#x27;-2&#x27;,&#xA;  &#x27;-c:a&#x27;,&#xA;  &#x27;copy&#x27;,&#xA;  &#x27;-f&#x27;,&#xA;  &#x27;webm&#x27;,&#xA;  &#x27;-flags&#x27;,&#xA;  &#x27;&#x2B;global_header&#x27;,&#xA;  &#x27;-y&#x27;,&#xA;  &#x27;storage/recordings/26e63cb3-4f81-499e-941a-c0bb7f7f52ce.webm&#x27;,&#xA;  [length]: 26&#xA;]&#xA;// ffmpeg log&#xA;ffmpeg::process::data [data:&#x27;ffmpeg version n4.4&#x27;]&#xA;ffmpeg::process::data [data:&#x27; Copyright (c) 2000-2021 the FFmpeg developers&#x27;]&#xA;ffmpeg::process::data [data:&#x27;\n&#x27;]&#xA;ffmpeg::process::data [data:&#x27;  built with gcc 11.1.0 (GCC)\n&#x27;]&#xA;ffmpeg::process::data [data:&#x27;  configuration: --prefix=/usr --disable-debug --disable-static --disable-stripping --enable-amf --enable-avisynth --enable-cuda-llvm --enable-lto --enable-fontconfig --enable-gmp --enable-gnutls --enable-gpl --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libdav1d --enable-libdrm --enable-libfreetype --enable-libfribidi --enable-libgsm --enable-libiec61883 --enable-libjack --enable-libmfx --enable-libmodplug --enable-libmp3lame --enable-libopencore_amrnb --enable-libopencore_amrwb --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librav1e --enable-librsvg --enable-libsoxr --enable-libspeex --enable-libsrt --enable-libssh --enable-libsvtav1 --enable-libtheora --enable-libv4l2 --enable-libvidstab --enable-libvmaf --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxcb --enable-libxml2 --enable-libxvid --enable-libzimg --enable-nvdec --enable-nvenc --enable-shared --enable-version3\n&#x27;]&#xA;ffmpeg::process::data [data:&#x27;  libavutil      56. 70.100 / 56. 70.100\n&#x27; &#x2B;&#xA;  &#x27;  libavcodec     58.134.100 / 58.134.100\n&#x27; &#x2B;&#xA;  &#x27;  libavformat    58. 76.100 / 58. 76.100\n&#x27; &#x2B;&#xA;  &#x27;  libavdevice    58. 13.100 / 58. 13.100\n&#x27; &#x2B;&#xA;  &#x27;  libavfilter     7.110.100 /  7.110.100\n&#x27; &#x2B;&#xA;  &#x27;  libswscale      5.  9.100 /  5.  9.100\n&#x27; &#x2B;&#xA;  &#x27;  libswresample   3.  9.100 /  3.  9.100\n&#x27; &#x2B;&#xA;  &#x27;  libpostproc    55.  9.100 / 55.  9.100\n&#x27; &#x2B;&#xA;  &#x27;Splitting the commandline.\n&#x27; &#x2B;&#xA;  "Reading option &#x27;-loglevel&#x27; ... matched as option &#x27;loglevel&#x27; (set logging level) with argument &#x27;debug&#x27;.\n" &#x2B;&#xA;  "Reading option &#x27;-protocol_whitelist&#x27; ..."]&#xA;ffmpeg::process::data [data:" matched as AVOption &#x27;protocol_whitelist&#x27; with argument &#x27;pipe,udp,rtp&#x27;.\n" &#x2B;&#xA;  "Reading option &#x27;-fflags&#x27; ..."]&#xA;ffmpeg::process::data [data:" matched as AVOption &#x27;fflags&#x27; with argument &#x27;&#x2B;genpts&#x27;.\n" &#x2B;&#xA;  "Reading option &#x27;-f&#x27; ... matched as option &#x27;f&#x27; (force format) with argument &#x27;sdp&#x27;.\n" &#x2B;&#xA;  "Reading option &#x27;-i&#x27; ... matched as input url with argument &#x27;pipe:0&#x27;.\n" &#x2B;&#xA;  "Reading option &#x27;-map&#x27; ... matched as option &#x27;map&#x27; (set input stream mapping) with argument &#x27;0:v:0&#x27;.\n" &#x2B;&#xA;  "Reading option &#x27;-c:v&#x27; ... matched as option &#x27;c&#x27; (codec name) with argument &#x27;copy&#x27;.\n" &#x2B;&#xA;  "Reading option &#x27;-map&#x27; ... matched as option &#x27;map&#x27; (set input stream mapping) with argument &#x27;0:a:0&#x27;.\n" &#x2B;&#xA;  "Reading option &#x27;-strict&#x27; ...Routing option strict to both codec and muxer layer\n" &#x2B;&#xA;  " matched as AVOption &#x27;strict&#x27; with argument &#x27;-2&#x27;.\n" &#x2B;&#xA;  "Reading option &#x27;-c:a&#x27; ... matched as option &#x27;c&#x27; (codec name) with argument &#x27;copy&#x27;.\n" &#x2B;&#xA;  "Reading option &#x27;-f&#x27; ... matched as option &#x27;f&#x27; (force format) with argument &#x27;webm&#x27;.\n" &#x2B;&#xA;  "Reading option &#x27;-flags&#x27; ... matched as AVOption &#x27;flags&#x27; with argument &#x27;&#x2B;global_header&#x27;.\n" &#x2B;&#xA;  "Reading option &#x27;-y&#x27; ... matched as option &#x27;y&#x27; (overwrite output files) with argument &#x27;1&#x27;.\n" &#x2B;&#xA;  "Reading option &#x27;storage/recordings/26e63cb3-4f81-499e-941a-c0bb7f7f52ce.webm&#x27; ... matched as output url.\n" &#x2B;&#xA;  &#x27;Finished splitting the commandline.\n&#x27; &#x2B;&#xA;  &#x27;Parsing a group of options: global .\n&#x27; &#x2B;&#xA;  &#x27;Applying option loglevel (set logging level) with argument debug.\n&#x27; &#x2B;&#xA;  &#x27;Applying option y (overwrite output files) with argument 1.\n&#x27; &#x2B;&#xA;  &#x27;Successfully parsed a group of options.\n&#x27; &#x2B;&#xA;  &#x27;Parsing a group of options: input url pipe:0.\n&#x27; &#x2B;&#xA;  &#x27;Applying option f (force format) with argument sdp.\n&#x27; &#x2B;&#xA;  &#x27;Successfully parsed a group of options.\n&#x27; &#x2B;&#xA;  &#x27;Opening an input file: pipe:0.\n&#x27; &#x2B;&#xA;  "[sdp @ 0x55604dc58400] Opening &#x27;pipe:0&#x27; for reading\n" &#x2B;&#xA;  &#x27;[sdp @ 0x55604dc58400] video codec set to: vp8\n&#x27; &#x2B;&#xA;  &#x27;[sdp @ 0x55604dc58400] audio codec set to: opus\n&#x27; &#x2B;&#xA;  &#x27;[sdp @ 0x55604dc58400] audio samplerate set to: 48000\n&#x27; &#x2B;&#xA;  &#x27;[sdp @ 0x55604dc58400] audio channels set to: 2\n&#x27; &#x2B;&#xA;  &#x27;[udp @ 0x55604dc6c500] end receive buffer size reported is 425984\n&#x27; &#x2B;&#xA;  &#x27;[udp @ 0x55604dc6c7c0] end receive buffer size reported is 425984\n&#x27; &#x2B;&#xA;  &#x27;[sdp @ 0x55604dc58400] setting jitter buffer size to 500\n&#x27; &#x2B;&#xA;  &#x27;[udp @ 0x55604dc6d900] end receive buffer size reported is 425984\n&#x27; &#x2B;&#xA;  &#x27;[udp @ 0x55604dc6d2c0] end receive buffer size reported is 425984\n&#x27; &#x2B;&#xA;  &#x27;[sdp @ 0x55604dc58400] setting jitter buffer size to 500\n&#x27;]&#xA;ffmpeg::process::data [data:&#x27;[sdp @ 0x55604dc58400] Before avformat_find_stream_info() pos: 210 bytes read:210 seeks:0 nb_streams:2\n&#x27;]&#xA;  **mediasoup:Consumer resume() &#x2B;1s**&#xA;  **mediasoup:Channel request() [method:consumer.resume, id:12] &#x2B;1s**&#xA;  **mediasoup:Channel request succeeded [method:consumer.resume, id:12] &#x2B;0ms**&#xA;  **mediasoup:Consumer resume() &#x2B;1ms**&#xA;  **mediasoup:Channel request() [method:consumer.resume, id:13] &#x2B;0ms**&#xA;  **mediasoup:Channel request succeeded [method:consumer.resume, id:13] &#x2B;0ms**&#xA;ffmpeg::process::data [data:&#x27;[sdp @ 0x55604dc58400] Could not find codec parameters for stream 0 (Video: vp8, 1 reference frame, yuv420p): unspecified size\n&#x27; &#x2B;&#xA;  "Consider increasing the value for the &#x27;analyzeduration&#x27; (0) and &#x27;probesize&#x27; (5000000) options\n"]&#xA;ffmpeg::process::data [data:&#x27;[sdp @ 0x55604dc58400] After avformat_find_stream_info() pos: 210 bytes read:210 seeks:0 frames:0\n&#x27; &#x2B;&#xA;  "Input #0, sdp, from &#x27;pipe:0&#x27;:\n" &#x2B;&#xA;  &#x27;  Metadata:\n&#x27; &#x2B;&#xA;  &#x27;    title           : FFmpeg\n&#x27; &#x2B;&#xA;  &#x27;  Duration: N/A, bitrate: N/A\n&#x27; &#x2B;&#xA;  &#x27;  Stream #0:0, 0, 1/90000: Video: vp8, 1 reference frame, yuv420p, 90k tbr, 90k tbn, 90k tbc\n&#x27; &#x2B;&#xA;  &#x27;  Stream #0:1, 0, 1/48000: Audio: opus, 48000 Hz, stereo, fltp\n&#x27; &#x2B;&#xA;  &#x27;Successfully opened the file.\n&#x27; &#x2B;&#xA;  &#x27;Parsing a group of options: output url storage/recordings/26e63cb3-4f81-499e-941a-c0bb7f7f52ce.webm.\n&#x27; &#x2B;&#xA;  &#x27;Applying option map (set input stream mapping) with argument 0:v:0.\n&#x27; &#x2B;&#xA;  &#x27;Applying option c:v (codec name) with argument copy.\n&#x27; &#x2B;&#xA;  &#x27;Applying option map (set input stream mapping) with argument 0:a:0.\n&#x27; &#x2B;&#xA;  &#x27;Applying option c:a (codec name) with argument copy.\n&#x27; &#x2B;&#xA;  &#x27;Applying option f (force format) with argument webm.\n&#x27; &#x2B;&#xA;  &#x27;Successfully parsed a group of options.\n&#x27; &#x2B;&#xA;  &#x27;Opening an output file: storage/recordings/26e63cb3-4f81-499e-941a-c0bb7f7f52ce.webm.\n&#x27; &#x2B;&#xA;  "[file @ 0x55604dce5bc0] Setting default whitelist &#x27;file,crypto,data&#x27;\n"]&#xA;ffmpeg::process::data [data:&#x27;Successfully opened the file.\n&#x27; &#x2B;&#xA;  &#x27;[webm @ 0x55604dce0fc0] dimensions not set\n&#x27; &#x2B;&#xA;  &#x27;Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument\n&#x27; &#x2B;&#xA;  &#x27;Error initializing output stream 0:1 -- \n&#x27; &#x2B;&#xA;  &#x27;Stream mapping:\n&#x27; &#x2B;&#xA;  &#x27;  Stream #0:0 -> #0:0 (copy)\n&#x27; &#x2B;&#xA;  &#x27;  Stream #0:1 -> #0:1 (copy)\n&#x27; &#x2B;&#xA;  &#x27;    Last message repeated 1 times\n&#x27; &#x2B;&#xA;  &#x27;[AVIOContext @ 0x55604dc6dcc0] Statistics: 0 seeks, 0 writeouts\n&#x27; &#x2B;&#xA;  &#x27;[AVIOContext @ 0x55604dc69380] Statistics: 210 bytes read, 0 seeks\n&#x27;]&#xA;ffmpeg::process::close&#xA;&#xA;

    &#xA;

    FFmpeg says dimensions not  set and Could not write header for output file when I use Firefox. This might be enough for understanding the problem, but if you need more information you can read how server side is performing.&#xA;Server-Side in summary can be something like this :&#xA;lets say we initialized worker and router at run time using following functions.

    &#xA;

        // Start the mediasoup workers&#xA;module.exports.initializeWorkers = async () => {&#xA;  const { logLevel, logTags, rtcMinPort, rtcMaxPort } = config.worker;&#xA;&#xA;  console.log(&#x27;initializeWorkers() creating %d mediasoup workers&#x27;, config.numWorkers);&#xA;&#xA;  for (let i = 0; i &lt; config.numWorkers; &#x2B;&#x2B;i) {&#xA;    const worker = await mediasoup.createWorker({&#xA;      logLevel, logTags, rtcMinPort, rtcMaxPort&#xA;    });&#xA;&#xA;    worker.once(&#x27;died&#x27;, () => {&#xA;      console.error(&#x27;worker::died worker has died exiting in 2 seconds... [pid:%d]&#x27;, worker.pid);&#xA;      setTimeout(() => process.exit(1), 2000);&#xA;    });&#xA;&#xA;    workers.push(worker);&#xA;  }&#xA;};&#xA;

    &#xA;

    module.exports.createRouter = async () => {&#xA;  const worker = getNextWorker();&#xA;&#xA;  console.log(&#x27;createRouter() creating new router [worker.pid:%d]&#x27;, worker.pid);&#xA;&#xA;  console.log(`config.router.mediaCodecs:${JSON.stringify(config.router.mediaCodecs)}`)&#xA;&#xA;  return await worker.createRouter({ mediaCodecs: config.router.mediaCodecs });&#xA;};&#xA;

    &#xA;

    We pass router.rtpCompatibilities to the client. clients get the rtpCompatibilities and create a device and loads it. after that a transport must be created at server side.

    &#xA;

        const handleCreateTransportRequest = async (jsonMessage) => {&#xA;&#xA;  const transport = await createTransport(&#x27;webRtc&#x27;, router);&#xA;&#xA;  var peer;&#xA;  try {peer = peers.get(jsonMessage.sessionId);}&#xA;  catch{console.log(&#x27;peer not found&#x27;)}&#xA;  &#xA;  peer.addTransport(transport);&#xA;&#xA;  peer.socket.emit(&#x27;create-transport&#x27;,{&#xA;    id: transport.id,&#xA;    iceParameters: transport.iceParameters,&#xA;    iceCandidates: transport.iceCandidates,&#xA;    dtlsParameters: transport.dtlsParameters&#xA;  });&#xA;};&#xA;

    &#xA;

    Then after the client side also created the transport we listen to connect event an at the time of event, we request the server to create connection.

    &#xA;

    const handleTransportConnectRequest = async (jsonMessage) => {&#xA;  var peer;&#xA;  try {peer = peers.get(jsonMessage.sessionId);}&#xA;  catch{console.log(&#x27;peer not found&#x27;)}&#xA;&#xA;  if (!peer) {&#xA;    throw new Error(`Peer with id ${jsonMessage.sessionId} was not found`);&#xA;  }&#xA;&#xA;  const transport = peer.getTransport(jsonMessage.transportId);&#xA;&#xA;  if (!transport) {&#xA;    throw new Error(`Transport with id ${jsonMessage.transportId} was not found`);&#xA;  }&#xA;&#xA;  await transport.connect({ dtlsParameters: jsonMessage.dtlsParameters });&#xA;  console.log(&#x27;handleTransportConnectRequest() transport connected&#x27;);&#xA;  peer.socket.emit(&#x27;connect-transport&#x27;);&#xA;};&#xA;

    &#xA;

    Similar thing happen on produce event.

    &#xA;

    const handleProduceRequest = async (jsonMessage) => {&#xA;  console.log(&#x27;handleProduceRequest [data:%o]&#x27;, jsonMessage);&#xA;&#xA;  var peer;&#xA;  try {peer = peers.get(jsonMessage.sessionId);}&#xA;  catch{console.log(&#x27;peer not found&#x27;)}&#xA;&#xA;  if (!peer) {&#xA;    throw new Error(`Peer with id ${jsonMessage.sessionId} was not found`);&#xA;  }&#xA;&#xA;  const transport = peer.getTransport(jsonMessage.transportId);&#xA;&#xA;  if (!transport) {&#xA;    throw new Error(`Transport with id ${jsonMessage.transportId} was not found`);&#xA;  }&#xA;&#xA;  const producer = await transport.produce({&#xA;    kind: jsonMessage.kind,&#xA;    rtpParameters: jsonMessage.rtpParameters&#xA;  });&#xA;&#xA;  peer.addProducer(producer);&#xA;&#xA;  console.log(&#x27;handleProducerRequest() new producer added [id:%s, kind:%s]&#x27;, producer.id, producer.kind);&#xA;&#xA;  peer.socket.emit(&#x27;produce&#x27;,{&#xA;    id: producer.id,&#xA;    kind: producer.kind&#xA;  });&#xA;};&#xA;

    &#xA;

    For Recording, first I create plain transports for audio and video producers.

    &#xA;

    const rtpTransport = router.createPlainTransport(config.plainRtpTransport);&#xA;

    &#xA;

    then rtp transport must be connected to ports :

    &#xA;

      await rtpTransport.connect({&#xA;    ip: &#x27;127.0.0.1&#x27;,&#xA;    port: remoteRtpPort,&#xA;    rtcpPort: remoteRtcpPort&#xA;  });&#xA;

    &#xA;

    Then the consumer must also be created.

    &#xA;

      const rtpConsumer = await rtpTransport.consume({&#xA;    producerId: producer.id,&#xA;    rtpCapabilities,&#xA;    paused: true&#xA;  });&#xA;

    &#xA;

    After that we can start recording using following code :

    &#xA;

     this._rtpParameters = args;&#xA;    this._process = undefined;&#xA;    this._observer = new EventEmitter();&#xA;    this._peer = args.peer;&#xA;&#xA;    this._sdpString = createSdpText(this._rtpParameters);&#xA;    this._sdpStream = convertStringToStream(this._sdpString);&#xA;    // create dir&#xA;    const dir = process.env.REOCRDING_PATH ?? &#x27;storage/recordings&#x27;;&#xA;    if (!fs.existsSync(dir)) shelljs.mkdir(&#x27;-p&#x27;, dir);&#xA;  &#xA;    this._extension = &#x27;webm&#x27;;&#xA;    // create file path&#xA;    this._path = `${dir}/${args.peer.sessionId}.${this._extension}`&#xA;    let loop = 0;&#xA;    while(fs.existsSync(this._path)) {&#xA;      this._path = `${dir}/${args.peer.sessionId}-${&#x2B;&#x2B;loop}.${this._extension}`&#xA;    }&#xA;&#xA;this._recordingnModel = await Recording.findOne({sessionIds: { $in: [this._peer.sessionId] }})&#xA;    this._recordingnModel.files.push(this._path);&#xA;    this._recordingnModel.save();&#xA;&#xA;let proc  = ffmpeg(this._sdpStream)&#xA;    .inputOptions([&#xA;      &#x27;-protocol_whitelist&#x27;,&#x27;pipe,udp,rtp&#x27;,&#xA;      &#x27;-f&#x27;,&#x27;sdp&#x27;,&#xA;    ])&#xA;    .format(this._extension)&#xA;    .output(this._path)&#xA;    .size(&#x27;720x?&#x27;)&#xA;    .on(&#x27;start&#x27;, ()=>{&#xA;      this._peer.socket.emit(&#x27;recording&#x27;);&#xA;    })&#xA;    .on(&#x27;end&#x27;, ()=>{&#xA;      let path = this._path.replace(&#x27;storage/recordings/&#x27;, &#x27;&#x27;);&#xA;      this._peer.socket.emit(&#x27;recording-closed&#x27;, {&#xA;        url: `${process.env.APP_URL}/recording/file/${path}`&#xA;      });&#xA;    });&#xA;&#xA;    proc.run();&#xA;    this._process =  proc;&#xA;  }&#xA;&#xA;

    &#xA;

  • audio do not stop recording after pause ffmpeg c++

    15 septembre 2021, par C1ngh10

    I am developing an application that record the screen and the audio from microphone. I implemented the pause function stopping video and audio thread on a condition variable, resuming them with a notify on the same condition variable. This is done in captureAudio(), in the main while. In this way works on macOS and linux, where I use avfoudation and alsa respectively, but on windows, with dshow, keep recording audio during the pause, when the thread is waiting on the condition variable. Does anybody know how can I fix this behaviour ?

    &#xA;

    #include "ScreenRecorder.h"&#xA;&#xA;using namespace std;&#xA;&#xA;ScreenRecorder::ScreenRecorder() : pauseCapture(false), stopCapture(false), started(false), activeMenu(true) {&#xA;    avcodec_register_all();&#xA;    avdevice_register_all();&#xA;&#xA;    width = 1920;&#xA;    height = 1200;&#xA;}&#xA;&#xA;ScreenRecorder::~ScreenRecorder() {&#xA;&#xA;    if (started) {&#xA;        value = av_write_trailer(outAVFormatContext);&#xA;        if (value &lt; 0) {&#xA;            cerr &lt;&lt; "Error in writing av trailer" &lt;&lt; endl;&#xA;            exit(-1);&#xA;        }&#xA;&#xA;        avformat_close_input(&amp;inAudioFormatContext);&#xA;        if(inAudioFormatContext == nullptr){&#xA;            cout &lt;&lt; "inAudioFormatContext close successfully" &lt;&lt; endl;&#xA;        }&#xA;        else{&#xA;            cerr &lt;&lt; "Error: unable to close the inAudioFormatContext" &lt;&lt; endl;&#xA;            exit(-1);&#xA;            //throw "Error: unable to close the file";&#xA;        }&#xA;        avformat_free_context(inAudioFormatContext);&#xA;        if(inAudioFormatContext == nullptr){&#xA;            cout &lt;&lt; "AudioFormat freed successfully" &lt;&lt; endl;&#xA;        }&#xA;        else{&#xA;            cerr &lt;&lt; "Error: unable to free AudioFormatContext" &lt;&lt; endl;&#xA;            exit(-1);&#xA;        }&#xA;        &#xA;        avformat_close_input(&amp;pAVFormatContext);&#xA;        if (pAVFormatContext == nullptr) {&#xA;            cout &lt;&lt; "File close successfully" &lt;&lt; endl;&#xA;        }&#xA;        else {&#xA;            cerr &lt;&lt; "Error: unable to close the file" &lt;&lt; endl;&#xA;            exit(-1);&#xA;            //throw "Error: unable to close the file";&#xA;        }&#xA;&#xA;        avformat_free_context(pAVFormatContext);&#xA;        if (pAVFormatContext == nullptr) {&#xA;            cout &lt;&lt; "VideoFormat freed successfully" &lt;&lt; endl;&#xA;        }&#xA;        else {&#xA;            cerr &lt;&lt; "Error: unable to free VideoFormatContext" &lt;&lt; endl;&#xA;            exit(-1);&#xA;        }&#xA;    }&#xA;}&#xA;&#xA;/*==================================== VIDEO ==============================*/&#xA;&#xA;int ScreenRecorder::openVideoDevice() throw() {&#xA;    value = 0;&#xA;    options = nullptr;&#xA;    pAVFormatContext = nullptr;&#xA;&#xA;    pAVFormatContext = avformat_alloc_context();&#xA;&#xA;    string dimension = to_string(width) &#x2B; "x" &#x2B; to_string(height);&#xA;    av_dict_set(&amp;options, "video_size", dimension.c_str(), 0);   //option to set the dimension of the screen section to record&#xA;&#xA;#ifdef _WIN32&#xA;    pAVInputFormat = av_find_input_format("gdigrab");&#xA;    if (avformat_open_input(&amp;pAVFormatContext, "desktop", pAVInputFormat, &amp;options) != 0) {&#xA;        cerr &lt;&lt; "Couldn&#x27;t open input stream" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;#elif defined linux&#xA;   &#xA;    int offset_x = 0, offset_y = 0;&#xA;    string url = ":0.0&#x2B;" &#x2B; to_string(offset_x) &#x2B; "," &#x2B; to_string(offset_y);  //custom string to set the start point of the screen section&#xA;    pAVInputFormat = av_find_input_format("x11grab");&#xA;    value = avformat_open_input(&amp;pAVFormatContext, url.c_str(), pAVInputFormat, &amp;options);&#xA;&#xA;    if (value != 0) {&#xA;        cerr &lt;&lt; "Error in opening input device (video)" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;#else&#xA;&#xA;    value = av_dict_set(&amp;options, "pixel_format", "0rgb", 0);&#xA;    if (value &lt; 0) {&#xA;        cerr &lt;&lt; "Error in setting pixel format" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;    value = av_dict_set(&amp;options, "video_device_index", "1", 0);&#xA;&#xA;    if (value &lt; 0) {&#xA;        cerr &lt;&lt; "Error in setting video device index" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;    pAVInputFormat = av_find_input_format("avfoundation");&#xA;&#xA;    if (avformat_open_input(&amp;pAVFormatContext, "Capture screen 0:none", pAVInputFormat, &amp;options) != 0) {  //TODO trovare un modo per selezionare sempre lo schermo (forse "Capture screen 0")&#xA;        cerr &lt;&lt; "Error in opening input device" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;&#xA;&#xA;#endif&#xA;    //set frame per second&#xA;&#xA;    value = av_dict_set(&amp;options, "framerate", "30", 0);&#xA;    if (value &lt; 0) {&#xA;        cerr &lt;&lt; "Error in setting dictionary value (setting framerate)" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;    value = av_dict_set(&amp;options, "preset", "medium", 0);&#xA;    if (value &lt; 0) {&#xA;        cerr &lt;&lt; "Error in setting dictionary value (setting preset value)" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;    /*&#xA;    value = av_dict_set(&amp;options, "vsync", "1", 0);&#xA;    if(value &lt; 0){&#xA;        cerr &lt;&lt; "Error in setting dictionary value (setting vsync value)" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;    */&#xA;&#xA;    value = av_dict_set(&amp;options, "probesize", "60M", 0);&#xA;    if (value &lt; 0) {&#xA;        cerr &lt;&lt; "Error in setting probesize value" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;    //get video stream infos from context&#xA;    value = avformat_find_stream_info(pAVFormatContext, nullptr);&#xA;    if (value &lt; 0) {&#xA;        cerr &lt;&lt; "Error in retrieving the stream info" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;    VideoStreamIndx = -1;&#xA;    for (int i = 0; i &lt; pAVFormatContext->nb_streams; i&#x2B;&#x2B;) {&#xA;        if (pAVFormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {&#xA;            VideoStreamIndx = i;&#xA;            break;&#xA;        }&#xA;    }&#xA;    if (VideoStreamIndx == -1) {&#xA;        cerr &lt;&lt; "Error: unable to find video stream index" &lt;&lt; endl;&#xA;        exit(-2);&#xA;    }&#xA;&#xA;    pAVCodecContext = pAVFormatContext->streams[VideoStreamIndx]->codec;&#xA;    pAVCodec = avcodec_find_decoder(pAVCodecContext->codec_id/*params->codec_id*/);&#xA;    if (pAVCodec == nullptr) {&#xA;        cerr &lt;&lt; "Error: unable to find decoder video" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;    cout &lt;&lt; "Insert height and width [h w]: ";   //custom screen dimension to record&#xA;    cin >> h >> w;*/&#xA;&#xA;&#xA;    return 0;&#xA;}&#xA;&#xA;/*==========================================  AUDIO  ============================*/&#xA;&#xA;int ScreenRecorder::openAudioDevice() {&#xA;    audioOptions = nullptr;&#xA;    inAudioFormatContext = nullptr;&#xA;&#xA;    inAudioFormatContext = avformat_alloc_context();&#xA;    value = av_dict_set(&amp;audioOptions, "sample_rate", "44100", 0);&#xA;    if (value &lt; 0) {&#xA;        cerr &lt;&lt; "Error: cannot set audio sample rate" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;    value = av_dict_set(&amp;audioOptions, "async", "1", 0);&#xA;    if (value &lt; 0) {&#xA;        cerr &lt;&lt; "Error: cannot set audio sample rate" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;#if defined linux&#xA;    audioInputFormat = av_find_input_format("alsa");&#xA;    value = avformat_open_input(&amp;inAudioFormatContext, "hw:0", audioInputFormat, &amp;audioOptions);&#xA;    if (value != 0) {&#xA;        cerr &lt;&lt; "Error in opening input device (audio)" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;#endif&#xA;&#xA;#if defined _WIN32&#xA;    audioInputFormat = av_find_input_format("dshow");&#xA;    value = avformat_open_input(&amp;inAudioFormatContext, "audio=Microfono (Realtek(R) Audio)", audioInputFormat, &amp;audioOptions);&#xA;    if (value != 0) {&#xA;        cerr &lt;&lt; "Error in opening input device (audio)" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;#endif&#xA;&#xA;    value = avformat_find_stream_info(inAudioFormatContext, nullptr);&#xA;    if (value != 0) {&#xA;        cerr &lt;&lt; "Error: cannot find the audio stream information" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;    audioStreamIndx = -1;&#xA;    for (int i = 0; i &lt; inAudioFormatContext->nb_streams; i&#x2B;&#x2B;) {&#xA;        if (inAudioFormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {&#xA;            audioStreamIndx = i;&#xA;            break;&#xA;        }&#xA;    }&#xA;    if (audioStreamIndx == -1) {&#xA;        cerr &lt;&lt; "Error: unable to find audio stream index" &lt;&lt; endl;&#xA;        exit(-2);&#xA;    }&#xA;}&#xA;&#xA;int ScreenRecorder::initOutputFile() {&#xA;    value = 0;&#xA;&#xA;    outAVFormatContext = nullptr;&#xA;    outputAVFormat = av_guess_format(nullptr, "output.mp4", nullptr);&#xA;    if (outputAVFormat == nullptr) {&#xA;        cerr &lt;&lt; "Error in guessing the video format, try with correct format" &lt;&lt; endl;&#xA;        exit(-5);&#xA;    }&#xA;    avformat_alloc_output_context2(&amp;outAVFormatContext, outputAVFormat, outputAVFormat->name, "..\\media\\output.mp4");&#xA;    if (outAVFormatContext == nullptr) {&#xA;        cerr &lt;&lt; "Error in allocating outAVFormatContext" &lt;&lt; endl;&#xA;        exit(-4);&#xA;    }&#xA;&#xA;    /*===========================================================================*/&#xA;    this->generateVideoStream();&#xA;    this->generateAudioStream();&#xA;&#xA;    //create an empty video file&#xA;    if (!(outAVFormatContext->flags &amp; AVFMT_NOFILE)) {&#xA;        if (avio_open2(&amp;outAVFormatContext->pb, "..\\media\\output.mp4", AVIO_FLAG_WRITE, nullptr, nullptr) &lt; 0) {&#xA;            cerr &lt;&lt; "Error in creating the video file" &lt;&lt; endl;&#xA;            exit(-10);&#xA;        }&#xA;    }&#xA;&#xA;    if (outAVFormatContext->nb_streams == 0) {&#xA;        cerr &lt;&lt; "Output file does not contain any stream" &lt;&lt; endl;&#xA;        exit(-11);&#xA;    }&#xA;    value = avformat_write_header(outAVFormatContext, &amp;options);&#xA;    if (value &lt; 0) {&#xA;        cerr &lt;&lt; "Error in writing the header context" &lt;&lt; endl;&#xA;        exit(-12);&#xA;    }&#xA;    return 0;&#xA;}&#xA;&#xA;/*===================================  VIDEO  ==================================*/&#xA;&#xA;void ScreenRecorder::generateVideoStream() {&#xA;    //Generate video stream&#xA;    videoSt = avformat_new_stream(outAVFormatContext, nullptr);&#xA;    if (videoSt == nullptr) {&#xA;        cerr &lt;&lt; "Error in creating AVFormatStream" &lt;&lt; endl;&#xA;        exit(-6);&#xA;    }&#xA;&#xA;    outVideoCodec = avcodec_find_encoder(AV_CODEC_ID_MPEG4);  //AV_CODEC_ID_MPEG4&#xA;    if (outVideoCodec == nullptr) {&#xA;        cerr &lt;&lt; "Error in finding the AVCodec, try again with the correct codec" &lt;&lt; endl;&#xA;        exit(-8);&#xA;    }&#xA;avcodec_alloc_context3(outAVCodec)&#xA;    outVideoCodecContext = avcodec_alloc_context3(outVideoCodec);&#xA;    if (outVideoCodecContext == nullptr) {&#xA;        cerr &lt;&lt; "Error in allocating the codec context" &lt;&lt; endl;&#xA;        exit(-7);&#xA;    }&#xA;&#xA;    //set properties of the video file (stream)&#xA;    outVideoCodecContext = videoSt->codec;&#xA;    outVideoCodecContext->codec_id = AV_CODEC_ID_MPEG4;&#xA;    outVideoCodecContext->codec_type = AVMEDIA_TYPE_VIDEO;&#xA;    outVideoCodecContext->pix_fmt = AV_PIX_FMT_YUV420P;&#xA;    outVideoCodecContext->bit_rate = 10000000;&#xA;    outVideoCodecContext->width = width;&#xA;    outVideoCodecContext->height = height;&#xA;    outVideoCodecContext->gop_size = 10;&#xA;    outVideoCodecContext->global_quality = 500;&#xA;    outVideoCodecContext->max_b_frames = 2;&#xA;    outVideoCodecContext->time_base.num = 1;&#xA;    outVideoCodecContext->time_base.den = 30;&#xA;    outVideoCodecContext->bit_rate_tolerance = 400000;&#xA;&#xA;    if (outVideoCodecContext->codec_id == AV_CODEC_ID_H264) {&#xA;        av_opt_set(outVideoCodecContext->priv_data, "preset", "slow", 0);&#xA;    }&#xA;&#xA;    if (outAVFormatContext->oformat->flags &amp; AVFMT_GLOBALHEADER) {&#xA;        outVideoCodecContext->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;&#xA;    }&#xA;&#xA;    value = avcodec_open2(outVideoCodecContext, outVideoCodec, nullptr);&#xA;    if (value &lt; 0) {&#xA;        cerr &lt;&lt; "Error in opening the AVCodec" &lt;&lt; endl;&#xA;        exit(-9);&#xA;    }&#xA;&#xA;    outVideoStreamIndex = -1;&#xA;    for (int i = 0; i &lt; outAVFormatContext->nb_streams; i&#x2B;&#x2B;) {&#xA;        if (outAVFormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_UNKNOWN) {&#xA;            outVideoStreamIndex = i;&#xA;        }&#xA;    }&#xA;    if (outVideoStreamIndex &lt; 0) {&#xA;        cerr &lt;&lt; "Error: cannot find a free stream index for video output" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;    avcodec_parameters_from_context(outAVFormatContext->streams[outVideoStreamIndex]->codecpar, outVideoCodecContext);&#xA;}&#xA;&#xA;/*===============================  AUDIO  ==================================*/&#xA;&#xA;void ScreenRecorder::generateAudioStream() {&#xA;    AVCodecParameters* params = inAudioFormatContext->streams[audioStreamIndx]->codecpar;&#xA;    inAudioCodec = avcodec_find_decoder(params->codec_id);&#xA;    if (inAudioCodec == nullptr) {&#xA;        cerr &lt;&lt; "Error: cannot find the audio decoder" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;    inAudioCodecContext = avcodec_alloc_context3(inAudioCodec);&#xA;    if (avcodec_parameters_to_context(inAudioCodecContext, params) &lt; 0) {&#xA;        cout &lt;&lt; "Cannot create codec context for audio input" &lt;&lt; endl;&#xA;    }&#xA;&#xA;    value = avcodec_open2(inAudioCodecContext, inAudioCodec, nullptr);&#xA;    if (value &lt; 0) {&#xA;        cerr &lt;&lt; "Error: cannot open the input audio codec" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;    //Generate audio stream&#xA;    outAudioCodecContext = nullptr;&#xA;    outAudioCodec = nullptr;&#xA;    int i;&#xA;&#xA;    AVStream* audio_st = avformat_new_stream(outAVFormatContext, nullptr);&#xA;    if (audio_st == nullptr) {&#xA;        cerr &lt;&lt; "Error: cannot create audio stream" &lt;&lt; endl;&#xA;        exit(1);&#xA;    }&#xA;&#xA;    outAudioCodec = avcodec_find_encoder(AV_CODEC_ID_AAC);&#xA;    if (outAudioCodec == nullptr) {&#xA;        cerr &lt;&lt; "Error: cannot find requested encoder" &lt;&lt; endl;&#xA;        exit(1);&#xA;    }&#xA;&#xA;    outAudioCodecContext = avcodec_alloc_context3(outAudioCodec);&#xA;    if (outAudioCodecContext == nullptr) {&#xA;        cerr &lt;&lt; "Error: cannot create related VideoCodecContext" &lt;&lt; endl;&#xA;        exit(1);&#xA;    }&#xA;&#xA;    if ((outAudioCodec)->supported_samplerates) {&#xA;        outAudioCodecContext->sample_rate = (outAudioCodec)->supported_samplerates[0];&#xA;        for (i = 0; (outAudioCodec)->supported_samplerates[i]; i&#x2B;&#x2B;) {&#xA;            if ((outAudioCodec)->supported_samplerates[i] == inAudioCodecContext->sample_rate)&#xA;                outAudioCodecContext->sample_rate = inAudioCodecContext->sample_rate;&#xA;        }&#xA;    }&#xA;    outAudioCodecContext->codec_id = AV_CODEC_ID_AAC;&#xA;    outAudioCodecContext->sample_fmt = (outAudioCodec)->sample_fmts ? (outAudioCodec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;&#xA;    outAudioCodecContext->channels = inAudioCodecContext->channels;&#xA;    outAudioCodecContext->channel_layout = av_get_default_channel_layout(outAudioCodecContext->channels);&#xA;    outAudioCodecContext->bit_rate = 96000;&#xA;    outAudioCodecContext->time_base = { 1, inAudioCodecContext->sample_rate };&#xA;&#xA;    outAudioCodecContext->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;&#xA;&#xA;    if ((outAVFormatContext)->oformat->flags &amp; AVFMT_GLOBALHEADER) {&#xA;        outAudioCodecContext->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;&#xA;    }&#xA;&#xA;    if (avcodec_open2(outAudioCodecContext, outAudioCodec, nullptr) &lt; 0) {&#xA;        cerr &lt;&lt; "error in opening the avcodec" &lt;&lt; endl;&#xA;        exit(1);&#xA;    }&#xA;&#xA;    //find a free stream index&#xA;    outAudioStreamIndex = -1;&#xA;    for (i = 0; i &lt; outAVFormatContext->nb_streams; i&#x2B;&#x2B;) {&#xA;        if (outAVFormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_UNKNOWN) {&#xA;            outAudioStreamIndex = i;&#xA;        }&#xA;    }&#xA;    if (outAudioStreamIndex &lt; 0) {&#xA;        cerr &lt;&lt; "Error: cannot find a free stream for audio on the output" &lt;&lt; endl;&#xA;        exit(1);&#xA;    }&#xA;&#xA;    avcodec_parameters_from_context(outAVFormatContext->streams[outAudioStreamIndex]->codecpar, outAudioCodecContext);&#xA;}&#xA;&#xA;int ScreenRecorder::init_fifo()&#xA;{&#xA;    /* Create the FIFO buffer based on the specified output sample format. */&#xA;    if (!(fifo = av_audio_fifo_alloc(outAudioCodecContext->sample_fmt,&#xA;        outAudioCodecContext->channels, 1))) {&#xA;        fprintf(stderr, "Could not allocate FIFO\n");&#xA;        return AVERROR(ENOMEM);&#xA;    }&#xA;    return 0;&#xA;}&#xA;&#xA;int ScreenRecorder::add_samples_to_fifo(uint8_t** converted_input_samples, const int frame_size) {&#xA;    int error;&#xA;    /* Make the FIFO as large as it needs to be to hold both,&#xA;     * the old and the new samples. */&#xA;    if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) &#x2B; frame_size)) &lt; 0) {&#xA;        fprintf(stderr, "Could not reallocate FIFO\n");&#xA;        return error;&#xA;    }&#xA;    /* Store the new samples in the FIFO buffer. */&#xA;    if (av_audio_fifo_write(fifo, (void**)converted_input_samples, frame_size) &lt; frame_size) {&#xA;        fprintf(stderr, "Could not write data to FIFO\n");&#xA;        return AVERROR_EXIT;&#xA;    }&#xA;    return 0;&#xA;}&#xA;&#xA;int ScreenRecorder::initConvertedSamples(uint8_t*** converted_input_samples,&#xA;    AVCodecContext* output_codec_context,&#xA;    int frame_size) {&#xA;    int error;&#xA;    /* Allocate as many pointers as there are audio channels.&#xA;     * Each pointer will later point to the audio samples of the corresponding&#xA;     * channels (although it may be NULL for interleaved formats).&#xA;     */&#xA;    if (!(*converted_input_samples = (uint8_t**)calloc(output_codec_context->channels,&#xA;        sizeof(**converted_input_samples)))) {&#xA;        fprintf(stderr, "Could not allocate converted input sample pointers\n");&#xA;        return AVERROR(ENOMEM);&#xA;    }&#xA;    /* Allocate memory for the samples of all channels in one consecutive&#xA;     * block for convenience. */&#xA;    if (av_samples_alloc(*converted_input_samples, nullptr,&#xA;        output_codec_context->channels,&#xA;        frame_size,&#xA;        output_codec_context->sample_fmt, 0) &lt; 0) {&#xA;&#xA;        exit(1);&#xA;    }&#xA;    return 0;&#xA;}&#xA;&#xA;static int64_t pts = 0;&#xA;void ScreenRecorder::captureAudio() {&#xA;    int ret;&#xA;    AVPacket* inPacket, * outPacket;&#xA;    AVFrame* rawFrame, * scaledFrame;&#xA;    uint8_t** resampledData;&#xA;&#xA;    init_fifo();&#xA;&#xA;    //allocate space for a packet&#xA;    inPacket = (AVPacket*)av_malloc(sizeof(AVPacket));&#xA;    if (!inPacket) {&#xA;        cerr &lt;&lt; "Cannot allocate an AVPacket for encoded video" &lt;&lt; endl;&#xA;        exit(1);&#xA;    }&#xA;    av_init_packet(inPacket);&#xA;&#xA;    //allocate space for a packet&#xA;    rawFrame = av_frame_alloc();&#xA;    if (!rawFrame) {&#xA;        cerr &lt;&lt; "Cannot allocate an AVPacket for encoded video" &lt;&lt; endl;&#xA;        exit(1);&#xA;    }&#xA;&#xA;    scaledFrame = av_frame_alloc();&#xA;    if (!scaledFrame) {&#xA;        cerr &lt;&lt; "Cannot allocate an AVPacket for encoded video" &lt;&lt; endl;&#xA;        exit(1);&#xA;    }&#xA;&#xA;    outPacket = (AVPacket*)av_malloc(sizeof(AVPacket));&#xA;    if (!outPacket) {&#xA;        cerr &lt;&lt; "Cannot allocate an AVPacket for encoded video" &lt;&lt; endl;&#xA;        exit(1);&#xA;    }&#xA;&#xA;    //init the resampler&#xA;    SwrContext* resampleContext = nullptr;&#xA;    resampleContext = swr_alloc_set_opts(resampleContext,&#xA;        av_get_default_channel_layout(outAudioCodecContext->channels),&#xA;        outAudioCodecContext->sample_fmt,&#xA;        outAudioCodecContext->sample_rate,&#xA;        av_get_default_channel_layout(inAudioCodecContext->channels),&#xA;        inAudioCodecContext->sample_fmt,&#xA;        inAudioCodecContext->sample_rate,&#xA;        0,&#xA;        nullptr);&#xA;    if (!resampleContext) {&#xA;        cerr &lt;&lt; "Cannot allocate the resample context" &lt;&lt; endl;&#xA;        exit(1);&#xA;    }&#xA;    if ((swr_init(resampleContext)) &lt; 0) {&#xA;        fprintf(stderr, "Could not open resample context\n");&#xA;        swr_free(&amp;resampleContext);&#xA;        exit(1);&#xA;    }&#xA;&#xA;    while (true) {&#xA;        if (pauseCapture) {&#xA;            cout &lt;&lt; "Pause audio" &lt;&lt; endl;&#xA;        }&#xA;        cv.wait(ul, [this]() { return !pauseCapture; });&#xA;&#xA;        if (stopCapture) {&#xA;            break;&#xA;        }&#xA;&#xA;        ul.unlock();&#xA;&#xA;        if (av_read_frame(inAudioFormatContext, inPacket) >= 0 &amp;&amp; inPacket->stream_index == audioStreamIndx) {&#xA;            //decode audio routing&#xA;            av_packet_rescale_ts(outPacket, inAudioFormatContext->streams[audioStreamIndx]->time_base, inAudioCodecContext->time_base);&#xA;            if ((ret = avcodec_send_packet(inAudioCodecContext, inPacket)) &lt; 0) {&#xA;                cout &lt;&lt; "Cannot decode current audio packet " &lt;&lt; ret &lt;&lt; endl;&#xA;                continue;&#xA;            }&#xA;            &#xA;            while (ret >= 0) {&#xA;                ret = avcodec_receive_frame(inAudioCodecContext, rawFrame);&#xA;                if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)&#xA;                    break;&#xA;                else if (ret &lt; 0) {&#xA;                    cerr &lt;&lt; "Error during decoding" &lt;&lt; endl;&#xA;                    exit(1);&#xA;                }&#xA;                if (outAVFormatContext->streams[outAudioStreamIndex]->start_time &lt;= 0) {&#xA;                    outAVFormatContext->streams[outAudioStreamIndex]->start_time = rawFrame->pts;&#xA;                }&#xA;                initConvertedSamples(&amp;resampledData, outAudioCodecContext, rawFrame->nb_samples);&#xA;&#xA;                swr_convert(resampleContext,&#xA;                    resampledData, rawFrame->nb_samples,&#xA;                    (const uint8_t**)rawFrame->extended_data, rawFrame->nb_samp&#xA;&#xA;                add_samples_to_fifo(resampledData, rawFrame->nb_samples);&#xA;&#xA;                //raw frame ready&#xA;                av_init_packet(outPacket);&#xA;                outPacket->data = nullptr;&#xA;                outPacket->size = 0;&#xA;&#xA;                const int frame_size = FFMAX(av_audio_fifo_size(fifo), outAudioCodecContext->frame_size);&#xA;&#xA;                scaledFrame = av_frame_alloc();&#xA;                if (!scaledFrame) {&#xA;                    cerr &lt;&lt; "Cannot allocate an AVPacket for encoded video" &lt;&lt; endl;&#xA;                    exit(1);&#xA;                }&#xA;&#xA;                scaledFrame->nb_samples = outAudioCodecContext->frame_size;&#xA;                scaledFrame->channel_layout = outAudioCodecContext->channel_layout;&#xA;                scaledFrame->format = outAudioCodecContext->sample_fmt;&#xA;                scaledFrame->sample_rate = outAudioCodecContext->sample_rate;&#xA;                av_frame_get_buffer(scaledFrame, 0);&#xA;&#xA;                while (av_audio_fifo_size(fifo) >= outAudioCodecContext->frame_size) {&#xA;&#xA;                    ret = av_audio_fifo_read(fifo, (void**)(scaledFrame->data), outAudioCodecContext->frame_size);&#xA;                    scaledFrame->pts = pts;&#xA;                    pts &#x2B;= scaledFrame->nb_samples;&#xA;                    if (avcodec_send_frame(outAudioCodecContext, scaledFrame) &lt; 0) {&#xA;                        cout &lt;&lt; "Cannot encode current audio packet " &lt;&lt; endl;&#xA;                        exit(1);&#xA;                    }&#xA;                    while (ret >= 0) {&#xA;                        ret = avcodec_receive_packet(outAudioCodecContext, outPacket);&#xA;                        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)&#xA;                            break;&#xA;                        else if (ret &lt; 0) {&#xA;                            cerr &lt;&lt; "Error during encoding" &lt;&lt; endl;&#xA;                            exit(1);&#xA;                        }&#xA;                        av_packet_rescale_ts(outPacket, outAudioCodecContext->time_base, outAVFormatContext->streams[outAudioStreamIndex]->time_base);&#xA;&#xA;                        outPacket->stream_index = outAudioStreamIndex;&#xA;&#xA;                        write_lock.lock();&#xA;                        &#xA;                        if (av_write_frame(outAVFormatContext, outPacket) != 0)&#xA;                        {&#xA;                            cerr &lt;&lt; "Error in writing audio frame" &lt;&lt; endl;&#xA;                        }&#xA;                        write_lock.unlock();&#xA;                        av_packet_unref(outPacket);&#xA;                    }&#xA;                    ret = 0;&#xA;                }&#xA;                av_frame_free(&amp;scaledFrame);&#xA;                av_packet_unref(outPacket);&#xA;            }&#xA;        }&#xA;    }&#xA;}&#xA;&#xA;int ScreenRecorder::captureVideoFrames() {&#xA;    int64_t pts = 0;&#xA;    int flag;&#xA;    int frameFinished = 0;&#xA;    bool endPause = false;&#xA;    int numPause = 0;&#xA;&#xA;    ofstream outFile{ "..\\media\\log.txt", ios::out };&#xA;&#xA;    int frameIndex = 0;&#xA;    value = 0;&#xA;&#xA;    pAVPacket = (AVPacket*)av_malloc(sizeof(AVPacket));&#xA;    if (pAVPacket == nullptr) {&#xA;        cerr &lt;&lt; "Error in allocating AVPacket" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;    pAVFrame = av_frame_alloc();&#xA;    if (pAVFrame == nullptr) {&#xA;        cerr &lt;&lt; "Error: unable to alloc the AVFrame resources" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;    outFrame = av_frame_alloc();&#xA;    if (outFrame == nullptr) {&#xA;        cerr &lt;&lt; "Error: unable to alloc the AVFrame resources for out frame" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;    int videoOutBuffSize;&#xA;    int nBytes = av_image_get_buffer_size(outVideoCodecContext->pix_fmt, outVideoCodecContext->width, outVideoCodecContext->height, 32);&#xA;    uint8_t* videoOutBuff = (uint8_t*)av_malloc(nBytes);&#xA;&#xA;    if (videoOutBuff == nullptr) {&#xA;        cerr &lt;&lt; "Error: unable to allocate memory" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;&#xA;    value = av_image_fill_arrays(outFrame->data, outFrame->linesize, videoOutBuff, AV_PIX_FMT_YUV420P, outVideoCodecContext->width, outVideoCodecContext->height, 1);&#xA;    if (value &lt; 0) {&#xA;        cerr &lt;&lt; "Error in filling image array" &lt;&lt; endl;&#xA;    }&#xA;&#xA;    SwsContext* swsCtx_;&#xA;    if (avcodec_open2(pAVCodecContext, pAVCodec, nullptr) &lt; 0) {&#xA;        cerr &lt;&lt; "Could not open codec" &lt;&lt; endl;&#xA;        exit(-1);&#xA;    }&#xA;    swsCtx_ = sws_getContext(pAVCodecContext->width, pAVCodecContext->height, pAVCodecContext->pix_fmt, outVideoCodecContext->width, outVideoCodecContext->height, outVideoCodecContext->pix_fmt, SWS_BICUBIC,&#xA;        nullptr, nullptr, nullptr);&#xA;&#xA;    AVPacket outPacket;&#xA;    int gotPicture;&#xA;&#xA;    time_t startTime;&#xA;    time(&amp;startTime);&#xA;&#xA;    while (true) {&#xA;&#xA;        if (pauseCapture) {&#xA;            cout &lt;&lt; "Pause" &lt;&lt; endl;&#xA;            outFile &lt;&lt; "///////////////////   Pause  ///////////////////" &lt;&lt; endl;&#xA;            cout &lt;&lt; "outVideoCodecContext->time_base: " &lt;&lt; outVideoCodecContext->time_base.num &lt;&lt; ", " &lt;&lt; outVideoCodecContext->time_base.den &lt;&lt; endl;&#xA;        }&#xA;        cv.wait(ul, [this]() { return !pauseCapture; });   //pause capture (not busy waiting)&#xA;        if (endPause) {&#xA;            endPause = false;&#xA;        }&#xA;&#xA;        if (stopCapture)  //check if the capture has to stop&#xA;            break;&#xA;        ul.unlock();&#xA;&#xA;        if (av_read_frame(pAVFormatContext, pAVPacket) >= 0 &amp;&amp; pAVPacket->stream_index == VideoStreamIndx) {&#xA;            av_packet_rescale_ts(pAVPacket, pAVFormatContext->streams[VideoStreamIndx]->time_base, pAVCodecContext->time_base);&#xA;            value = avcodec_decode_video2(pAVCodecContext, pAVFrame, &amp;frameFinished, pAVPacket);&#xA;            if (value &lt; 0) {&#xA;                cout &lt;&lt; "Unable to decode video" &lt;&lt; endl;&#xA;            }&#xA;&#xA;            if (frameFinished) { //frame successfully decoded&#xA;                //sws_scale(swsCtx_, pAVFrame->data, pAVFrame->linesize, 0, pAVCodecContext->height, outFrame->data, outFrame->linesize);&#xA;                av_init_packet(&amp;outPacket);&#xA;                outPacket.data = nullptr;&#xA;                outPacket.size = 0;&#xA;&#xA;                if (outAVFormatContext->streams[outVideoStreamIndex]->start_time &lt;= 0) {&#xA;                    outAVFormatContext->streams[outVideoStreamIndex]->start_time = pAVFrame->pts;&#xA;                }&#xA;&#xA;                //disable warning on the console&#xA;                outFrame->width = outVideoCodecContext->width;&#xA;                outFrame->height = outVideoCodecContext->height;&#xA;                outFrame->format = outVideoCodecContext->pix_fmt;&#xA;&#xA;                sws_scale(swsCtx_, pAVFrame->data, pAVFrame->linesize, 0, pAVCodecContext->height, outFrame->data, outFrame->linesize);&#xA;&#xA;                avcodec_encode_video2(outVideoCodecContext, &amp;outPacket, outFrame, &amp;gotPicture);&#xA;&#xA;                if (gotPicture) {&#xA;                    if (outPacket.pts != AV_NOPTS_VALUE) {&#xA;                        outPacket.pts = av_rescale_q(outPacket.pts, videoSt->codec->time_base, videoSt->time_base);&#xA;                    }&#xA;                    if (outPacket.dts != AV_NOPTS_VALUE) {&#xA;                        outPacket.dts = av_rescale_q(outPacket.dts, videoSt->codec->time_base, videoSt->time_base);&#xA;                    }&#xA;&#xA;                    //cout &lt;&lt; "Write frame " &lt;&lt; j&#x2B;&#x2B; &lt;&lt; " (size = " &lt;&lt; outPacket.size / 1000 &lt;&lt; ")" &lt;&lt; endl;&#xA;                    //cout &lt;&lt; "(size = " &lt;&lt; outPacket.size &lt;&lt; ")" &lt;&lt; endl;&#xA;&#xA;                    //av_packet_rescale_ts(&amp;outPacket, outVideoCodecContext->time_base, outAVFormatContext->streams[outVideoStreamIndex]->time_base);&#xA;                    //outPacket.stream_index = outVideoStreamIndex;&#xA;&#xA;                    outFile &lt;&lt; "outPacket->duration: " &lt;&lt; outPacket.duration &lt;&lt; ", " &lt;&lt; "pAVPacket->duration: " &lt;&lt; pAVPacket->duration &lt;&lt; endl;&#xA;                    outFile &lt;&lt; "outPacket->pts: " &lt;&lt; outPacket.pts &lt;&lt; ", " &lt;&lt; "pAVPacket->pts: " &lt;&lt; pAVPacket->pts &lt;&lt; endl;&#xA;                    outFile &lt;&lt; "outPacket.dts: " &lt;&lt; outPacket.dts &lt;&lt; ", " &lt;&lt; "pAVPacket->dts: " &lt;&lt; pAVPacket->dts &lt;&lt; endl;&#xA;&#xA;                    time_t timer;&#xA;                    double seconds;&#xA;&#xA;                    mu.lock();&#xA;                    if (!activeMenu) {&#xA;                        time(&amp;timer);&#xA;                        seconds = difftime(timer, startTime);&#xA;                        int h = (int)(seconds / 3600);&#xA;                        int m = (int)(seconds / 60) % 60;&#xA;                        int s = (int)(seconds) % 60;&#xA;&#xA;                        std::cout &lt;&lt; std::flush &lt;&lt; "\r" &lt;&lt; std::setw(2) &lt;&lt; std::setfill(&#x27;0&#x27;) &lt;&lt; h &lt;&lt; &#x27;:&#x27;&#xA;                            &lt;&lt; std::setw(2) &lt;&lt; std::setfill(&#x27;0&#x27;) &lt;&lt; m &lt;&lt; &#x27;:&#x27;&#xA;                            &lt;&lt; std::setw(2) &lt;&lt; std::setfill(&#x27;0&#x27;) &lt;&lt; s &lt;&lt; std::flush;&#xA;                    }&#xA;                    mu.unlock();&#xA;&#xA;                    write_lock.lock();&#xA;                    if (av_write_frame(outAVFormatContext, &amp;outPacket) != 0) {&#xA;                        cerr &lt;&lt; "Error in writing video frame" &lt;&lt; endl;&#xA;                    }&#xA;                    write_lock.unlock();&#xA;                    av_packet_unref(&amp;outPacket);&#xA;                }&#xA;&#xA;                av_packet_unref(&amp;outPacket);&#xA;                av_free_packet(pAVPacket);  //avoid memory saturation&#xA;            }&#xA;        }&#xA;    }&#xA;&#xA;    outFile.close();&#xA;&#xA;    av_free(videoOutBuff);&#xA;&#xA;    return 0;&#xA;}&#xA;

    &#xA;