How to detect with ffmpeg if the stream has video or audio or both

Abstract: Detect if a media file contains video, audio, or both using ffprobe JSON output for automated pipeline validation.

Created: 2026-09-08 by
Use ffprobe to inspect the stream metadata and identify the presence of video or audio tracks by parsing the JSON output for codec types. This tool provides a reliable, non-invasive method to determine media composition without decoding the entire file, making it ideal for scripting and automated pipeline validation in Linux environments.

Understanding ffprobe Basics

ffprobe is part of the FFmpeg suite designed specifically for probing media files and streams. Unlike ffmpeg, which is used for conversion and processing, ffprobe reads headers and metadata to describe the content structure. It outputs information about containers, streams, and codecs, allowing you to verify what data exists within a file before attempting to process it. The most effective way to use this tool programmatically is by requesting the output in JSON format. This structured data is easy to parse using command-line tools like jq or within scripts written in Python, Bash, or other languages. By focusing on the streams array in the JSON response, you can iterate through each track and check its codec_type.

Identifying Stream Types

To detect if a stream contains video, audio, or both, you need to examine the codec_type field for each stream entry. The possible values are typically video, audio, subtitle, data, or attachment. A standard multimedia file will usually have at least one video stream and one audio stream, but edge cases such as silent videos or audio-only recordings require explicit checking. You can run a basic probe command to see all available streams:
ffprobe -v quiet -print_format json -show_streams input.mp4
This command suppresses verbose logging (-v quiet) and outputs only the stream details in JSON. Look for objects within the streams array that contain "codec_type": "video" or "codec_type": "audio". If neither exists, the file may be corrupted or contain only data streams. For automation, you can filter the output directly in the shell. To count the number of video streams, use:
ffprobe -v quiet -print_format json -show_streams input.mp4 | jq '.streams[] | select(.codec_type == "video")' | wc -l
Similarly, replace "video" with "audio" to count audio tracks. A result greater than zero indicates the presence of that media type. This approach allows you to build conditional logic in scripts, such as skipping files that lack an audio track when encoding for a platform that requires it.

Advanced Detection with Format Info

Sometimes, the container format itself provides hints, though stream-level inspection is more accurate. You can also retrieve general format information using -show_format. However, relying solely on the container does not guarantee the presence of specific codecs inside, especially in hybrid or modified files. Combining -show_streams with -show_format gives a complete picture:
ffprobe -v quiet -print_format json -show_streams -show_format input.mp4
This output includes duration, bitrate, and codec names alongside the stream types. For robust detection, always prioritize the codec_type from the streams list. If you are dealing with live streams rather than static files, ensure the input URL supports seeking or buffering, as ffprobe may timeout if it cannot read enough packets to determine the stream types. In scenarios where you are combining media, such as adding audio to a silent video, understanding the current state is crucial. You might refer to guides on Combining Video and Audio with FFmpeg to understand how these streams interact during muxing. Detecting the source streams first ensures you do not accidentally overwrite existing tracks or create duplicate audio channels.

Handling Edge Cases and Errors

Not all streams behave predictably. Some files may have multiple audio tracks (e.g., dual language) or hidden subtitle streams. When writing detection scripts, account for multiple instances of the same codec_type. Instead of just checking for existence, consider counting them to decide which track to process. If ffprobe returns an empty streams array or fails to connect, the file might be inaccessible or in an unsupported format. Always check the exit code of the ffprobe command. A non-zero exit code indicates an error, such as a missing file or invalid path. In network streaming contexts, ensure your network configuration allows sufficient bandwidth for the probe packet read, as low-bandwidth connections might cause timeouts. Additionally, some proprietary formats or encrypted streams may hide codec information until decrypted. In such cases, standard ffprobe inspection might fail or return incomplete data. You may need to provide decryption keys or use specific flags depending on the DRM system involved. For common open formats like MP4, MKV, and WebM, the standard JSON output is fully reliable.

Frequently Asked Questions

What if ffprobe reports no streams?

This usually means the file is corrupted, empty, or uses a highly unusual container format that ffprobe cannot recognize. Verify the file path and ensure the file is not zero bytes in size. Try opening the file in a media player to confirm it is valid.

Can I detect subtitles using this method?

Yes, simply change the select condition in your query to codec_type == "subtitle". Subtitle streams are often overlooked but are critical for accessibility compliance in many distribution platforms.

Does this work for live RTMP or HLS streams?

It works for live streams if the protocol allows reading enough initial packets to identify codecs. However, some live streams may require specific buffering options or may time out if the server does not send keyframes quickly enough. Test with a short duration limit first.

How do I handle files with multiple audio tracks?

Count the occurrences of codec_type == "audio" instead of just checking for existence. You can then inspect the index or tags field within each stream object to identify which track corresponds to which language or channel layout.

Is there a faster way than parsing JSON?

Using -v error and grepping for "Stream" lines is faster for simple shell checks, but JSON parsing is more robust for complex logic. For high-volume batch processing, consider using a dedicated library like PyAV in Python, which offers programmatic access to stream metadata without spawning subprocesses.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More