
Recherche avancée
Autres articles (50)
-
Submit bugs and patches
13 avril 2011Unfortunately 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 2011MediaSPIP 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, parLe 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 -
How to install ffmpeg on a Windows Dockerhub image ?
18 janvier, par Youssef KharoufiI 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;
using System;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;

public class Program
{
 public static async Task Main(string[] args)
 {
 var result = new DockerTaskResult();
 try
 {
 // Path to the JSON input file
 string jsonInputPath = @"C:\Users\ykharoufi\source\repos\Renderer\Renderer\Json\task.json";

 // Check if the JSON file exists
 if (!File.Exists(jsonInputPath))
 {
 throw new FileNotFoundException($"JSON input file not found at path: {jsonInputPath}");
 }

 // Read the JSON content
 string jsonContent = File.ReadAllText(jsonInputPath);

 try
 {
 // Deserialize the JSON into a DockerTask object
 DockerTask task = JsonSerializer.Deserialize<dockertask>(jsonContent);
 if (task == null)
 {
 throw new Exception("Failed to deserialize the task from JSON.");
 }

 // Validate the input paths
 if (string.IsNullOrEmpty(task.InputFileRepoPath) || !File.Exists(task.InputFileRepoPath))
 {
 throw new Exception($"Input file path is invalid or does not exist: {task.InputFileRepoPath}");
 }

 if (string.IsNullOrEmpty(task.OutputFileRepoPath) || !Directory.Exists(task.OutputFileRepoPath))
 {
 throw new Exception($"Output directory path is invalid or does not exist: {task.OutputFileRepoPath}");
 }

 // Initialize the Docker worker and run the task
 var worker = new DockerWorker();
 var success = await worker.RunDockerTaskAsync(task);

 if (success.Success)
 {
 result.Success = true;
 result.Message = "Command executed successfully!";

 // Check the output directory for files
 if (Directory.Exists(task.OutputFileRepoPath))
 {
 result.OutputFiles = Directory.GetFiles(task.OutputFileRepoPath);
 }
 }
 else
 {
 result.Success = false;
 result.Message = "Failed to execute the command.";
 result.ErrorDetails = success.ErrorDetails;
 }
 }
 catch (JsonException)
 {
 // Handle invalid JSON format
 result.Success = false;
 result.Message = "Invalid JSON format.";
 result.ErrorDetails = "Invalid data entry";
 }
 }
 catch (Exception ex)
 {
 result.Success = false;
 result.Message = "An error occurred during execution.";
 result.ErrorDetails = ex.Message;
 }
 finally
 {
 // Serialize the result to JSON and write to console
 string outputJson = JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true });
 Console.WriteLine(outputJson);
 }
 }
}

 using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
using Docker.DotNet;
using Docker.DotNet.Models;
using Renderer.Models;

public class DockerWorker
{
 private readonly DockerClient _dockerClient;

 public DockerWorker()
 {
 Console.WriteLine("Initializing Docker client...");
 _dockerClient = new DockerClientConfiguration(
 new Uri("npipe://./pipe/docker_engine")) // Windows Docker URI
 .CreateClient();
 Console.WriteLine("Docker client initialized.");
 }

 public async Task<dockertaskresult> RunDockerTaskAsync(DockerTask task)
 {
 var result = new DockerTaskResult();

 try
 {
 Console.WriteLine("Starting Docker task...");
 Console.WriteLine($"Image: {task.ImageNaming}");
 Console.WriteLine($"Container: {task.ContainerNaming}");
 Console.WriteLine($"Input Path: {task.InputFileRepoPath}");
 Console.WriteLine($"Output Path: {task.OutputFileRepoPath}");
 Console.WriteLine($"Command: {task.CommandDef}");

 // Ensure the Docker image exists
 Console.WriteLine("Checking if Docker image exists...");
 var imageCheckResult = await EnsureImageExists(task.ImageNaming);
 if (!imageCheckResult.Success)
 {
 result.Success = false;
 result.Message = imageCheckResult.Message;
 result.ErrorDetails = imageCheckResult.ErrorDetails;
 return result;
 }
 Console.WriteLine("Docker image verified.");

 // Determine platform
 var platform = await GetImagePlatform(task.ImageNaming);
 Console.WriteLine($"Detected image platform: {platform}");

 // Translate paths
 string inputVolume, outputVolume;
 if (platform == "linux")
 {
 inputVolume = $"{task.InputFileRepoPath.Replace("C:\\", "/mnt/c/").Replace("\\", "/")}:/app/input";
 outputVolume = $"{task.OutputFileRepoPath.Replace("C:\\", "/mnt/c/").Replace("\\", "/")}:/app/output";
 }
 else if (platform == "windows")
 {
 string inputDir = Path.GetFullPath(Path.GetDirectoryName(task.InputFileRepoPath)).TrimEnd('\\');
 string outputDir = Path.GetFullPath(task.OutputFileRepoPath).TrimEnd('\\');

 if (!Directory.Exists(inputDir))
 {
 throw new Exception($"Input directory does not exist: {inputDir}");
 }
 if (!Directory.Exists(outputDir))
 {
 throw new Exception($"Output directory does not exist: {outputDir}");
 }

 inputVolume = $"{inputDir}:C:\\app\\input";
 outputVolume = $"{outputDir}:C:\\app\\output";

 Console.WriteLine($"Input volume: {inputVolume}");
 Console.WriteLine($"Output volume: {outputVolume}");
 }
 else
 {
 throw new Exception($"Unsupported platform: {platform}");
 }

 // Create container
 Console.WriteLine("Creating Docker container...");
 var containerResponse = await _dockerClient.Containers.CreateContainerAsync(new CreateContainerParameters
 {
 Image = task.ImageNaming,
 Name = task.ContainerNaming,
 HostConfig = new HostConfig
 {
 Binds = new List<string> { inputVolume, outputVolume },
 AutoRemove = true
 },
 Cmd = new[] { platform == "linux" ? "bash" : "cmd.exe", "/c", task.CommandDef }
 });

 if (string.IsNullOrEmpty(containerResponse.ID))
 {
 throw new Exception("Failed to create Docker container.");
 }
 Console.WriteLine($"Container created with ID: {containerResponse.ID}");

 // Start container
 Console.WriteLine("Starting container...");
 bool started = await _dockerClient.Containers.StartContainerAsync(containerResponse.ID, new ContainerStartParameters());
 if (!started)
 {
 throw new Exception($"Failed to start container: {task.ContainerNaming}");
 }

 // Wait for container to finish
 Console.WriteLine("Waiting for container to finish...");
 var waitResponse = await _dockerClient.Containers.WaitContainerAsync(containerResponse.ID);

 if (waitResponse.StatusCode != 0)
 {
 Console.WriteLine($"Container exited with error code: {waitResponse.StatusCode}");
 await FetchContainerLogs(containerResponse.ID);
 throw new Exception($"Container exited with non-zero status code: {waitResponse.StatusCode}");
 }

 // Fetch logs
 Console.WriteLine("Fetching container logs...");
 await FetchContainerLogs(containerResponse.ID);

 result.Success = true;
 result.Message = "Docker task completed successfully.";
 return result;
 }
 catch (Exception ex)
 {
 Console.WriteLine($"Error: {ex.Message}");
 result.Success = false;
 result.Message = "An error occurred during execution.";
 result.ErrorDetails = ex.Message;
 return result;
 }
 }

 private async Task<string> GetImagePlatform(string imageName)
 {
 try
 {
 Console.WriteLine($"Inspecting Docker image: {imageName}...");
 var imageDetails = await _dockerClient.Images.InspectImageAsync(imageName);
 Console.WriteLine($"Image platform: {imageDetails.Os}");
 return imageDetails.Os.ToLower();
 }
 catch (Exception ex)
 {
 throw new Exception($"Failed to inspect image: {ex.Message}");
 }
 }

 private async Task<dockertaskresult> EnsureImageExists(string imageName)
 {
 var result = new DockerTaskResult();
 try
 {
 Console.WriteLine($"Pulling Docker image: {imageName}...");
 await _dockerClient.Images.CreateImageAsync(
 new ImagesCreateParameters { FromImage = imageName, Tag = "latest" },
 null,
 new Progress<jsonmessage>()
 );
 result.Success = true;
 result.Message = "Docker image is available.";
 }
 catch (Exception ex)
 {
 result.Success = false;
 result.Message = $"Failed to pull Docker image: {imageName}";
 result.ErrorDetails = ex.Message;
 }
 return result;
 }

 private async Task FetchContainerLogs(string containerId)
 {
 try
 {
 Console.WriteLine($"Fetching logs for container: {containerId}...");
 var logs = await _dockerClient.Containers.GetContainerLogsAsync(
 containerId,
 new ContainerLogsParameters { ShowStdout = true, ShowStderr = true });

 using (var reader = new StreamReader(logs))
 {
 string logLine;
 while ((logLine = await reader.ReadLineAsync()) != null)
 {
 Console.WriteLine(logLine);
 }
 }
 }
 catch (Exception ex)
 {
 Console.WriteLine($"Failed to fetch logs: {ex.Message}");
 }
 }
}

 {
 "ImageNaming": "khuser/windowsimage:latest",
 "ContainerNaming": "custom-worker-container",
 "InputFileRepoPath": "C:/Users/user/source/repos/Renderer/Renderer/wwwroot/audio.mp4",
 "OutputFileRepoPath": "C:/Users/user/Desktop/output/",
 "CommandDef": "ffmpeg -i C:\\app\\input\\audio.mp4 -c copy C:\\app\\output\\copiedAudio.mp4"
</jsonmessage></dockertaskresult></string></string></dockertaskresult></dockertask>


}. 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... @'ffmpeg' 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 :

`# Use Windows Server Core as the base image
FROM mcr.microsoft.com/windows/server:ltsc2022

# Set the working directory
WORKDIR /app

# Install required tools (FFmpeg and Visual C++ Redistributable)
RUN powershell -Command \
 $ErrorActionPreference = 'Stop'; \
 # Install Visual C++ Redistributable
 Invoke-WebRequest -Uri https://aka.ms/vs/16/release/vc_redist.x64.exe -OutFile vc_redist.x64.exe; \
 Start-Process -FilePath vc_redist.x64.exe -ArgumentList '/install', '/quiet', '/norestart' -NoNewWindow -Wait; \
 Remove-Item -Force vc_redist.x64.exe; \
 # Download FFmpeg
 Invoke-WebRequest -Uri https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-n7.1-latest-win64-gpl-7.1.zip -OutFile ffmpeg.zip; \
 # Extract FFmpeg
 Expand-Archive -Path ffmpeg.zip -DestinationPath C:\ffmpeg; \
 Remove-Item -Force ffmpeg.zip; \
 # Debug step: Verify FFmpeg extraction
 Write-Output "FFmpeg extracted to C:\\ffmpeg"; \
 dir C:\ffmpeg; \
 dir C:\ffmpeg\ffmpeg-n7.1-latest-win64-gpl-7.1\bin

# Add FFmpeg to PATH permanently
ENV PATH="C:\\ffmpeg\\ffmpeg-n7.1-latest-win64-gpl-7.1\\bin;${PATH}"

# Verify FFmpeg installation
RUN ["cmd", "/S", "/C", "ffmpeg -version"]

# Copy required files to the container
COPY ./ /app/

# Default to a PowerShell session
CMD ["C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", "-NoExit"]
`



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


-
FFmpeg WASM writeFile Stalls and Doesn't Complete in React App with Ant Design
26 février, par raiyan khanI'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.


Problem :


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.


Code Snippet :


- 

-
Loading FFmpeg


const loadFFmpeg = async () => {
 if (loaded) return; // Avoid reloading if 
 already loaded

 const baseURL = 'https://unpkg.com/@ffmpeg/core@0.12.6/dist/umd';
 const ffmpeg = ffmpegRef.current;
 ffmpeg.on('log', ({ message }) => {
 messageRef.current.innerHTML = message;
 console.log(message);
 });
 await ffmpeg.load({
 coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, 'text/javascript'),
 wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, 'application/wasm'),
 });
 setLoaded(true);
 };

 useEffect(() => {
 loadFFmpeg()
 }, [])



-
Fetching and Writing File


const convertVideoTo720p = async (videoFile) => {
 console.log("Starting video 
 conversion...");



 const { height } = await getVideoMetadata(videoFile);
 console.log(`Video height: ${height}`);

 if (height <= 720) {
 console.log("No conversion needed.");
 return videoFile;
 }

 const ffmpeg = ffmpegRef.current;
 console.log("FFmpeg instance loaded. Writing file to memory...");

 const fetchedFile = await fetchFile(videoFile);
 console.log("File fetched successfully:", fetchedFile);

 console.log("Checking FFmpeg memory before writing...");
 console.log(`File size: ${fetchedFile.length} bytes (~${(fetchedFile.length / 1024 / 1024).toFixed(2)} MB)`);

 if (!ffmpeg.isLoaded()) {
 console.error("FFmpeg is not fully loaded yet!");
 return;
 }

 console.log("Memory seems okay. Writing file to FFmpeg...");
 await ffmpeg.writeFile('input.mp4', fetchedFile); // ❌ This line hangs, nothing after runs
 console.log("File successfully written to FFmpeg memory.");
 };









Debugging Steps I've Tried :


- 

- Ensured FFmpeg is fully loaded before calling
writeFile()

✅ffmpeg.isLoaded()
returnstrue
. - Checked file fetch process :
✅
fetchFile(videoFile)
successfully returns aUint8Array
. - Tried renaming the file to prevent caching issues
✅ Used a unique file name like
video_${Date.now()}.mp4
, but no change - Checked browser console for errors :
❌ No errors are displayed.
- Tried skipping FFmpeg and uploading the raw file instead :
✅ Upload works fine without FFmpeg, so the issue is specific to FFmpeg.












Expected Behavior


- 

ffmpeg.writeFile('input.mp4', fetchedFile);
should complete and allow FFmpeg to process the video.




Actual Behavior


- 

- Execution stops at
writeFile
, and no errors are thrown.




Environment :


- 

- React : 18.x
- FFmpeg WASM Version : @ffmpeg/ffmpeg@0.12.15
- Browser : Chrome 121, Edge 120
- Operating System : Windows 11










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

Here is my full code :




import { useNavigate } from "react-router-dom";
import { useEffect, useRef, useState } from 'react';
import { Form, Input, Button, Select, Space } from 'antd';
const { Option } = Select;
import { FaAngleLeft } from "react-icons/fa6";
import { message, Upload } from 'antd';
import { CiCamera } from "react-icons/ci";
import { IoVideocamOutline } from "react-icons/io5";
import { useCreateWorkoutVideoMutation } from "../../../redux/features/workoutVideo/workoutVideoApi";
import { convertVideoTo720p } from "../../../utils/ffmpegHelper";
import { FFmpeg } from '@ffmpeg/ffmpeg';
import { fetchFile, toBlobURL } from '@ffmpeg/util';


const AddWorkoutVideo = () => {
 const [videoFile, setVideoFile] = useState(null);
 const [imageFile, setImageFile] = useState(null);
 const [loaded, setLoaded] = useState(false);
 const ffmpegRef = useRef(new FFmpeg());
 const videoRef = useRef(null);
 const messageRef = useRef(null);
 const [form] = Form.useForm();
 const [createWorkoutVideo, { isLoading }] = useCreateWorkoutVideoMutation()
 const navigate = useNavigate();

 const videoFileRef = useRef(null); // Use a ref instead of state


 // Handle Video Upload
 const handleVideoChange = ({ file }) => {
 setVideoFile(file.originFileObj);
 };

 // Handle Image Upload
 const handleImageChange = ({ file }) => {
 setImageFile(file.originFileObj);
 };

 // Load FFmpeg core if needed (optional if you want to preload)
 const loadFFmpeg = async () => {
 if (loaded) return; // Avoid reloading if already loaded

 const baseURL = 'https://unpkg.com/@ffmpeg/core@0.12.6/dist/umd';
 const ffmpeg = ffmpegRef.current;
 ffmpeg.on('log', ({ message }) => {
 messageRef.current.innerHTML = message;
 console.log(message);
 });
 await ffmpeg.load({
 coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, 'text/javascript'),
 wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, 'application/wasm'),
 });
 setLoaded(true);
 };

 useEffect(() => {
 loadFFmpeg()
 }, [])

 // Helper: Get video metadata (width and height)
 const getVideoMetadata = (file) => {
 return new Promise((resolve, reject) => {
 const video = document.createElement('video');
 video.preload = 'metadata';
 video.onloadedmetadata = () => {
 resolve({ width: video.videoWidth, height: video.videoHeight });
 };
 video.onerror = () => reject(new Error('Could not load video metadata'));
 video.src = URL.createObjectURL(file);
 });
 };

 // Inline conversion helper function
 // const convertVideoTo720p = async (videoFile) => {
 // // Check the video resolution first
 // const { height } = await getVideoMetadata(videoFile);
 // if (height <= 720) {
 // // No conversion needed
 // return videoFile;
 // }
 // const ffmpeg = ffmpegRef.current;
 // // Load ffmpeg if not already loaded
 // // await ffmpeg.load({
 // // coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, 'text/javascript'),
 // // wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, 'application/wasm'),
 // // });
 // // Write the input file to the ffmpeg virtual FS
 // await ffmpeg.writeFile('input.mp4', await fetchFile(videoFile));
 // // Convert video to 720p (scale filter maintains aspect ratio)
 // await ffmpeg.exec(['-i', 'input.mp4', '-vf', 'scale=-1:720', 'output.mp4']);
 // // Read the output file
 // const data = await ffmpeg.readFile('output.mp4');
 // console.log(data, 'data from convertVideoTo720p');
 // const videoBlob = new Blob([data.buffer], { type: 'video/mp4' });
 // return new File([videoBlob], 'output.mp4', { type: 'video/mp4' });
 // };
 const convertVideoTo720p = async (videoFile) => {
 console.log("Starting video conversion...");

 // Check the video resolution first
 const { height } = await getVideoMetadata(videoFile);
 console.log(`Video height: ${height}`);

 if (height <= 720) {
 console.log("No conversion needed. Returning original file.");
 return videoFile;
 }

 const ffmpeg = ffmpegRef.current;
 console.log("FFmpeg instance loaded. Writing file to memory...");

 // await ffmpeg.writeFile('input.mp4', await fetchFile(videoFile));
 // console.log("File written. Starting conversion...");
 console.log("Fetching file for FFmpeg:", videoFile);
 const fetchedFile = await fetchFile(videoFile);
 console.log("File fetched successfully:", fetchedFile);
 console.log("Checking FFmpeg memory before writing...");
 console.log(`File size: ${fetchedFile.length} bytes (~${(fetchedFile.length / 1024 / 1024).toFixed(2)} MB)`);

 if (fetchedFile.length > 50 * 1024 * 1024) { // 50MB limit
 console.error("File is too large for FFmpeg WebAssembly!");
 message.error("File too large. Try a smaller video.");
 return;
 }

 console.log("Memory seems okay. Writing file to FFmpeg...");
 const fileName = `video_${Date.now()}.mp4`; // Generate a unique name
 console.log(`Using filename: ${fileName}`);

 await ffmpeg.writeFile(fileName, fetchedFile);
 console.log(`File successfully written to FFmpeg memory as ${fileName}.`);

 await ffmpeg.exec(['-i', 'input.mp4', '-vf', 'scale=-1:720', 'output.mp4']);
 console.log("Conversion completed. Reading output file...");

 const data = await ffmpeg.readFile('output.mp4');
 console.log("File read successful. Creating new File object.");

 const videoBlob = new Blob([data.buffer], { type: 'video/mp4' });
 const convertedFile = new File([videoBlob], 'output.mp4', { type: 'video/mp4' });

 console.log(convertedFile, "converted video from convertVideoTo720p");

 return convertedFile;
 };


 const onFinish = async (values) => {
 // Ensure a video is selected
 if (!videoFileRef.current) {
 message.error("Please select a video file.");
 return;
 }

 // Create FormData
 const formData = new FormData();
 if (imageFile) {
 formData.append("image", imageFile);
 }

 try {
 message.info("Processing video. Please wait...");

 // Convert the video to 720p only if needed
 const convertedVideo = await convertVideoTo720p(videoFileRef.current);
 console.log(convertedVideo, 'convertedVideo from onFinish');

 formData.append("media", videoFileRef.current);

 formData.append("data", JSON.stringify(values));

 // Upload manually to the backend
 const response = await createWorkoutVideo(formData).unwrap();
 console.log(response, 'response from add video');

 message.success("Video added successfully!");
 form.resetFields(); // Reset form
 setVideoFile(null); // Clear file

 } catch (error) {
 message.error(error.data?.message || "Failed to add video.");
 }

 // if (videoFile) {
 // message.info("Processing video. Please wait...");
 // try {
 // // Convert the video to 720p only if needed
 // const convertedVideo = await convertVideoTo720p(videoFile);
 // formData.append("media", convertedVideo);
 // } catch (conversionError) {
 // message.error("Video conversion failed.");
 // return;
 // }
 // }
 // formData.append("data", JSON.stringify(values)); // Convert text fields to JSON

 // try {
 // const response = await createWorkoutVideo(formData).unwrap();
 // console.log(response, 'response from add video');

 // message.success("Video added successfully!");
 // form.resetFields(); // Reset form
 // setFile(null); // Clear file
 // } catch (error) {
 // message.error(error.data?.message || "Failed to add video.");
 // }
 };

 const handleBackButtonClick = () => {
 navigate(-1); // This takes the user back to the previous page
 };

 const videoUploadProps = {
 name: 'video',
 // action: 'https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload',
 // headers: {
 // authorization: 'authorization-text',
 // },
 // beforeUpload: (file) => {
 // const isVideo = file.type.startsWith('video/');
 // if (!isVideo) {
 // message.error('You can only upload video files!');
 // }
 // return isVideo;
 // },
 // onChange(info) {
 // if (info.file.status === 'done') {
 // message.success(`${info.file.name} video uploaded successfully`);
 // } else if (info.file.status === 'error') {
 // message.error(`${info.file.name} video upload failed.`);
 // }
 // },
 beforeUpload: (file) => {
 const isVideo = file.type.startsWith('video/');
 if (!isVideo) {
 message.error('You can only upload video files!');
 return Upload.LIST_IGNORE; // Prevents the file from being added to the list
 }
 videoFileRef.current = file; // Store file in ref
 // setVideoFile(file); // Store the file in state instead of uploading it automatically
 return false; // Prevent auto-upload
 },
 };

 const imageUploadProps = {
 name: 'image',
 action: 'https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload',
 headers: {
 authorization: 'authorization-text',
 },
 beforeUpload: (file) => {
 const isImage = file.type.startsWith('image/');
 if (!isImage) {
 message.error('You can only upload image files!');
 }
 return isImage;
 },
 onChange(info) {
 if (info.file.status === 'done') {
 message.success(`${info.file.name} image uploaded successfully`);
 } else if (info.file.status === 'error') {
 message.error(`${info.file.name} image upload failed.`);
 }
 },
 };
 return (
 <>
 <div classname="flex items-center gap-2 text-xl cursor-pointer">
 <faangleleft></faangleleft>
 <h1 classname="font-semibold">Add Video</h1>
 </div>
 <div classname="rounded-lg py-4 border-[#79CDFF] border-2 shadow-lg mt-8 bg-white">
 <div classname="space-y-[24px] min-h-[83vh] bg-light-gray rounded-2xl">
 <h3 classname="text-2xl text-[#174C6B] mb-4 border-b border-[#79CDFF]/50 pb-3 pl-16 font-semibold">
 Adding Video
 </h3>
 <div classname="w-full px-16">
 / style={{ maxWidth: 600, margin: '0 auto' }}
 >
 {/* Section 1 */}
 {/* <space direction="vertical" style="{{"> */}
 {/* <space size="large" direction="horizontal" classname="responsive-space"> */}
 <div classname="grid grid-cols-2 gap-8 mt-8">
 <div>
 <space size="large" direction="horizontal" classname="responsive-space-section-2">

 {/* Video */}
 Upload Video}
 name="media"
 className="responsive-form-item"
 // rules={[{ required: true, message: 'Please enter the package amount!' }]}
 >
 <upload maxcount="{1}">
 <button style="{{" solid="solid">
 <span style="{{" 600="600">Select a video</span>
 <iovideocamoutline size="{20}" color="#174C6B"></iovideocamoutline>
 </button>
 </upload>
 

 {/* Thumbnail */}
 Upload Image}
 name="image"
 className="responsive-form-item"
 // rules={[{ required: true, message: 'Please enter the package amount!' }]}
 >
 <upload maxcount="{1}">
 <button style="{{" solid="solid">
 <span style="{{" 600="600">Select an image</span>
 <cicamera size="{25}" color="#174C6B"></cicamera>
 </button>
 </upload>
 

 {/* Title */}
 Video Title}
 name="name"
 className="responsive-form-item-section-2"
 >
 <input type="text" placeholder="Enter video title" style="{{&#xA;" solid="solid" />
 
 </space>
 </div>
 </div>

 {/* </space> */}
 {/* </space> */}


 {/* Submit Button */}
 
 <div classname="p-4 mt-10 text-center mx-auto flex items-center justify-center">
 
 <span classname="text-white font-semibold">{isLoading ? 'Uploading...' : 'Upload'}</span>
 
 </div>
 
 
 </div>
 </div>
 </div>
 >
 )
}

export default AddWorkoutVideo







Would appreciate any insights or suggestions. Thanks !


-