Recherche avancée

Médias (1)

Mot : - Tags -/MediaSPIP 0.2

Autres articles (46)

  • MediaSPIP v0.2

    21 juin 2013, par

    MediaSPIP 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 (...)

  • Mise à disposition des fichiers

    14 avril 2011, par

    Par défaut, lors de son initialisation, MediaSPIP ne permet pas aux visiteurs de télécharger les fichiers qu’ils soient originaux ou le résultat de leur transformation ou encodage. Il permet uniquement de les visualiser.
    Cependant, il est possible et facile d’autoriser les visiteurs à avoir accès à ces documents et ce sous différentes formes.
    Tout cela se passe dans la page de configuration du squelette. Il vous faut aller dans l’espace d’administration du canal, et choisir dans la navigation (...)

  • Installation en mode ferme

    4 février 2011, par

    Le mode ferme permet d’héberger plusieurs sites de type MediaSPIP en n’installant qu’une seule fois son noyau fonctionnel.
    C’est la méthode que nous utilisons sur cette même plateforme.
    L’utilisation en mode ferme nécessite de connaïtre un peu le mécanisme de SPIP contrairement à la version standalone qui ne nécessite pas réellement de connaissances spécifique puisque l’espace privé habituel de SPIP n’est plus utilisé.
    Dans un premier temps, vous devez avoir installé les mêmes fichiers que l’installation (...)

Sur d’autres sites (5830)

  • lavc/vvcdec : remove unneeded set_output_format

    26 janvier, par Nuo Mi
    lavc/vvcdec : remove unneeded set_output_format
    

    Downstream can determine the format from the output frame format

    Co-authored-by : Frank Plowman <post@frankplowman.com>

    • [DH] libavcodec/vvc/dec.c
  • How to install ffmpeg on a Windows Dockerhub image ?

    18 janvier, par Youssef Kharoufi

    I have a program that executes a ffmpeg command to a video input, copies this video and pastes is in an output directory.

    &#xA;

    Here is my code in case you would want to duplicate it :

    &#xA;

        using Renderer.Models;&#xA;using System;&#xA;using System.IO;&#xA;using System.Text.Json;&#xA;using System.Threading.Tasks;&#xA;&#xA;public class Program&#xA;{&#xA;    public static async Task Main(string[] args)&#xA;    {&#xA;        var result = new DockerTaskResult();&#xA;        try&#xA;        {&#xA;            // Path to the JSON input file&#xA;            string jsonInputPath = @"C:\Users\ykharoufi\source\repos\Renderer\Renderer\Json\task.json";&#xA;&#xA;            // Check if the JSON file exists&#xA;            if (!File.Exists(jsonInputPath))&#xA;            {&#xA;                throw new FileNotFoundException($"JSON input file not found at path: {jsonInputPath}");&#xA;            }&#xA;&#xA;            // Read the JSON content&#xA;            string jsonContent = File.ReadAllText(jsonInputPath);&#xA;&#xA;            try&#xA;            {&#xA;                // Deserialize the JSON into a DockerTask object&#xA;                DockerTask task = JsonSerializer.Deserialize<dockertask>(jsonContent);&#xA;                if (task == null)&#xA;                {&#xA;                    throw new Exception("Failed to deserialize the task from JSON.");&#xA;                }&#xA;&#xA;                // Validate the input paths&#xA;                if (string.IsNullOrEmpty(task.InputFileRepoPath) || !File.Exists(task.InputFileRepoPath))&#xA;                {&#xA;                    throw new Exception($"Input file path is invalid or does not exist: {task.InputFileRepoPath}");&#xA;                }&#xA;&#xA;                if (string.IsNullOrEmpty(task.OutputFileRepoPath) || !Directory.Exists(task.OutputFileRepoPath))&#xA;                {&#xA;                    throw new Exception($"Output directory path is invalid or does not exist: {task.OutputFileRepoPath}");&#xA;                }&#xA;&#xA;                // Initialize the Docker worker and run the task&#xA;                var worker = new DockerWorker();&#xA;                var success = await worker.RunDockerTaskAsync(task);&#xA;&#xA;                if (success.Success)&#xA;                {&#xA;                    result.Success = true;&#xA;                    result.Message = "Command executed successfully!";&#xA;&#xA;                    // Check the output directory for files&#xA;                    if (Directory.Exists(task.OutputFileRepoPath))&#xA;                    {&#xA;                        result.OutputFiles = Directory.GetFiles(task.OutputFileRepoPath);&#xA;                    }&#xA;                }&#xA;                else&#xA;                {&#xA;                    result.Success = false;&#xA;                    result.Message = "Failed to execute the command.";&#xA;                    result.ErrorDetails = success.ErrorDetails;&#xA;                }&#xA;            }&#xA;            catch (JsonException)&#xA;            {&#xA;                // Handle invalid JSON format&#xA;                result.Success = false;&#xA;                result.Message = "Invalid JSON format.";&#xA;                result.ErrorDetails = "Invalid data entry";&#xA;            }&#xA;        }&#xA;        catch (Exception ex)&#xA;        {&#xA;            result.Success = false;&#xA;            result.Message = "An error occurred during execution.";&#xA;            result.ErrorDetails = ex.Message;&#xA;        }&#xA;        finally&#xA;        {&#xA;            // Serialize the result to JSON and write to console&#xA;            string outputJson = JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true });&#xA;            Console.WriteLine(outputJson);&#xA;        }&#xA;    }&#xA;}&#xA;&#xA;    using System;&#xA;using System.Collections.Generic;&#xA;using System.IO;&#xA;using System.Text.Json;&#xA;using System.Threading.Tasks;&#xA;using Docker.DotNet;&#xA;using Docker.DotNet.Models;&#xA;using Renderer.Models;&#xA;&#xA;public class DockerWorker&#xA;{&#xA;    private readonly DockerClient _dockerClient;&#xA;&#xA;    public DockerWorker()&#xA;    {&#xA;        Console.WriteLine("Initializing Docker client...");&#xA;        _dockerClient = new DockerClientConfiguration(&#xA;            new Uri("npipe://./pipe/docker_engine")) // Windows Docker URI&#xA;            .CreateClient();&#xA;        Console.WriteLine("Docker client initialized.");&#xA;    }&#xA;&#xA;    public async Task<dockertaskresult> RunDockerTaskAsync(DockerTask task)&#xA;    {&#xA;        var result = new DockerTaskResult();&#xA;&#xA;        try&#xA;        {&#xA;            Console.WriteLine("Starting Docker task...");&#xA;            Console.WriteLine($"Image: {task.ImageNaming}");&#xA;            Console.WriteLine($"Container: {task.ContainerNaming}");&#xA;            Console.WriteLine($"Input Path: {task.InputFileRepoPath}");&#xA;            Console.WriteLine($"Output Path: {task.OutputFileRepoPath}");&#xA;            Console.WriteLine($"Command: {task.CommandDef}");&#xA;&#xA;            // Ensure the Docker image exists&#xA;            Console.WriteLine("Checking if Docker image exists...");&#xA;            var imageCheckResult = await EnsureImageExists(task.ImageNaming);&#xA;            if (!imageCheckResult.Success)&#xA;            {&#xA;                result.Success = false;&#xA;                result.Message = imageCheckResult.Message;&#xA;                result.ErrorDetails = imageCheckResult.ErrorDetails;&#xA;                return result;&#xA;            }&#xA;            Console.WriteLine("Docker image verified.");&#xA;&#xA;            // Determine platform&#xA;            var platform = await GetImagePlatform(task.ImageNaming);&#xA;            Console.WriteLine($"Detected image platform: {platform}");&#xA;&#xA;            // Translate paths&#xA;            string inputVolume, outputVolume;&#xA;            if (platform == "linux")&#xA;            {&#xA;                inputVolume = $"{task.InputFileRepoPath.Replace("C:\\", "/mnt/c/").Replace("\\", "/")}:/app/input";&#xA;                outputVolume = $"{task.OutputFileRepoPath.Replace("C:\\", "/mnt/c/").Replace("\\", "/")}:/app/output";&#xA;            }&#xA;            else if (platform == "windows")&#xA;            {&#xA;                string inputDir = Path.GetFullPath(Path.GetDirectoryName(task.InputFileRepoPath)).TrimEnd(&#x27;\\&#x27;);&#xA;                string outputDir = Path.GetFullPath(task.OutputFileRepoPath).TrimEnd(&#x27;\\&#x27;);&#xA;&#xA;                if (!Directory.Exists(inputDir))&#xA;                {&#xA;                    throw new Exception($"Input directory does not exist: {inputDir}");&#xA;                }&#xA;                if (!Directory.Exists(outputDir))&#xA;                {&#xA;                    throw new Exception($"Output directory does not exist: {outputDir}");&#xA;                }&#xA;&#xA;                inputVolume = $"{inputDir}:C:\\app\\input";&#xA;                outputVolume = $"{outputDir}:C:\\app\\output";&#xA;&#xA;                Console.WriteLine($"Input volume: {inputVolume}");&#xA;                Console.WriteLine($"Output volume: {outputVolume}");&#xA;            }&#xA;            else&#xA;            {&#xA;                throw new Exception($"Unsupported platform: {platform}");&#xA;            }&#xA;&#xA;            // Create container&#xA;            Console.WriteLine("Creating Docker container...");&#xA;            var containerResponse = await _dockerClient.Containers.CreateContainerAsync(new CreateContainerParameters&#xA;            {&#xA;                Image = task.ImageNaming,&#xA;                Name = task.ContainerNaming,&#xA;                HostConfig = new HostConfig&#xA;                {&#xA;                    Binds = new List<string> { inputVolume, outputVolume },&#xA;                    AutoRemove = true&#xA;                },&#xA;                Cmd = new[] { platform == "linux" ? "bash" : "cmd.exe", "/c", task.CommandDef }&#xA;            });&#xA;&#xA;            if (string.IsNullOrEmpty(containerResponse.ID))&#xA;            {&#xA;                throw new Exception("Failed to create Docker container.");&#xA;            }&#xA;            Console.WriteLine($"Container created with ID: {containerResponse.ID}");&#xA;&#xA;            // Start container&#xA;            Console.WriteLine("Starting container...");&#xA;            bool started = await _dockerClient.Containers.StartContainerAsync(containerResponse.ID, new ContainerStartParameters());&#xA;            if (!started)&#xA;            {&#xA;                throw new Exception($"Failed to start container: {task.ContainerNaming}");&#xA;            }&#xA;&#xA;            // Wait for container to finish&#xA;            Console.WriteLine("Waiting for container to finish...");&#xA;            var waitResponse = await _dockerClient.Containers.WaitContainerAsync(containerResponse.ID);&#xA;&#xA;            if (waitResponse.StatusCode != 0)&#xA;            {&#xA;                Console.WriteLine($"Container exited with error code: {waitResponse.StatusCode}");&#xA;                await FetchContainerLogs(containerResponse.ID);&#xA;                throw new Exception($"Container exited with non-zero status code: {waitResponse.StatusCode}");&#xA;            }&#xA;&#xA;            // Fetch logs&#xA;            Console.WriteLine("Fetching container logs...");&#xA;            await FetchContainerLogs(containerResponse.ID);&#xA;&#xA;            result.Success = true;&#xA;            result.Message = "Docker task completed successfully.";&#xA;            return result;&#xA;        }&#xA;        catch (Exception ex)&#xA;        {&#xA;            Console.WriteLine($"Error: {ex.Message}");&#xA;            result.Success = false;&#xA;            result.Message = "An error occurred during execution.";&#xA;            result.ErrorDetails = ex.Message;&#xA;            return result;&#xA;        }&#xA;    }&#xA;&#xA;    private async Task<string> GetImagePlatform(string imageName)&#xA;    {&#xA;        try&#xA;        {&#xA;            Console.WriteLine($"Inspecting Docker image: {imageName}...");&#xA;            var imageDetails = await _dockerClient.Images.InspectImageAsync(imageName);&#xA;            Console.WriteLine($"Image platform: {imageDetails.Os}");&#xA;            return imageDetails.Os.ToLower();&#xA;        }&#xA;        catch (Exception ex)&#xA;        {&#xA;            throw new Exception($"Failed to inspect image: {ex.Message}");&#xA;        }&#xA;    }&#xA;&#xA;    private async Task<dockertaskresult> EnsureImageExists(string imageName)&#xA;    {&#xA;        var result = new DockerTaskResult();&#xA;        try&#xA;        {&#xA;            Console.WriteLine($"Pulling Docker image: {imageName}...");&#xA;            await _dockerClient.Images.CreateImageAsync(&#xA;                new ImagesCreateParameters { FromImage = imageName, Tag = "latest" },&#xA;                null,&#xA;                new Progress<jsonmessage>()&#xA;            );&#xA;            result.Success = true;&#xA;            result.Message = "Docker image is available.";&#xA;        }&#xA;        catch (Exception ex)&#xA;        {&#xA;            result.Success = false;&#xA;            result.Message = $"Failed to pull Docker image: {imageName}";&#xA;            result.ErrorDetails = ex.Message;&#xA;        }&#xA;        return result;&#xA;    }&#xA;&#xA;    private async Task FetchContainerLogs(string containerId)&#xA;    {&#xA;        try&#xA;        {&#xA;            Console.WriteLine($"Fetching logs for container: {containerId}...");&#xA;            var logs = await _dockerClient.Containers.GetContainerLogsAsync(&#xA;                containerId,&#xA;                new ContainerLogsParameters { ShowStdout = true, ShowStderr = true });&#xA;&#xA;            using (var reader = new StreamReader(logs))&#xA;            {&#xA;                string logLine;&#xA;                while ((logLine = await reader.ReadLineAsync()) != null)&#xA;                {&#xA;                    Console.WriteLine(logLine);&#xA;                }&#xA;            }&#xA;        }&#xA;        catch (Exception ex)&#xA;        {&#xA;            Console.WriteLine($"Failed to fetch logs: {ex.Message}");&#xA;        }&#xA;    }&#xA;}&#xA;&#xA;    {&#xA;  "ImageNaming": "khuser/windowsimage:latest",&#xA;  "ContainerNaming": "custom-worker-container",&#xA;  "InputFileRepoPath": "C:/Users/user/source/repos/Renderer/Renderer/wwwroot/audio.mp4",&#xA;  "OutputFileRepoPath": "C:/Users/user/Desktop/output/",&#xA;  "CommandDef": "ffmpeg -i C:\\app\\input\\audio.mp4 -c copy C:\\app\\output\\copiedAudio.mp4"&#xA;</jsonmessage></dockertaskresult></string></string></dockertaskresult></dockertask>

    &#xA;

    }. My problem is what I get in the output of my program : Initializing Docker client... Docker client initialized. Starting Docker task... Image: khyoussef/windowsimage:latest Container: custom-worker-container Input Path: C:/Users/ykharoufi/source/repos/Renderer/Renderer/wwwroot/audio.mp4 Output Path: C:/Users/ykharoufi/Desktop/output/ Command: ffmpeg -i C:\app\input\audio.mp4 -c copy C:\app\output\copiedAudio.mp4 Checking if Docker image exists... Pulling Docker image: khyoussef/windowsimage:latest... Docker image verified. Inspecting Docker image: khyoussef/windowsimage:latest... Image platform: windows Detected image platform: windows Input volume: C:\Users\ykharoufi\source\repos\Renderer\Renderer\wwwroot:C:\app\input Output volume: C:\Users\ykharoufi\Desktop\output:C:\app\output Creating Docker container... Container created with ID: 1daca99b3c76bc8c99c1aed7d2c546ae75aedd9aa1feb0f5002e54769390248e Starting container... Waiting for container to finish... Container exited with error code: 1 Fetching logs for container: 1daca99b3c76bc8c99c1aed7d2c546ae75aedd9aa1feb0f5002e54769390248e... @&#x27;ffmpeg&#x27; is not recognized as an internal or external command, !operable program or batch file. Error: Container exited with non-zero status code: 1 { "Success": false, "Message": "Failed to execute the command.", "ErrorDetails": "Container exited with non-zero status code: 1", "OutputFiles": null }, This is the Dockerfile I am working with :

    &#xA;

    `# Use Windows Server Core as the base image&#xA;FROM mcr.microsoft.com/windows/server:ltsc2022&#xA;&#xA;# Set the working directory&#xA;WORKDIR /app&#xA;&#xA;# Install required tools (FFmpeg and Visual C&#x2B;&#x2B; Redistributable)&#xA;RUN powershell -Command \&#xA;    $ErrorActionPreference = &#x27;Stop&#x27;; \&#xA;    # Install Visual C&#x2B;&#x2B; Redistributable&#xA;    Invoke-WebRequest -Uri https://aka.ms/vs/16/release/vc_redist.x64.exe -OutFile vc_redist.x64.exe; \&#xA;    Start-Process -FilePath vc_redist.x64.exe -ArgumentList &#x27;/install&#x27;, &#x27;/quiet&#x27;, &#x27;/norestart&#x27; -NoNewWindow -Wait; \&#xA;    Remove-Item -Force vc_redist.x64.exe; \&#xA;    # Download FFmpeg&#xA;    Invoke-WebRequest -Uri https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-n7.1-latest-win64-gpl-7.1.zip -OutFile ffmpeg.zip; \&#xA;    # Extract FFmpeg&#xA;    Expand-Archive -Path ffmpeg.zip -DestinationPath C:\ffmpeg; \&#xA;    Remove-Item -Force ffmpeg.zip; \&#xA;    # Debug step: Verify FFmpeg extraction&#xA;    Write-Output "FFmpeg extracted to C:\\ffmpeg"; \&#xA;    dir C:\ffmpeg; \&#xA;    dir C:\ffmpeg\ffmpeg-n7.1-latest-win64-gpl-7.1\bin&#xA;&#xA;# Add FFmpeg to PATH permanently&#xA;ENV PATH="C:\\ffmpeg\\ffmpeg-n7.1-latest-win64-gpl-7.1\\bin;${PATH}"&#xA;&#xA;# Verify FFmpeg installation&#xA;RUN ["cmd", "/S", "/C", "ffmpeg -version"]&#xA;&#xA;# Copy required files to the container&#xA;COPY ./ /app/&#xA;&#xA;# Default to a PowerShell session&#xA;CMD ["C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", "-NoExit"]&#xA;`&#xA;

    &#xA;

    . I did build it using this command : docker build -t khuser/windowsimage:latest -f Dockerfile .

    &#xA;

  • Issues with Video Recording Duration and Smooth Playback when Using v4l2 framework to MP4 (FFmpeg)

    9 décembre 2024, par Reena

    I'm trying to record a video from a USB device with v4l2 framework and save it in MP4 format using FFmpeg. My sample code successfully captures and saves the video, but I'm running into some issues :

    &#xA;

    The recorded video duration is shorter than expected. For instance :

    &#xA;

    When recording a 1-minute video at 1280x720, the output file only has 58 or 59 seconds. For 1920x1080, the duration is even more off — only about 28 or 30 seconds, instead of the expected 1 minute. Additionally, the video is not smooth. There are noticeable drops in frames and playback inconsistencies.

    &#xA;

    My setup :

    &#xA;

    Using a USB device with v4l2 framework Saving the video in MP4 format Tested with different resolutions (1280x720, 1920x1080) I've attached my sample code below. Could someone help me figure out why I'm experiencing these issues with video duration and smooth playback ?

    &#xA;

    #include &#xA;#include &#xA;#include &#xA;#include &#xA;#include <sys></sys>ioctl.h>&#xA;#include <sys></sys>mman.h>&#xA;#include <linux></linux>videodev2.h>&#xA;#include <libavformat></libavformat>avformat.h>&#xA;#include <libavcodec></libavcodec>avcodec.h>&#xA;#include <libavutil></libavutil>imgutils.h>&#xA;#include <libavutil></libavutil>opt.h>&#xA;#include <libswscale></libswscale>swscale.h>&#xA;#include &#xA;#include <sys></sys>time.h>&#xA;#include &#xA;&#xA;#define WIDTH 1280&#xA;#define HEIGHT 720&#xA;#define FPS 30&#xA;#define DURATION 10 // Recording duration in seconds&#xA;#define BUFFER_COUNT 4 // Number of buffers&#xA;&#xA;struct buffer {&#xA;    void *start;&#xA;    size_t length;&#xA;};&#xA;&#xA;struct buffer *buffers;&#xA;&#xA;void open_device(int *fd, const char *device) {&#xA;    *fd = open(device, O_RDWR | O_NONBLOCK);&#xA;    if (*fd &lt; 0) {&#xA;        perror("Cannot open video device");&#xA;        exit(1);&#xA;    }&#xA;}&#xA;&#xA;void init_mmap(int fd) {&#xA;    struct v4l2_requestbuffers req;&#xA;    memset(&amp;req, 0, sizeof(req));&#xA;    req.count = BUFFER_COUNT;&#xA;    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;&#xA;    req.memory = V4L2_MEMORY_MMAP;&#xA;&#xA;    if (ioctl(fd, VIDIOC_REQBUFS, &amp;req) &lt; 0) {&#xA;        perror("Requesting buffer");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    buffers = calloc(req.count, sizeof(*buffers));&#xA;    for (size_t i = 0; i &lt; req.count; &#x2B;&#x2B;i) {&#xA;        struct v4l2_buffer buf;&#xA;        memset(&amp;buf, 0, sizeof(buf));&#xA;        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;&#xA;        buf.memory = V4L2_MEMORY_MMAP;&#xA;        buf.index = i;&#xA;&#xA;        if (ioctl(fd, VIDIOC_QUERYBUF, &amp;buf) &lt; 0) {&#xA;            perror("Querying buffer");&#xA;            exit(1);&#xA;        }&#xA;&#xA;        buffers[i].length = buf.length;&#xA;        buffers[i].start = mmap(NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, buf.m.offset);&#xA;&#xA;        if (MAP_FAILED == buffers[i].start) {&#xA;            perror("mmap");&#xA;            exit(1);&#xA;        }&#xA;    }&#xA;}&#xA;&#xA;void start_capturing(int fd) {&#xA;    for (size_t i = 0; i &lt; BUFFER_COUNT; &#x2B;&#x2B;i) {&#xA;        struct v4l2_buffer buf;&#xA;        memset(&amp;buf, 0, sizeof(buf));&#xA;        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;&#xA;        buf.memory = V4L2_MEMORY_MMAP;&#xA;        buf.index = i;&#xA;&#xA;        if (ioctl(fd, VIDIOC_QBUF, &amp;buf) &lt; 0) {&#xA;            perror("Queue buffer");&#xA;            exit(1);&#xA;        }&#xA;    }&#xA;&#xA;    enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;&#xA;    if (ioctl(fd, VIDIOC_STREAMON, &amp;type) &lt; 0) {&#xA;        perror("Start capture");&#xA;        exit(1);&#xA;    }&#xA;}&#xA;&#xA;void stop_capturing(int fd) {&#xA;    enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;&#xA;&#xA;    if (ioctl(fd, VIDIOC_STREAMOFF, &amp;type) &lt; 0) {&#xA;        perror("Stop capture");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    printf("Video capture stopped.\n");&#xA;}&#xA;&#xA;void unmap_buffers() {&#xA;    for (size_t i = 0; i &lt; BUFFER_COUNT; &#x2B;&#x2B;i) {&#xA;        if (munmap(buffers[i].start, buffers[i].length) &lt; 0) {&#xA;            perror("munmap");&#xA;            exit(1);&#xA;        }&#xA;    }&#xA;&#xA;    free(buffers);&#xA;}&#xA;&#xA;void initialize_ffmpeg(AVFormatContext **fmt_ctx, AVCodecContext **codec_ctx, AVStream **video_stream, const char *filename) {&#xA;    av_register_all();&#xA;&#xA;    AVOutputFormat *fmt = av_guess_format(NULL, filename, NULL);&#xA;    if (!fmt) {&#xA;        fprintf(stderr, "Could not determine output format\n");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    if (avformat_alloc_output_context2(fmt_ctx, fmt, NULL, filename) &lt; 0) {&#xA;        fprintf(stderr, "Could not allocate format context\n");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_H264);&#xA;    if (!codec) {&#xA;        fprintf(stderr, "Codec not found\n");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    *video_stream = avformat_new_stream(*fmt_ctx, NULL);&#xA;    if (!*video_stream) {&#xA;        fprintf(stderr, "Could not create stream\n");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    *codec_ctx = avcodec_alloc_context3(codec);&#xA;    if (!*codec_ctx) {&#xA;        fprintf(stderr, "Could not allocate codec context\n");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    (*codec_ctx)->codec_type = AVMEDIA_TYPE_VIDEO;&#xA;    (*codec_ctx)->width = WIDTH;&#xA;    (*codec_ctx)->height = HEIGHT;&#xA;    (*codec_ctx)->time_base = (AVRational){1, FPS};&#xA;    (*codec_ctx)->framerate = (AVRational){FPS, 1};&#xA;    (*codec_ctx)->pix_fmt = AV_PIX_FMT_YUV420P;&#xA;    (*codec_ctx)->gop_size = 10;&#xA;    (*codec_ctx)->max_b_frames = 1;&#xA;&#xA;    av_opt_set(*codec_ctx, "preset", "fast", 0);&#xA;    av_opt_set_int(*codec_ctx, "crf", 23, 0);&#xA;&#xA;    (*video_stream)->time_base = (*codec_ctx)->time_base;&#xA;    (*video_stream)->codecpar->codec_id = fmt->video_codec;&#xA;    (*video_stream)->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;&#xA;    (*video_stream)->codecpar->width = (*codec_ctx)->width;&#xA;    (*video_stream)->codecpar->height = (*codec_ctx)->height;&#xA;    (*video_stream)->codecpar->format = (*codec_ctx)->pix_fmt;&#xA;&#xA;    if ((*fmt_ctx)->oformat->flags &amp; AVFMT_GLOBALHEADER) {&#xA;        (*codec_ctx)->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;&#xA;    }&#xA;&#xA;    if (avcodec_open2(*codec_ctx, codec, NULL) &lt; 0) {&#xA;        fprintf(stderr, "Could not open codec\n");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    if (avcodec_parameters_from_context((*video_stream)->codecpar, *codec_ctx) &lt; 0) {&#xA;        fprintf(stderr, "Could not copy codec parameters\n");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    if (!(fmt->flags &amp; AVFMT_NOFILE)) {&#xA;        if (avio_open(&amp;(*fmt_ctx)->pb, filename, AVIO_FLAG_WRITE) &lt; 0) {&#xA;            fprintf(stderr, "Could not open output file\n");&#xA;            exit(1);&#xA;        }&#xA;    }&#xA;&#xA;    if (avformat_write_header(*fmt_ctx, NULL) &lt; 0) {&#xA;        fprintf(stderr, "Could not write header\n");&#xA;        exit(1);&#xA;    }&#xA;}&#xA;&#xA;void capture_and_encode(int fd, AVFormatContext *fmt_ctx, AVCodecContext *codec_ctx, struct SwsContext *sws_ctx, AVStream *video_stream, int duration) {&#xA;    struct v4l2_buffer buffer;&#xA;    AVFrame *frame = av_frame_alloc();&#xA;    AVPacket packet;&#xA;    av_init_packet(&amp;packet);&#xA;&#xA;    frame->format = codec_ctx->pix_fmt;&#xA;    frame->width = codec_ctx->width;&#xA;    frame->height = codec_ctx->height;&#xA;    av_image_alloc(frame->data, frame->linesize, codec_ctx->width, codec_ctx->height, codec_ctx->pix_fmt, 32);&#xA;&#xA;    struct timespec start_time;&#xA;    clock_gettime(CLOCK_MONOTONIC, &amp;start_time);&#xA;    double elapsed_time = 0;&#xA;    int64_t pts_counter = 0;&#xA;    int frame_count = 0;&#xA;&#xA;    while (elapsed_time &lt; duration) {&#xA;        fd_set fds;&#xA;        struct timeval tv;&#xA;        int r;&#xA;&#xA;        FD_ZERO(&amp;fds);&#xA;        FD_SET(fd, &amp;fds);&#xA;&#xA;        tv.tv_sec = 2;&#xA;        tv.tv_usec = 0;&#xA;&#xA;        r = select(fd &#x2B; 1, &amp;fds, NULL, NULL, &amp;tv);&#xA;        if (r == -1) {&#xA;            perror("select");&#xA;            exit(1);&#xA;        }&#xA;&#xA;        if (r == 0) {&#xA;            fprintf(stderr, "select timeout\n");&#xA;            exit(1);&#xA;        }&#xA;&#xA;        memset(&amp;buffer, 0, sizeof(buffer));&#xA;        buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;&#xA;        buffer.memory = V4L2_MEMORY_MMAP;&#xA;&#xA;        if (ioctl(fd, VIDIOC_DQBUF, &amp;buffer) &lt; 0) {&#xA;            if (errno == EAGAIN) continue;&#xA;            perror("Could not dequeue buffer");&#xA;            exit(1);&#xA;        }&#xA;&#xA;        uint8_t *src_slices[1] = {buffers[buffer.index].start};&#xA;        int src_stride[1] = {WIDTH * 2}; // UYVY is 2 bytes per pixel&#xA;&#xA;        sws_scale(sws_ctx, src_slices, src_stride, 0, HEIGHT, frame->data, frame->linesize);&#xA;&#xA;        frame->pts = pts_counter;&#xA;        pts_counter &#x2B;= av_rescale_q(1, (AVRational){1, FPS}, codec_ctx->time_base);&#xA;&#xA;        if (avcodec_send_frame(codec_ctx, frame) &lt; 0) {&#xA;            fprintf(stderr, "Error sending frame\n");&#xA;            exit(1);&#xA;        }&#xA;&#xA;        while (avcodec_receive_packet(codec_ctx, &amp;packet) == 0) {&#xA;            av_packet_rescale_ts(&amp;packet, codec_ctx->time_base, video_stream->time_base);&#xA;            packet.stream_index = video_stream->index;&#xA;&#xA;            if (av_interleaved_write_frame(fmt_ctx, &amp;packet) &lt; 0) {&#xA;                fprintf(stderr, "Error writing frame\n");&#xA;                exit(1);&#xA;            }&#xA;&#xA;            av_packet_unref(&amp;packet);&#xA;        }&#xA;        printf("Processed frame %d\n", frame_count);&#xA;&#xA;        if (ioctl(fd, VIDIOC_QBUF, &amp;buffer) &lt; 0) {&#xA;            perror("Could not requeue buffer");&#xA;            exit(1);&#xA;        }&#xA;        frame_count&#x2B;&#x2B;;&#xA;        struct timespec current_time;&#xA;        clock_gettime(CLOCK_MONOTONIC, &amp;current_time);&#xA;        elapsed_time = (current_time.tv_sec - start_time.tv_sec) &#x2B; (current_time.tv_nsec - start_time.tv_nsec) / 1e9;&#xA;        printf("Elapsed time: %f seconds\n", elapsed_time);&#xA;    }&#xA;&#xA;    av_freep(&amp;frame->data[0]);&#xA;    av_frame_free(&amp;frame);&#xA;    printf("Total frames processed: %d\n", frame_count);&#xA;}&#xA;&#xA;int main(int argc, char *argv[]) {&#xA;    if (argc != 2) {&#xA;        fprintf(stderr, "Usage: %s <output file="file">\n", argv[0]);&#xA;        exit(1);&#xA;    }&#xA;&#xA;    const char *output_file = argv[1];&#xA;    int fd;&#xA;    open_device(&amp;fd, "/dev/video2");&#xA;&#xA;    struct v4l2_format fmt;&#xA;    memset(&amp;fmt, 0, sizeof(fmt));&#xA;    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;&#xA;    fmt.fmt.pix.width = WIDTH;&#xA;    fmt.fmt.pix.height = HEIGHT;&#xA;    fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_UYVY;&#xA;    fmt.fmt.pix.field = V4L2_FIELD_NONE;&#xA;&#xA;    if (ioctl(fd, VIDIOC_S_FMT, &amp;fmt) &lt; 0) {&#xA;        perror("Setting pixel format");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    if (fmt.fmt.pix.pixelformat != V4L2_PIX_FMT_UYVY) {&#xA;        fprintf(stderr, "Device does not support UYVY format\n");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    init_mmap(fd);&#xA;    start_capturing(fd);&#xA;&#xA;    AVFormatContext *fmt_ctx = NULL;&#xA;    AVCodecContext *codec_ctx = NULL;&#xA;    AVStream *video_stream = NULL;&#xA;&#xA;    initialize_ffmpeg(&amp;fmt_ctx, &amp;codec_ctx, &amp;video_stream, output_file);&#xA;&#xA;    struct SwsContext *sws_ctx = sws_getContext(WIDTH, HEIGHT, AV_PIX_FMT_UYVY422,&#xA;                                                WIDTH, HEIGHT, AV_PIX_FMT_YUV420P,&#xA;                                                SWS_BICUBIC, NULL, NULL, NULL);&#xA;&#xA;    if (!sws_ctx) {&#xA;        fprintf(stderr, "Could not initialize SwsContext\n");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    capture_and_encode(fd, fmt_ctx, codec_ctx, sws_ctx, video_stream, DURATION);&#xA;&#xA;    sws_freeContext(sws_ctx);&#xA;    av_write_trailer(fmt_ctx);&#xA;    avcodec_free_context(&amp;codec_ctx);&#xA;    avformat_free_context(fmt_ctx);&#xA;    stop_capturing(fd);&#xA;    unmap_buffers();&#xA;    close(fd);&#xA;&#xA;    return 0;&#xA;}&#xA;</output>

    &#xA;