Recherche avancée

Médias (0)

Mot : - Tags -/xmlrpc

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

Autres articles (50)

  • Submit bugs and patches

    13 avril 2011

    Unfortunately a software is never perfect.
    If you think you have found a bug, report it using our ticket system. Please to help us to fix it by providing the following information : the browser you are using, including the exact version as precise an explanation as possible of the problem if possible, the steps taken resulting in the problem a link to the site / page in question
    If you think you have solved the bug, fill in a ticket and attach to it a corrective patch.
    You may also (...)

  • Support audio et vidéo HTML5

    10 avril 2011

    MediaSPIP utilise les balises HTML5 video et audio pour la lecture de documents multimedia en profitant des dernières innovations du W3C supportées par les navigateurs modernes.
    Pour les navigateurs plus anciens, le lecteur flash Flowplayer est utilisé.
    Le lecteur HTML5 utilisé a été spécifiquement créé pour MediaSPIP : il est complètement modifiable graphiquement pour correspondre à un thème choisi.
    Ces technologies permettent de distribuer vidéo et son à la fois sur des ordinateurs conventionnels (...)

  • De l’upload à la vidéo finale [version standalone]

    31 janvier 2010, par

    Le chemin d’un document audio ou vidéo dans SPIPMotion est divisé en trois étapes distinctes.
    Upload et récupération d’informations de la vidéo source
    Dans un premier temps, il est nécessaire de créer un article SPIP et de lui joindre le document vidéo "source".
    Au moment où ce document est joint à l’article, deux actions supplémentaires au comportement normal sont exécutées : La récupération des informations techniques des flux audio et video du fichier ; La génération d’une vignette : extraction d’une (...)

Sur d’autres sites (7569)

  • Unwrapping Matomo 5.2.0 – Bringing you enhanced security and performance

    25 décembre 2024, par Daniel Crough — Latest Releases

     As we tie a bow on 2024, we’re delighted to share our final gift of the year. Matomo 5.2.0 comes wrapped with new security features, privacy controls, and performance improvements to enhance your analytics experience.

     Enhanced security and privacy controls

    Image that shows the This Wasn’t Me link in password reset email.

    We’ve strengthened Matomo’s security framework with several key updates :

    • A new installer timestamp mechanism for on-premise installations creates a secure 72-hour installation window, preventing unauthorised access during setup
    • Enhanced account security features including a “This Wasn’t Me” link in password reset emails and location-based login alerts
    • The new Global List of Query URL parameters feature lets you refine tracking by excluding sensitive or unnecessary parameters from collection

    Tag manager improvements for better efficiency

    The Matomo Tag Manager now includes several features to streamline your workflow :

    • New Consent Management Platform (CMP) tags for CookieYes, OneTrust, and Axeptio, simplifying consent tracking implementatio.
    • A new copy feature for containers, tags, and triggers that reduces setup time and ensures consistency across multiple properties
    • Improved management tools for maintaining standardised tracking across websites

    Performance and reliability updates

    We’ve made technical improvements to enhance Matomo’s performance :

    Important to note : This release does not require any major database upgrade, making it easier to implement these improvements.

    Looking forward to 2025

    As we prepare to enter a new year, these updates reflect our ongoing commitment to providing privacy-focused analytics. We’re grateful to all our community contributors who have helped make this release possible. Special thanks to the Matomo community for their contributions to this release.

    Ready to explore these new features ? Update to Matomo 5.2.0 today and start the new year with enhanced security, efficiency, and control over your analytics data.

    From all of us at Matomo, thank you for being part of our journey. Here’s to another year of protecting privacy and empowering insights together !


    For a detailed overview of all changes and improvements, see our complete release notes or join the discussion in our community forums. If you’d like to contribute to making Matomo even better, learn more about getting involved with our open-source project.

  • 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.

    


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

    


        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;

  • FFmpeg WASM writeFile Stalls and Doesn't Complete in React App with Ant Design

    26 février, par raiyan khan

    I'm using FFmpeg WebAssembly (WASM) in a React app to process and convert a video file before uploading it. The goal is to resize the video to 720p using FFmpeg before sending it to the backend.

    &#xA;

    Problem :

    &#xA;

    Everything works up to fetching the file and confirming it's loaded into memory, but FFmpeg hangs at ffmpeg.writeFile() and does not proceed further. No errors are thrown.

    &#xA;

    Code Snippet :

    &#xA;

      &#xA;
    • Loading FFmpeg

      &#xA;

       const loadFFmpeg = async () => {&#xA; if (loaded) return; // Avoid reloading if &#xA; already loaded&#xA;&#xA; const baseURL = &#x27;https://unpkg.com/@ffmpeg/core@0.12.6/dist/umd&#x27;;&#xA; const ffmpeg = ffmpegRef.current;&#xA; ffmpeg.on(&#x27;log&#x27;, ({ message }) => {&#xA;     messageRef.current.innerHTML = message;&#xA;     console.log(message);&#xA; });&#xA; await ffmpeg.load({&#xA;     coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, &#x27;text/javascript&#x27;),&#xA;     wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, &#x27;application/wasm&#x27;),&#xA; });&#xA; setLoaded(true);&#xA; };&#xA;&#xA; useEffect(() => {&#xA; loadFFmpeg()&#xA; }, [])&#xA;

      &#xA;

    • &#xA;

    • Fetching and Writing File

      &#xA;

        const convertVideoTo720p = async (videoFile) => {&#xA;       console.log("Starting video &#xA;     conversion...");&#xA;&#xA;&#xA;&#xA; const { height } = await getVideoMetadata(videoFile);&#xA; console.log(`Video height: ${height}`);&#xA;&#xA; if (height &lt;= 720) {&#xA;     console.log("No conversion needed.");&#xA;     return videoFile;&#xA; }&#xA;&#xA; const ffmpeg = ffmpegRef.current;&#xA; console.log("FFmpeg instance loaded. Writing file to memory...");&#xA;&#xA; const fetchedFile = await fetchFile(videoFile);&#xA; console.log("File fetched successfully:", fetchedFile);&#xA;&#xA; console.log("Checking FFmpeg memory before writing...");&#xA; console.log(`File size: ${fetchedFile.length} bytes (~${(fetchedFile.length / 1024 / 1024).toFixed(2)} MB)`);&#xA;&#xA; if (!ffmpeg.isLoaded()) {&#xA;     console.error("FFmpeg is not fully loaded yet!");&#xA;     return;&#xA; }&#xA;&#xA; console.log("Memory seems okay. Writing file to FFmpeg...");&#xA; await ffmpeg.writeFile(&#x27;input.mp4&#x27;, fetchedFile);  // ❌ This line hangs, nothing after runs&#xA; console.log("File successfully written to FFmpeg memory.");&#xA;      };&#xA;

      &#xA;

    • &#xA;

    &#xA;

    Debugging Steps I've Tried :

    &#xA;

      &#xA;
    • Ensured FFmpeg is fully loaded before calling writeFile()&#xA;✅ ffmpeg.isLoaded() returns true.
    • &#xA;

    • Checked file fetch process :&#xA;✅ fetchFile(videoFile) successfully returns a Uint8Array.
    • &#xA;

    • Tried renaming the file to prevent caching issues&#xA;✅ Used a unique file name like video_${Date.now()}.mp4, but no change
    • &#xA;

    • Checked browser console for errors :&#xA;❌ No errors are displayed.
    • &#xA;

    • Tried skipping FFmpeg and uploading the raw file instead :&#xA;✅ Upload works fine without FFmpeg, so the issue is specific to FFmpeg.
    • &#xA;

    &#xA;

    Expected Behavior

    &#xA;

      &#xA;
    • ffmpeg.writeFile(&#x27;input.mp4&#x27;, fetchedFile); should complete and allow FFmpeg to process the video.
    • &#xA;

    &#xA;

    Actual Behavior

    &#xA;

      &#xA;
    • Execution stops at writeFile, and no errors are thrown.
    • &#xA;

    &#xA;

    Environment :

    &#xA;

      &#xA;
    • React : 18.x
    • &#xA;

    • FFmpeg WASM Version : @ffmpeg/ffmpeg@0.12.15
    • &#xA;

    • Browser : Chrome 121, Edge 120
    • &#xA;

    • Operating System : Windows 11
    • &#xA;

    &#xA;

    Question :&#xA;Why is FFmpeg's writeFile() stalling and never completing ?&#xA;How can I fix or further debug this issue ?

    &#xA;

    Here is my full code :

    &#xA;

    &#xD;&#xA;
    &#xD;&#xA;
    import { useNavigate } from "react-router-dom";&#xA;import { useEffect, useRef, useState } from &#x27;react&#x27;;&#xA;import { Form, Input, Button, Select, Space } from &#x27;antd&#x27;;&#xA;const { Option } = Select;&#xA;import { FaAngleLeft } from "react-icons/fa6";&#xA;import { message, Upload } from &#x27;antd&#x27;;&#xA;import { CiCamera } from "react-icons/ci";&#xA;import { IoVideocamOutline } from "react-icons/io5";&#xA;import { useCreateWorkoutVideoMutation } from "../../../redux/features/workoutVideo/workoutVideoApi";&#xA;import { convertVideoTo720p } from "../../../utils/ffmpegHelper";&#xA;import { FFmpeg } from &#x27;@ffmpeg/ffmpeg&#x27;;&#xA;import { fetchFile, toBlobURL } from &#x27;@ffmpeg/util&#x27;;&#xA;&#xA;&#xA;const AddWorkoutVideo = () => {&#xA;    const [videoFile, setVideoFile] = useState(null);&#xA;    const [imageFile, setImageFile] = useState(null);&#xA;    const [loaded, setLoaded] = useState(false);&#xA;    const ffmpegRef = useRef(new FFmpeg());&#xA;    const videoRef = useRef(null);&#xA;    const messageRef = useRef(null);&#xA;    const [form] = Form.useForm();&#xA;    const [createWorkoutVideo, { isLoading }] = useCreateWorkoutVideoMutation()&#xA;    const navigate = useNavigate();&#xA;&#xA;    const videoFileRef = useRef(null); // Use a ref instead of state&#xA;&#xA;&#xA;    // Handle Video Upload&#xA;    const handleVideoChange = ({ file }) => {&#xA;        setVideoFile(file.originFileObj);&#xA;    };&#xA;&#xA;    // Handle Image Upload&#xA;    const handleImageChange = ({ file }) => {&#xA;        setImageFile(file.originFileObj);&#xA;    };&#xA;&#xA;    // Load FFmpeg core if needed (optional if you want to preload)&#xA;    const loadFFmpeg = async () => {&#xA;        if (loaded) return; // Avoid reloading if already loaded&#xA;&#xA;        const baseURL = &#x27;https://unpkg.com/@ffmpeg/core@0.12.6/dist/umd&#x27;;&#xA;        const ffmpeg = ffmpegRef.current;&#xA;        ffmpeg.on(&#x27;log&#x27;, ({ message }) => {&#xA;            messageRef.current.innerHTML = message;&#xA;            console.log(message);&#xA;        });&#xA;        await ffmpeg.load({&#xA;            coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, &#x27;text/javascript&#x27;),&#xA;            wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, &#x27;application/wasm&#x27;),&#xA;        });&#xA;        setLoaded(true);&#xA;    };&#xA;&#xA;    useEffect(() => {&#xA;        loadFFmpeg()&#xA;    }, [])&#xA;&#xA;    // Helper: Get video metadata (width and height)&#xA;    const getVideoMetadata = (file) => {&#xA;        return new Promise((resolve, reject) => {&#xA;            const video = document.createElement(&#x27;video&#x27;);&#xA;            video.preload = &#x27;metadata&#x27;;&#xA;            video.onloadedmetadata = () => {&#xA;                resolve({ width: video.videoWidth, height: video.videoHeight });&#xA;            };&#xA;            video.onerror = () => reject(new Error(&#x27;Could not load video metadata&#x27;));&#xA;            video.src = URL.createObjectURL(file);&#xA;        });&#xA;    };&#xA;&#xA;    // Inline conversion helper function&#xA;    // const convertVideoTo720p = async (videoFile) => {&#xA;    //     // Check the video resolution first&#xA;    //     const { height } = await getVideoMetadata(videoFile);&#xA;    //     if (height &lt;= 720) {&#xA;    //         // No conversion needed&#xA;    //         return videoFile;&#xA;    //     }&#xA;    //     const ffmpeg = ffmpegRef.current;&#xA;    //     // Load ffmpeg if not already loaded&#xA;    //     // await ffmpeg.load({&#xA;    //     //     coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, &#x27;text/javascript&#x27;),&#xA;    //     //     wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, &#x27;application/wasm&#x27;),&#xA;    //     // });&#xA;    //     // Write the input file to the ffmpeg virtual FS&#xA;    //     await ffmpeg.writeFile(&#x27;input.mp4&#x27;, await fetchFile(videoFile));&#xA;    //     // Convert video to 720p (scale filter maintains aspect ratio)&#xA;    //     await ffmpeg.exec([&#x27;-i&#x27;, &#x27;input.mp4&#x27;, &#x27;-vf&#x27;, &#x27;scale=-1:720&#x27;, &#x27;output.mp4&#x27;]);&#xA;    //     // Read the output file&#xA;    //     const data = await ffmpeg.readFile(&#x27;output.mp4&#x27;);&#xA;    //     console.log(data, &#x27;data from convertVideoTo720p&#x27;);&#xA;    //     const videoBlob = new Blob([data.buffer], { type: &#x27;video/mp4&#x27; });&#xA;    //     return new File([videoBlob], &#x27;output.mp4&#x27;, { type: &#x27;video/mp4&#x27; });&#xA;    // };&#xA;    const convertVideoTo720p = async (videoFile) => {&#xA;        console.log("Starting video conversion...");&#xA;&#xA;        // Check the video resolution first&#xA;        const { height } = await getVideoMetadata(videoFile);&#xA;        console.log(`Video height: ${height}`);&#xA;&#xA;        if (height &lt;= 720) {&#xA;            console.log("No conversion needed. Returning original file.");&#xA;            return videoFile;&#xA;        }&#xA;&#xA;        const ffmpeg = ffmpegRef.current;&#xA;        console.log("FFmpeg instance loaded. Writing file to memory...");&#xA;&#xA;        // await ffmpeg.writeFile(&#x27;input.mp4&#x27;, await fetchFile(videoFile));&#xA;        // console.log("File written. Starting conversion...");&#xA;        console.log("Fetching file for FFmpeg:", videoFile);&#xA;        const fetchedFile = await fetchFile(videoFile);&#xA;        console.log("File fetched successfully:", fetchedFile);&#xA;        console.log("Checking FFmpeg memory before writing...");&#xA;        console.log(`File size: ${fetchedFile.length} bytes (~${(fetchedFile.length / 1024 / 1024).toFixed(2)} MB)`);&#xA;&#xA;        if (fetchedFile.length > 50 * 1024 * 1024) { // 50MB limit&#xA;            console.error("File is too large for FFmpeg WebAssembly!");&#xA;            message.error("File too large. Try a smaller video.");&#xA;            return;&#xA;        }&#xA;&#xA;        console.log("Memory seems okay. Writing file to FFmpeg...");&#xA;        const fileName = `video_${Date.now()}.mp4`; // Generate a unique name&#xA;        console.log(`Using filename: ${fileName}`);&#xA;&#xA;        await ffmpeg.writeFile(fileName, fetchedFile);&#xA;        console.log(`File successfully written to FFmpeg memory as ${fileName}.`);&#xA;&#xA;        await ffmpeg.exec([&#x27;-i&#x27;, &#x27;input.mp4&#x27;, &#x27;-vf&#x27;, &#x27;scale=-1:720&#x27;, &#x27;output.mp4&#x27;]);&#xA;        console.log("Conversion completed. Reading output file...");&#xA;&#xA;        const data = await ffmpeg.readFile(&#x27;output.mp4&#x27;);&#xA;        console.log("File read successful. Creating new File object.");&#xA;&#xA;        const videoBlob = new Blob([data.buffer], { type: &#x27;video/mp4&#x27; });&#xA;        const convertedFile = new File([videoBlob], &#x27;output.mp4&#x27;, { type: &#x27;video/mp4&#x27; });&#xA;&#xA;        console.log(convertedFile, "converted video from convertVideoTo720p");&#xA;&#xA;        return convertedFile;&#xA;    };&#xA;&#xA;&#xA;    const onFinish = async (values) => {&#xA;        // Ensure a video is selected&#xA;        if (!videoFileRef.current) {&#xA;            message.error("Please select a video file.");&#xA;            return;&#xA;        }&#xA;&#xA;        // Create FormData&#xA;        const formData = new FormData();&#xA;        if (imageFile) {&#xA;            formData.append("image", imageFile);&#xA;        }&#xA;&#xA;        try {&#xA;            message.info("Processing video. Please wait...");&#xA;&#xA;            // Convert the video to 720p only if needed&#xA;            const convertedVideo = await convertVideoTo720p(videoFileRef.current);&#xA;            console.log(convertedVideo, &#x27;convertedVideo from onFinish&#x27;);&#xA;&#xA;            formData.append("media", videoFileRef.current);&#xA;&#xA;            formData.append("data", JSON.stringify(values));&#xA;&#xA;            // Upload manually to the backend&#xA;            const response = await createWorkoutVideo(formData).unwrap();&#xA;            console.log(response, &#x27;response from add video&#x27;);&#xA;&#xA;            message.success("Video added successfully!");&#xA;            form.resetFields(); // Reset form&#xA;            setVideoFile(null); // Clear file&#xA;&#xA;        } catch (error) {&#xA;            message.error(error.data?.message || "Failed to add video.");&#xA;        }&#xA;&#xA;        // if (videoFile) {&#xA;        //     message.info("Processing video. Please wait...");&#xA;        //     try {&#xA;        //         // Convert the video to 720p only if needed&#xA;        //         const convertedVideo = await convertVideoTo720p(videoFile);&#xA;        //         formData.append("media", convertedVideo);&#xA;        //     } catch (conversionError) {&#xA;        //         message.error("Video conversion failed.");&#xA;        //         return;&#xA;        //     }&#xA;        // }&#xA;        // formData.append("data", JSON.stringify(values)); // Convert text fields to JSON&#xA;&#xA;        // try {&#xA;        //     const response = await createWorkoutVideo(formData).unwrap();&#xA;        //     console.log(response, &#x27;response from add video&#x27;);&#xA;&#xA;        //     message.success("Video added successfully!");&#xA;        //     form.resetFields(); // Reset form&#xA;        //     setFile(null); // Clear file&#xA;        // } catch (error) {&#xA;        //     message.error(error.data?.message || "Failed to add video.");&#xA;        // }&#xA;    };&#xA;&#xA;    const handleBackButtonClick = () => {&#xA;        navigate(-1); // This takes the user back to the previous page&#xA;    };&#xA;&#xA;    const videoUploadProps = {&#xA;        name: &#x27;video&#x27;,&#xA;        // action: &#x27;https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload&#x27;,&#xA;        // headers: {&#xA;        //     authorization: &#x27;authorization-text&#x27;,&#xA;        // },&#xA;        // beforeUpload: (file) => {&#xA;        //     const isVideo = file.type.startsWith(&#x27;video/&#x27;);&#xA;        //     if (!isVideo) {&#xA;        //         message.error(&#x27;You can only upload video files!&#x27;);&#xA;        //     }&#xA;        //     return isVideo;&#xA;        // },&#xA;        // onChange(info) {&#xA;        //     if (info.file.status === &#x27;done&#x27;) {&#xA;        //         message.success(`${info.file.name} video uploaded successfully`);&#xA;        //     } else if (info.file.status === &#x27;error&#x27;) {&#xA;        //         message.error(`${info.file.name} video upload failed.`);&#xA;        //     }&#xA;        // },&#xA;        beforeUpload: (file) => {&#xA;            const isVideo = file.type.startsWith(&#x27;video/&#x27;);&#xA;            if (!isVideo) {&#xA;                message.error(&#x27;You can only upload video files!&#x27;);&#xA;                return Upload.LIST_IGNORE; // Prevents the file from being added to the list&#xA;            }&#xA;            videoFileRef.current = file; // Store file in ref&#xA;            // setVideoFile(file); // Store the file in state instead of uploading it automatically&#xA;            return false; // Prevent auto-upload&#xA;        },&#xA;    };&#xA;&#xA;    const imageUploadProps = {&#xA;        name: &#x27;image&#x27;,&#xA;        action: &#x27;https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload&#x27;,&#xA;        headers: {&#xA;            authorization: &#x27;authorization-text&#x27;,&#xA;        },&#xA;        beforeUpload: (file) => {&#xA;            const isImage = file.type.startsWith(&#x27;image/&#x27;);&#xA;            if (!isImage) {&#xA;                message.error(&#x27;You can only upload image files!&#x27;);&#xA;            }&#xA;            return isImage;&#xA;        },&#xA;        onChange(info) {&#xA;            if (info.file.status === &#x27;done&#x27;) {&#xA;                message.success(`${info.file.name} image uploaded successfully`);&#xA;            } else if (info.file.status === &#x27;error&#x27;) {&#xA;                message.error(`${info.file.name} image upload failed.`);&#xA;            }&#xA;        },&#xA;    };&#xA;    return (&#xA;        &lt;>&#xA;            <div classname="flex items-center gap-2 text-xl cursor-pointer">&#xA;                <faangleleft></faangleleft>&#xA;                <h1 classname="font-semibold">Add Video</h1>&#xA;            </div>&#xA;            <div classname="rounded-lg py-4 border-[#79CDFF] border-2 shadow-lg mt-8 bg-white">&#xA;                <div classname="space-y-[24px] min-h-[83vh] bg-light-gray rounded-2xl">&#xA;                    <h3 classname="text-2xl text-[#174C6B] mb-4 border-b border-[#79CDFF]/50 pb-3 pl-16 font-semibold">&#xA;                        Adding Video&#xA;                    </h3>&#xA;                    <div classname="w-full px-16">&#xA;                        / style={{ maxWidth: 600, margin: &#x27;0 auto&#x27; }}&#xA;                        >&#xA;                            {/* Section 1 */}&#xA;                            {/* <space direction="vertical" style="{{"> */}&#xA;                            {/* <space size="large" direction="horizontal" classname="responsive-space"> */}&#xA;                            <div classname="grid grid-cols-2 gap-8 mt-8">&#xA;                                <div>&#xA;                                    <space size="large" direction="horizontal" classname="responsive-space-section-2">&#xA;&#xA;                                        {/* Video */}&#xA;                                        Upload Video}&#xA;                                            name="media"&#xA;                                            className="responsive-form-item"&#xA;                                        // rules={[{ required: true, message: &#x27;Please enter the package amount!&#x27; }]}&#xA;                                        >&#xA;                                            <upload maxcount="{1}">&#xA;                                                <button style="{{" solid="solid">&#xA;                                                    <span style="{{" 600="600">Select a video</span>&#xA;                                                    <iovideocamoutline size="{20}" color="#174C6B"></iovideocamoutline>&#xA;                                                </button>&#xA;                                            </upload>&#xA;                                        &#xA;&#xA;                                        {/* Thumbnail */}&#xA;                                        Upload Image}&#xA;                                            name="image"&#xA;                                            className="responsive-form-item"&#xA;                                        // rules={[{ required: true, message: &#x27;Please enter the package amount!&#x27; }]}&#xA;                                        >&#xA;                                            <upload maxcount="{1}">&#xA;                                                <button style="{{" solid="solid">&#xA;                                                    <span style="{{" 600="600">Select an image</span>&#xA;                                                    <cicamera size="{25}" color="#174C6B"></cicamera>&#xA;                                                </button>&#xA;                                            </upload>&#xA;                                        &#xA;&#xA;                                        {/* Title */}&#xA;                                        Video Title}&#xA;                                            name="name"&#xA;                                            className="responsive-form-item-section-2"&#xA;                                        >&#xA;                                            <input type="text" placeholder="Enter video title" style="{{&amp;#xA;" solid="solid" />&#xA;                                        &#xA;                                    </space>&#xA;                                </div>&#xA;                            </div>&#xA;&#xA;                            {/* </space> */}&#xA;                            {/* </space> */}&#xA;&#xA;&#xA;                            {/* Submit Button */}&#xA;                            &#xA;                                <div classname="p-4 mt-10 text-center mx-auto flex items-center justify-center">&#xA;                                    &#xA;                                        <span classname="text-white font-semibold">{isLoading ? &#x27;Uploading...&#x27; : &#x27;Upload&#x27;}</span>&#xA;                                    &#xA;                                </div>&#xA;                            &#xA;                        &#xA;                    </div>&#xA;                </div>&#xA;            </div>&#xA;        >&#xA;    )&#xA;}&#xA;&#xA;export default AddWorkoutVideo

    &#xD;&#xA;

    &#xD;&#xA;

    &#xD;&#xA;&#xA;

    Would appreciate any insights or suggestions. Thanks !

    &#xA;