Newest 'ffmpeg' Questions - Stack Overflow
Les articles publiés sur le site
-
cv2/ffmpeg "grabFrame packet read max attempts exceeded" error after exactly reading certain number of frames
26 juin, par banjaxingI am using OpenCV to extract frames from videos, run a segmentation AI model, and save the frames and masks to a folder. When I run my code to extract the frame from I encounter the error "grabFrame packet read max attempts exceeded" after processing a certain number of frames. This issue occurs consistently for the same videos across multiple environments.
Error message:
[ WARN:0@379.898] global cap_ffmpeg_impl.hpp:1541 grabFrame packet read max attempts exceeded, if your video have multiple streams (video, audio) try to increase attempt limit by setting environment variable OPENCV_FFMPEG_READ_ATTEMPTS (current value is 10000)
Minimum Reproducible Example
import os import cv2 videofilename = "test.mp4" capture = cv2.VideoCapture(videofilename) frameNum = 0 createfolder = os.getcwd() + '/' + videofilename.split(".")[0] + '/' if not os.path.exists(createfolder): os.makedirs(createfolder) os.makedirs(createfolder + "/frames/") while True: success, frame = capture.read() if success is False: break frameNum += 1 framedownloadname = videofilename.split(".")[0] + '-fr' + str(frameNum) + '.jpg' framedownloadloc = createfolder + '/frames/' + framedownloadname print(framedownloadloc) cv2.imwrite(framedownloadloc, frame) img = cv2.imread(framedownloadloc) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) capture.release()
As suggested in error, I increased the OPENCV_FFMPEG_READ_ATTEMPTS env variable up to 10000. However, this seems to have little to no effect on the number of frames before the error appears.
-
PHP convert any video to MP4 using ffmpeg
26 juin, par DilakI have a website in which I allow users to upload videos. But with the HTML5 tag video, only MP4 videos are allowed
So, I want to convert any type of videos that the users upload to MP4 and then add the path in my database.
I tried something, changing the file extension to MP4 but it didn't work. I've read something about ffmepg but I can't figure out how to use it.
Here is my PHP script where I change the file extension and then add the path in my data base, please how can I convert the video correctly, what should I add/change?
<?php if(file_exists($_FILES['media-vid']['tmp_name']) && is_uploaded_file($_FILES['media-vid']['tmp_name'])) { $targetvid = md5(time()); $target_dirvid = "videos/"; $target_filevid = $targetvid.basename($_FILES["media-vid"]["name"]); $uploadOk = 0; $videotype = pathinfo($target_filevid,PATHINFO_EXTENSION); $video_formats = array( "mpeg", "mp4", "mov", "wav", "avi", "dat", "flv", "3gp" ); foreach ($video_formats as $valid_video_format) { if (preg_match("/$videotype/i", $valid_video_format)) { $target_filevid = $targetvid . basename($_FILES["media-vid"] . ".mp4"); $uploadOk = 1; break; } else { //if it is an image or another file format it is not accepted $format_error = "Invalid Video Format!"; } } if ($_FILES["media-vid"]["size"] > 5000000000000) { $uploadOk = 0; echo "Sorry, your file is too large."; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0 && isset($format_error)) { echo "Sorry, your video was not uploaded."; // if everything is ok, try to upload file } else if ($uploadOk == 0) { echo "Sorry, your video was not uploaded."; } else { $target_filevid = strtr($target_filevid, 'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ', 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy'); $target_filevid = preg_replace('/([^.a-z0-9]+)/i', '_', $target_filevid); if (!move_uploaded_file($_FILES["media-vid"]["tmp_name"], $target_dirvid. $target_filevid)) { echo "Sorry, there was an error uploading your file. Please retry."; } else { $vid= $target_dirvid.$target_filevid; $nbvid = 1; } } } ?>
Thank you.
-
Create playable video with audio for vscode using ffmpeg [closed]
25 juin, par Camilo Martínez M.I am trying to create a function which adds an audio stream to a silent video using
ffmpeg
. According to this, in order to be able to play videos in vscode, we need to...make sure that both the video and audio track's media formats are supported. Many .mp4 files for example use H.264 for video and AAC audio. VS Code will be able to play the video part of the mp4, but since AAC audio is not supported there won't be any sound. Instead you need to use mp3 for the audio track.
The following function already produces a playable video in vscode, but the audio is not played, even though I am using the
libmp3lame
encoder, which is the MP3 encoder (according to this).def add_audio_to_video( silent_video_path: Path, audio_source_path: Path, output_path: Path, audio_codec: Literal["libmp3lame", "aac"] = "libmp3lame", fps: int | None = None, ) -> None: """Combine a video file with an audio stream from another file using ffmpeg. Args: silent_video_path (Path): Path to the video file without audio. audio_source_path (Path): Path to the file containing the audio stream. output_path (Path): Path for the final video file with audio. audio_codec (Literal["libmp3lame", "aac"]): Codec to use for the audio stream. Defaults to "libmp3lame" (MP3). Use "aac" for AAC codec. **Note**: MP3 is compatible with vscode's video preview. fps (int): Frames per second for the output video. Defaults to 30. Todo: * [ ] TODO: Not working to be able to play audio in vscode """ # TODO: Not working to be able to play audio in vscode if not check_ffmpeg_installed(): raise RuntimeError("ffmpeg is required to add audio to the video.") # If fps is not provided, try to get it from the silent video if not fps: video_info = get_video_info(silent_video_path) if video_info and video_info.fps: fps = int(video_info.fps) else: logger.warning( "fps not provided and could not be determined from the video. Using default 30.", ) fps = 30 logger.info(f"Adding audio from '{audio_source_path}' to '{silent_video_path}'...") cmd = [ "ffmpeg", "-y", # Overwrite output file if it exists "-i", str(silent_video_path), # Input 0: Silent video "-i", str(audio_source_path), # Input 1: Audio source "-c:v", "libx264", "-profile:v", "baseline", "-level", "3.0", "-pix_fmt", "yuv420p", "-r", str(fps), "-c:a", audio_codec, "-b:a", "192k", # Set a reasonable audio bitrate for quality "-map", "0:v:0", # Map video stream from input 0 "-map", "1:a:0?", # Map audio stream from input 1 (optional) "-shortest", # Finish encoding when the shortest input stream ends str(output_path), ] try: subprocess.run(cmd, check=True, capture_output=True, text=True) # noqa: S603 logger.success(f"Final video with audio saved to {output_path}") except subprocess.CalledProcessError as e: logger.error("ffmpeg command failed to add audio.") logger.error(f"ffmpeg stderr:\n{e.stderr}") raise
Has anyone faced something similar before?
-
ffmpeg `-start_at_zero` with `-ss` does not seem to work as advertized in document [closed]
24 juin, par WangThe command make the file name start from 0, instead of 60000
ffmpeg -ss 60 -i input.ts -copyts -start_at_zero -fps_mode passthrough -enc_time_base 0.001 -frame_pts 1 -vframes:v 10 "/tmp/outframes/tms%010d.png"
but according to document the
-start_at_zero
should make the timestamp start with 60000. Is there anything I do wrong here?-copyts Do not process input timestamps, but keep their values without trying to sanitize them. In particular, do not remove the initial start time offset value. Note that, depending on the vsync option or on specific muxer processing (e.g. in case the format option avoid_negative_ts is enabled) the output timestamps may mismatch with the input timestamps even when this option is selected. -start_at_zero When used with copyts, shift input timestamps so they start at zero. This means that using e.g. -ss 50 will make output timestamps start at 50 seconds, regardless of what timestamp the input file started at.
-
exe file not executing from deployed ASP.NET MVC app in TAS (Tanzu /PCF)
24 juin, par Darshan AdakaneI am facing an issue for my ASP.NET MVC web application on .NET 4 being deployed to TAS.
I am trying to do image compression using
ffmpeg.exe
.While it is working on my local machine, I get an "500 internal server error" when deployed to TAS (tanzu application server). I am using
hwc_buildpack
and storing the file inPath.GetTemp()
folder for testing.applications: - name: MyApp-Dev memory: 1G instances: 1 stack: windows buildpacks: - hwc_buildpack path: \MyAppnew\obj\Release\Package\PackageTmp env: services: routes: - route: myapp-dev.apps.company.com - route: myapp-dev.company.com
I also see that the
.exe
is being published when app I deployed. I am assuming if TAS has NO permission to read exe or read exe 'not allowed' policy.This is my code:
[HttpPost] [Route("uploadimage")] public async Task
UploadImage() { try { if (!Request.Content.IsMimeMultipartContent()) return BadRequest("Unsupported media type."); Console.WriteLine("UploadImage method started."); var provider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(provider); Console.WriteLine($"Total Files available: {provider.Contents.Count}, {provider.Contents}"); foreach (var file in provider.Contents) { try { var imageFile = await file.ReadAsByteArrayAsync(); Console.WriteLine($"imageFile, { imageFile.Length }"); var rawFileName = file.Headers.ContentDisposition.FileName.Trim('"'); Console.WriteLine($"rawFileName, {rawFileName}"); var fileName = Path.GetFileName(rawFileName); // Sanitize filename Console.WriteLine($"fileName, {fileName}"); // Check file size limit (300MB) if (imageFile.Length > 300 * 1024 * 1024) // 300MB limit { Console.WriteLine("File size exceeds 300MB limit."); return BadRequest("File size exceeds 300MB limit."); } var inputFilePath = Path.Combine(_uploadFolder, fileName); Console.WriteLine($"inputFilePath, {inputFilePath}"); var outputFilePath = Path.Combine(_uploadFolder, "compressed_" + fileName); Console.WriteLine($"outputFilePath, {outputFilePath}"); // Save uploaded file to disk File.WriteAllBytes(inputFilePath, imageFile); // Check if the input file exists if (!File.Exists(inputFilePath)) { Console.WriteLine($"Input file does not exist: {inputFilePath}"); return InternalServerError(new Exception($"❌ Input file does not exist: {inputFilePath}")); } //Console.WriteLine($"✅ FFmpeg found at path: {ffmpegFullPath}"); await FFMpegArguments .FromFileInput(inputFilePath) .OutputToFile(outputFilePath, overwrite: true, options => options .WithCustomArgument("-vf scale=800:-1") .WithCustomArgument("-q:v 10") ) .ProcessAsynchronously(); Console.WriteLine($"outputFilePath, {outputFilePath}"); // Check if the output file was created if (File.Exists(outputFilePath)) { var fileInfo = new FileInfo(outputFilePath); // Get file info Console.WriteLine($"outputFileInfoPropsFullName, {fileInfo.FullName}"); Console.WriteLine($"outputFileInfoPropsLength, {fileInfo.Length}"); var compressedFileBytes = File.ReadAllBytes(outputFilePath); var compressedFileBase64 = Convert.ToBase64String(compressedFileBytes); return Ok(new { Message = "Image uploaded and compressed successfully.", CompressedImagePath = outputFilePath, CompressedFileSize = fileInfo.Length, // Size in bytes CompressedFileBase64 = compressedFileBase64 }); } else { Console.WriteLine("OutputFilePath File not exists."); return InternalServerError(new Exception($"❌ Failed to create compressed file: {outputFilePath}")); }); } catch (Exception ex) { Console.WriteLine($"File TRYCATCH:{ex}"); return InternalServerError(new Exception("Image compression failed: " + ex.Message)); } } } catch (Exception ex) { Console.WriteLine($"Method TRYCATCH:{ex}"); throw; } return BadRequest("No image file uploaded."); } I'm getting this error in my tanzu environment logs from the code when I execute:
await FFMpegArguments
This is the exception log:
FFMpegCore.Exceptions.FFMpegException: ffmpeg was not found on your system
I also see that the
.exe
files do exist in TAS in these logs:2025-06-13T16:07:55.878+05:30 [APP/PROC/WEB/0] [OUT] PATH of FFmpeg Executable: C:\Users\vcap\app\ffmpeg-bin\ffmpeg.exe 2025-06-13T16:07:55.878+05:30 [APP/PROC/WEB/0] [OUT] PATH of ffmpegPath: C:\Users\vcap\app\ffmpeg-bin 2025-06-13T16:07:55.878+05:30 [APP/PROC/WEB/0] [OUT] PATH of BaseDirectory: C:\Users\vcap\app\ 2025-06-13T16:07:55.881+05:30 [APP/PROC/WEB/0] [OUT] TempPath: C:\Users\vcap\AppData\Local\Temp\ 2025-06-24T18:39:50.684+05:30 [APP/PROC/WEB/0] [OUT] at MCANew.Controllers.Api.MessagesController.
d__6.MoveNext() in I:\Agents\Agent-Win-B\_work\3033\s\MCANew\Controllers\Api\MessagesController.cs:line 133 2025-06-24T18:39:50.684+05:30 [APP/PROC/WEB/0] [OUT] at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 2025-06-24T18:39:50.684+05:30 [APP/PROC/WEB/0] [OUT] --- End of stack trace from previous location where exception was thrown --- 2025-06-24T18:39:50.684+05:30 [APP/PROC/WEB/0] [OUT] at FFMpegCore.FFMpegArgumentProcessor. d__24.MoveNext() 2025-06-24T18:39:50.684+05:30 [APP/PROC/WEB/0] [OUT] at FFMpegCore.FFMpegArgumentProcessor.PrepareProcessArguments(FFOptions ffOptions, CancellationTokenSource& cancellationTokenSource) 2025-06-24T18:39:50.684+05:30 [APP/PROC/WEB/0] [OUT] at FFMpegCore.Helpers.FFMpegHelper.VerifyFFMpegExists(FFOptions ffMpegOptions) 2025-06-24T18:39:50.684+05:30 [APP/PROC/WEB/0] [OUT] File TRYCATCH:FFMpegCore.Exceptions.FFMpegException: ffmpeg was not found on your system My objective is to run successfully exe on TAS and image compression to happen.