
Recherche avancée
Médias (3)
-
The Slip - Artworks
26 septembre 2011, par
Mis à jour : Septembre 2011
Langue : English
Type : Texte
-
Podcasting Legal guide
16 mai 2011, par
Mis à jour : Mai 2011
Langue : English
Type : Texte
-
Creativecommons informational flyer
16 mai 2011, par
Mis à jour : Juillet 2013
Langue : English
Type : Texte
Autres articles (47)
-
HTML5 audio and video support
13 avril 2011, parMediaSPIP uses HTML5 video and audio tags to play multimedia files, taking advantage of the latest W3C innovations supported by modern browsers.
The MediaSPIP player used has been created specifically for MediaSPIP and can be easily adapted to fit in with a specific theme.
For older browsers the Flowplayer flash fallback is used.
MediaSPIP allows for media playback on major mobile platforms with the above (...) -
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 (...) -
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 (...)
Sur d’autres sites (7445)
-
Segmentation fault with avcodec_encode_video2() while encoding H.264
16 juillet 2015, par Baris DemirayI’m trying to convert a
cv::Mat
to anAVFrame
to encode it then in H.264 and wanted to start from a simple example, as I’m a newbie in both. So I first read in a JPEG file, and then do the pixel format conversion withsws_scale()
fromAV_PIX_FMT_BGR24
toAV_PIX_FMT_YUV420P
keeping the dimensions the same, and it all goes fine until I callavcodec_encode_video2()
.I read quite a few discussions regarding an
AVFrame
allocation and the question segmetation fault while avcodec_encode_video2 seemed like a match but I just can’t see what I’m missing or getting wrong.Here is the minimal code that you can reproduce the crash, it should be compiled with,
g++ -o OpenCV2FFmpeg OpenCV2FFmpeg.cpp -lopencv_imgproc -lopencv_highgui -lopencv_core -lswscale -lavutil -lavcodec -lavformat
It’s output on my system,
cv::Mat [width=420, height=315, depth=0, channels=3, step=1260]
I'll soon crash..
Segmentation faultAnd that
sample.jpg
file’s details byidentify
tool,~temporary/sample.jpg JPEG 420x315 420x315+0+0 8-bit sRGB 38.3KB 0.000u 0:00.000
Please note that I’m trying to create a video out of a single image, just to keep things simple.
#include <iostream>
#include <cassert>
using namespace std;
extern "C" {
#include <libavcodec></libavcodec>avcodec.h>
#include <libswscale></libswscale>swscale.h>
#include <libavformat></libavformat>avformat.h>
}
#include <opencv2></opencv2>core/core.hpp>
#include <opencv2></opencv2>highgui/highgui.hpp>
const string TEST_IMAGE = "/home/baris/temporary/sample.jpg";
int main(int /*argc*/, char** argv)
{
av_register_all();
avcodec_register_all();
/**
* Initialise the encoder
*/
AVCodec *h264encoder = avcodec_find_encoder(AV_CODEC_ID_H264);
AVFormatContext *cv2avFormatContext = avformat_alloc_context();
/**
* Create a stream and allocate frames
*/
AVStream *h264outputstream = avformat_new_stream(cv2avFormatContext, h264encoder);
avcodec_get_context_defaults3(h264outputstream->codec, h264encoder);
AVFrame *sourceAvFrame = av_frame_alloc(), *destAvFrame = av_frame_alloc();
int got_frame;
/**
* Pixel formats for the input and the output
*/
AVPixelFormat sourcePixelFormat = AV_PIX_FMT_BGR24;
AVPixelFormat destPixelFormat = AV_PIX_FMT_YUV420P;
/**
* Create cv::Mat
*/
cv::Mat cvFrame = cv::imread(TEST_IMAGE, CV_LOAD_IMAGE_COLOR);
int width = cvFrame.size().width, height = cvFrame.size().height;
cerr << "cv::Mat [width=" << width << ", height=" << height << ", depth=" << cvFrame.depth() << ", channels=" << cvFrame.channels() << ", step=" << cvFrame.step << "]" << endl;
h264outputstream->codec->pix_fmt = destPixelFormat;
h264outputstream->codec->width = cvFrame.cols;
h264outputstream->codec->height = cvFrame.rows;
/**
* Prepare the conversion context
*/
SwsContext *bgr2yuvcontext = sws_getContext(width, height,
sourcePixelFormat,
h264outputstream->codec->width, h264outputstream->codec->height,
h264outputstream->codec->pix_fmt,
SWS_BICUBIC, NULL, NULL, NULL);
/**
* Convert and encode frames
*/
for (uint i=0; i < 250; i++)
{
/**
* Allocate source frame, i.e. input to sws_scale()
*/
avpicture_alloc((AVPicture*)sourceAvFrame, sourcePixelFormat, width, height);
for (int h = 0; h < height; h++)
memcpy(&(sourceAvFrame->data[0][h*sourceAvFrame->linesize[0]]), &(cvFrame.data[h*cvFrame.step]), width*3);
/**
* Allocate destination frame, i.e. output from sws_scale()
*/
avpicture_alloc((AVPicture *)destAvFrame, destPixelFormat, width, height);
sws_scale(bgr2yuvcontext, sourceAvFrame->data, sourceAvFrame->linesize,
0, height, destAvFrame->data, destAvFrame->linesize);
/**
* Prepare an AVPacket for encoded output
*/
AVPacket avEncodedPacket;
av_init_packet(&avEncodedPacket);
avEncodedPacket.data = NULL;
avEncodedPacket.size = 0;
// av_free_packet(&avEncodedPacket); w/ or w/o result doesn't change
cerr << "I'll soon crash.." << endl;
if (avcodec_encode_video2(h264outputstream->codec, &avEncodedPacket, destAvFrame, &got_frame) < 0)
exit(1);
cerr << "Checking if we have a frame" << endl;
if (got_frame)
av_write_frame(cv2avFormatContext, &avEncodedPacket);
av_free_packet(&avEncodedPacket);
av_frame_free(&sourceAvFrame);
av_frame_free(&destAvFrame);
}
}
</cassert></iostream>Thanks in advance !
EDIT : And the stack trace after the crash,
Thread 2 (Thread 0x7fffe5506700 (LWP 10005)):
#0 0x00007ffff4bf6c5d in poll () at /lib64/libc.so.6
#1 0x00007fffe9073268 in () at /usr/lib64/libusb-1.0.so.0
#2 0x00007ffff47010a4 in start_thread () at /lib64/libpthread.so.0
#3 0x00007ffff4bff08d in clone () at /lib64/libc.so.6
Thread 1 (Thread 0x7ffff7f869c0 (LWP 10001)):
#0 0x00007ffff5ecc7dc in avcodec_encode_video2 () at /usr/lib64/libavcodec.so.56
#1 0x00000000004019b6 in main(int, char**) (argv=0x7fffffffd3d8) at ../src/OpenCV2FFmpeg.cpp:99EDIT2 : Problem was that I hadn’t
avcodec_open2()
the codec as spotted by Ronald. Final version of the code is at https://github.com/barisdemiray/opencv2ffmpeg/, with leaks and probably other problems hoping that I’ll improve it while learning both libraries. -
How to restream IPTV playlist with Nginx RTMP, FFmpeg, and Python without recording, but getting HTTP 403 error ? [closed]
1er avril, par boyuna1720I have an IPTV playlist from a provider that allows only one user to connect and watch. I want to restream this playlist through my own server without recording it and in a lightweight manner. I’m using Nginx RTMP, FFmpeg, and Python TCP for the setup, but I keep getting an HTTP 403 error when trying to access the stream.


Here’s a summary of my setup :


Nginx RTMP : Used for streaming.


FFmpeg : Used to handle the video stream.


Python TCP : Trying to handle the connection between my server and the IPTV source.


#!/usr/bin/env python3

import sys
import socket
import threading
import requests
import time

def accept_connections(server_socket, clients, clients_lock):
 """
 Continuously accept new client connections, perform a minimal read of the
 client's HTTP request, send back a valid HTTP/1.1 response header, and
 add the socket to the broadcast list.
 """
 while True:
 client_socket, addr = server_socket.accept()
 print(f"[+] New client connected from {addr}")
 threading.Thread(
 target=handle_client,
 args=(client_socket, addr, clients, clients_lock),
 daemon=True
 ).start()

def handle_client(client_socket, addr, clients, clients_lock):
 """
 Read the client's HTTP request minimally, send back a proper HTTP/1.1 200 OK header,
 and then add the socket to our broadcast list.
 """
 try:
 # Read until we reach the end of the request headers
 request_data = b""
 while b"\r\n\r\n" not in request_data:
 chunk = client_socket.recv(1024)
 if not chunk:
 break
 request_data += chunk

 # Send a proper HTTP response header to satisfy clients like curl
 response_header = (
 "HTTP/1.1 200 OK\r\n"
 "Content-Type: application/octet-stream\r\n"
 "Connection: close\r\n"
 "\r\n"
 )
 client_socket.sendall(response_header.encode("utf-8"))

 with clients_lock:
 clients.append(client_socket)
 print(f"[+] Client from {addr} is ready to receive stream.")
 except Exception as e:
 print(f"[!] Error handling client {addr}: {e}")
 client_socket.close()

def read_from_source_and_broadcast(source_url, clients, clients_lock):
 """
 Continuously connect to the source URL (following redirects) using custom headers
 so that it mimics a curl-like request. In case of connection errors (e.g. connection reset),
 wait a bit and then try again.
 
 For each successful connection, stream data in chunks and broadcast each chunk
 to all connected clients.
 """
 # Set custom headers to mimic curl
 headers = {
 "User-Agent": "curl/8.5.0",
 "Accept": "*/*"
 }

 while True:
 try:
 print(f"[+] Fetching from source URL (with redirects): {source_url}")
 with requests.get(source_url, stream=True, allow_redirects=True, headers=headers) as resp:
 if resp.status_code >= 400:
 print(f"[!] Got HTTP {resp.status_code} from the source. Retrying in 5 seconds.")
 time.sleep(5)
 continue

 # Stream data and broadcast each chunk
 for chunk in resp.iter_content(chunk_size=4096):
 if not chunk:
 continue
 with clients_lock:
 for c in clients[:]:
 try:
 c.sendall(chunk)
 except Exception as e:
 print(f"[!] A client disconnected or send failed: {e}")
 c.close()
 clients.remove(c)
 except requests.exceptions.RequestException as e:
 print(f"[!] Source connection error, retrying in 5 seconds: {e}")
 time.sleep(5)

def main():
 if len(sys.argv) != 3:
 print(f"Usage: {sys.argv[0]} <port>")
 sys.exit(1)

 source_url = sys.argv[1]
 port = int(sys.argv[2])

 # Create a TCP socket to listen for incoming connections
 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 server_socket.bind(("0.0.0.0", port))
 server_socket.listen(5)
 print(f"[+] Listening on port {port}...")

 # List of currently connected client sockets
 clients = []
 clients_lock = threading.Lock()

 # Start a thread to accept incoming client connections
 t_accept = threading.Thread(
 target=accept_connections,
 args=(server_socket, clients, clients_lock),
 daemon=True
 )
 t_accept.start()

 # Continuously read from the source URL and broadcast to connected clients
 read_from_source_and_broadcast(source_url, clients, clients_lock)

if __name__ == "__main__":
 main()
</port>


When i write command
python3 proxy_server.py 'http://channelurl' 9999

I getting error.

[+] Listening on port 9999...
[+] Fetching from source URL (with redirects): http://ate91060.cdn-akm.me:80/dc31a19e5a6a/fc5e38e28e/325973
[!] Got HTTP 403 from the source. Retrying in 5 seconds.
^CTraceback (most recent call last):
 File "/home/namepirate58/nginx-1.23.1/proxy_server.py", line 127, in <module>
 main()
 File "/home/namepirate58/nginx-1.23.1/proxy_server.py", line 124, in main
 read_from_source_and_broadcast(source_url, clients, clients_lock)
 File "/home/namepirate58/nginx-1.23.1/proxy_server.py", line 77, in read_from_source_and_broadcast
 time.sleep(5)
KeyboardInterrupt
</module>


-
While using skvideo.io.FFmpegReader and skvideo.io.FFmpegWriter for video throughput the input video and output video length differ
28 juin 2024, par Kaesebrotus AnonymousI have an h264 encoded mp4 video of about 27.5 minutes length and I am trying to create a copy of the video which excludes the first 5 frames. I am using scikit-video and ffmpeg in python for this purpose. I do not have a GPU, so I am using libx264 codec for the output video.


It generally works and the output video excludes the first 5 frames. Somehow, the output video results in a length of about 22 minutes. When visually checking the videos, the shorter video does seem slightly faster and I can identify the same frames at different timestamps. In windows explorer, when clicking properties and then details, both videos' frame rates show as 20.00 fps.


So, my goal is to have both videos of the same length, except for the loss of the first 5 frames which should result in a duration difference of 0.25 seconds, and use the same (almost same) codec and not lose quality.


Can anyone explain why this apparent loss of frames is happening ?


Thank you for your interest in helping me, please find the details below.


Here is a minimal example of what I have done.


framerate = str(20)
reader = skvideo.io.FFmpegReader(inputvideo.mp4, inputdict={'-r': framerate})
writer = skvideo.io.FFmpegWriter(outputvideo.mp4, outputdict={'-vcodec': 'libx264', '-r': framerate})

for idx,frame in enumerate(reader.nextFrame()):
 if idx < 5:
 continue
 writer.writeFrame(frame)

reader.close()
writer.close()



When I read the output video again using FFmpegReader and check the .probeInfo, I can see that the output video has less frames in total. I have also managed to replicate the same problem for shorter videos (now not excluding the first 5 frames, but only throughputting a video), e.g. 10 seconds input turns to 8 seconds output with less frames. I have also tried playing around with further parameters of the outputdict, e.g. -pix_fmt, -b. I have tried to set -time_base in the output dict to the same value as in the inputdict, but that did not seem to have the desired effect. I am not sure if the name of the parameter is right.


For additional info, I am providing the .probeInfo of the input video, of which I used 10 seconds, and the .probeInfo of the 8 second output video it produced.


**input video** .probeInfo:
input dict

{'video': OrderedDict([('@index', '0'),
 ('@codec_name', 'h264'),
 ('@codec_long_name',
 'H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10'),
 ('@profile', 'High 4:4:4 Predictive'),
 ('@codec_type', 'video'),
 ('@codec_tag_string', 'avc1'),
 ('@codec_tag', '0x31637661'),
 ('@width', '4096'),
 ('@height', '3000'),
 ('@coded_width', '4096'),
 ('@coded_height', '3000'),
 ('@closed_captions', '0'),
 ('@film_grain', '0'),
 ('@has_b_frames', '0'),
 ('@sample_aspect_ratio', '1:1'),
 ('@display_aspect_ratio', '512:375'),
 ('@pix_fmt', 'yuv420p'),
 ('@level', '60'),
 ('@chroma_location', 'left'),
 ('@field_order', 'progressive'),
 ('@refs', '1'),
 ('@is_avc', 'true'),
 ('@nal_length_size', '4'),
 ('@id', '0x1'),
 ('@r_frame_rate', '20/1'),
 ('@avg_frame_rate', '20/1'),
 ('@time_base', '1/1200000'),
 ('@start_pts', '0'),
 ('@start_time', '0.000000'),
 ('@duration_ts', '1984740000'),
 ('@duration', '1653.950000'),
 ('@bit_rate', '3788971'),
 ('@bits_per_raw_sample', '8'),
 ('@nb_frames', '33079'),
 ('@extradata_size', '43'),
 ('disposition',
 OrderedDict([('@default', '1'),
 ('@dub', '0'),
 ('@original', '0'),
 ('@comment', '0'),
 ('@lyrics', '0'),
 ('@karaoke', '0'),
 ('@forced', '0'),
 ('@hearing_impaired', '0'),
 ('@visual_impaired', '0'),
 ('@clean_effects', '0'),
 ('@attached_pic', '0'),
 ('@timed_thumbnails', '0'),
 ('@non_diegetic', '0'),
 ('@captions', '0'),
 ('@descriptions', '0'),
 ('@metadata', '0'),
 ('@dependent', '0'),
 ('@still_image', '0')])),
 ('tags',
 OrderedDict([('tag',
 [OrderedDict([('@key', 'language'),
 ('@value', 'und')]),
 OrderedDict([('@key', 'handler_name'),
 ('@value', 'VideoHandler')]),
 OrderedDict([('@key', 'vendor_id'),
 ('@value', '[0][0][0][0]')])])]))])}

**output video** .probeInfo:
{'video': OrderedDict([('@index', '0'),
 ('@codec_name', 'h264'),
 ('@codec_long_name',
 'H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10'),
 ('@profile', 'High'),
 ('@codec_type', 'video'),
 ('@codec_tag_string', 'avc1'),
 ('@codec_tag', '0x31637661'),
 ('@width', '4096'),
 ('@height', '3000'),
 ('@coded_width', '4096'),
 ('@coded_height', '3000'),
 ('@closed_captions', '0'),
 ('@film_grain', '0'),
 ('@has_b_frames', '2'),
 ('@pix_fmt', 'yuv420p'),
 ('@level', '60'),
 ('@chroma_location', 'left'),
 ('@field_order', 'progressive'),
 ('@refs', '1'),
 ('@is_avc', 'true'),
 ('@nal_length_size', '4'),
 ('@id', '0x1'),
 ('@r_frame_rate', '20/1'),
 ('@avg_frame_rate', '20/1'),
 ('@time_base', '1/10240'),
 ('@start_pts', '0'),
 ('@start_time', '0.000000'),
 ('@duration_ts', '82944'),
 ('@duration', '8.100000'),
 ('@bit_rate', '3444755'),
 ('@bits_per_raw_sample', '8'),
 ('@nb_frames', '162'),
 ('@extradata_size', '47'),
 ('disposition',
 OrderedDict([('@default', '1'),
 ('@dub', '0'),
 ('@original', '0'),
 ('@comment', '0'),
 ('@lyrics', '0'),
 ('@karaoke', '0'),
 ('@forced', '0'),
 ('@hearing_impaired', '0'),
 ('@visual_impaired', '0'),
 ('@clean_effects', '0'),
 ('@attached_pic', '0'),
 ('@timed_thumbnails', '0'),
 ('@non_diegetic', '0'),
 ('@captions', '0'),
 ('@descriptions', '0'),
 ('@metadata', '0'),
 ('@dependent', '0'),
 ('@still_image', '0')])),
 ('tags',
 OrderedDict([('tag',
 [OrderedDict([('@key', 'language'),
 ('@value', 'und')]),
 OrderedDict([('@key', 'handler_name'),
 ('@value', 'VideoHandler')]),
 OrderedDict([('@key', 'vendor_id'),
 ('@value', '[0][0][0][0]')]),
 OrderedDict([('@key', 'encoder'),
 ('@value',
 'Lavc61.8.100 libx264')])])]))])}



I used 10 seconds by adding this to the bottom of the loop shown above :


if idx >= 200:
 break