Recherche avancée

Médias (0)

Mot : - Tags -/signalement

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

Autres articles (73)

  • MediaSPIP v0.2

    21 juin 2013, par

    MediaSPIP 0.2 est la première version de MediaSPIP stable.
    Sa date de sortie officielle est le 21 juin 2013 et est annoncée ici.
    Le fichier zip ici présent contient uniquement les sources de MediaSPIP en version standalone.
    Comme pour la version précédente, il est nécessaire d’installer manuellement l’ensemble des dépendances logicielles sur le serveur.
    Si vous souhaitez utiliser cette archive pour une installation en mode ferme, il vous faudra également procéder à d’autres modifications (...)

  • Mise à disposition des fichiers

    14 avril 2011, par

    Par défaut, lors de son initialisation, MediaSPIP ne permet pas aux visiteurs de télécharger les fichiers qu’ils soient originaux ou le résultat de leur transformation ou encodage. Il permet uniquement de les visualiser.
    Cependant, il est possible et facile d’autoriser les visiteurs à avoir accès à ces documents et ce sous différentes formes.
    Tout cela se passe dans la page de configuration du squelette. Il vous faut aller dans l’espace d’administration du canal, et choisir dans la navigation (...)

  • MediaSPIP version 0.1 Beta

    16 avril 2011, par

    MediaSPIP 0.1 beta est la première version de MediaSPIP décrétée comme "utilisable".
    Le fichier zip ici présent contient uniquement les sources de MediaSPIP en version standalone.
    Pour avoir une installation fonctionnelle, il est nécessaire d’installer manuellement l’ensemble des dépendances logicielles sur le serveur.
    Si vous souhaitez utiliser cette archive pour une installation en mode ferme, il vous faudra également procéder à d’autres modifications (...)

Sur d’autres sites (14784)

  • MJPEG decoding is 3x slower when opening a V4L2 input device [closed]

    26 octobre 2024, par Xenonic

    I'm trying to decode a MJPEG video stream coming from a webcam, but I'm hitting some performance blockers when using FFmpeg's C API in my application. I've recreated the problem using the example video decoder, where I just simply open the V4L2 input device, read packets, and push them to the decoder. What's strange is if I try to get my input packets from the V4L2 device instead of from a file, the avcodec_send_packet call to the decoder is nearly 3x slower. After further poking around, I narrowed the issue down to whether or not I open the V4L2 device at all.

    


    Let's look at a minimal example demonstrating this behavior :

    


    extern "C"&#xA;{&#xA;#include <libavcodec></libavcodec>avcodec.h>&#xA;#include <libavformat></libavformat>avformat.h>&#xA;#include <libavutil></libavutil>opt.h>&#xA;#include <libavdevice></libavdevice>avdevice.h>&#xA;}&#xA;&#xA;#define INBUF_SIZE 4096&#xA;&#xA;static void decode(AVCodecContext *dec_ctx, AVFrame *frame, AVPacket *pkt)&#xA;{&#xA;    if (avcodec_send_packet(dec_ctx, pkt) &lt; 0)&#xA;        exit(1);&#xA; &#xA;    int ret = 0;&#xA;    while (ret >= 0) {&#xA;        ret = avcodec_receive_frame(dec_ctx, frame);&#xA;        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)&#xA;            return;&#xA;        else if (ret &lt; 0)&#xA;            exit(1);&#xA;&#xA;        // Here we&#x27;d save off the decoded frame, but that&#x27;s not necessary for the example.&#xA;    }&#xA;}&#xA;&#xA;int main(int argc, char **argv)&#xA;{&#xA;    const char *filename;&#xA;    const AVCodec *codec;&#xA;    AVCodecParserContext *parser;&#xA;    AVCodecContext *c= NULL;&#xA;    FILE *f;&#xA;    AVFrame *frame;&#xA;    uint8_t inbuf[INBUF_SIZE &#x2B; AV_INPUT_BUFFER_PADDING_SIZE];&#xA;    uint8_t *data;&#xA;    size_t   data_size;&#xA;    int ret;&#xA;    int eof;&#xA;    AVPacket *pkt;&#xA;&#xA;    filename = argv[1];&#xA;&#xA;    pkt = av_packet_alloc();&#xA;    if (!pkt)&#xA;        exit(1);&#xA;&#xA;    /* set end of buffer to 0 (this ensures that no overreading happens for damaged MPEG streams) */&#xA;    memset(inbuf &#x2B; INBUF_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);&#xA;&#xA;    // Use MJPEG instead of the example&#x27;s MPEG1&#xA;    //codec = avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO);&#xA;    codec = avcodec_find_decoder(AV_CODEC_ID_MJPEG);&#xA;    if (!codec) {&#xA;        fprintf(stderr, "Codec not found\n");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    parser = av_parser_init(codec->id);&#xA;    if (!parser) {&#xA;        fprintf(stderr, "parser not found\n");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    c = avcodec_alloc_context3(codec);&#xA;    if (!c) {&#xA;        fprintf(stderr, "Could not allocate video codec context\n");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    if (avcodec_open2(c, codec, NULL) &lt; 0) {&#xA;        fprintf(stderr, "Could not open codec\n");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    c->pix_fmt = AV_PIX_FMT_YUVJ422P;&#xA;&#xA;    f = fopen(filename, "rb");&#xA;    if (!f) {&#xA;        fprintf(stderr, "Could not open %s\n", filename);&#xA;        exit(1);&#xA;    }&#xA;&#xA;    frame = av_frame_alloc();&#xA;    if (!frame) {&#xA;        fprintf(stderr, "Could not allocate video frame\n");&#xA;        exit(1);&#xA;    }&#xA;&#xA;    avdevice_register_all();&#xA;    auto* inputFormat = av_find_input_format("v4l2");&#xA;    AVDictionary* options = nullptr;&#xA;    av_dict_set(&amp;options, "input_format", "mjpeg", 0);&#xA;    av_dict_set(&amp;options, "video_size", "1920x1080", 0);&#xA;&#xA;    AVFormatContext* fmtCtx = nullptr;&#xA;&#xA;&#xA;    // Commenting this line out results in fast encoding!&#xA;    // Notice how fmtCtx is not even used anywhere, we still read packets from the file&#xA;    avformat_open_input(&amp;fmtCtx, "/dev/video0", inputFormat, &amp;options);&#xA;&#xA;&#xA;    // Just parse packets from a file and send them to the decoder.&#xA;    do {&#xA;        data_size = fread(inbuf, 1, INBUF_SIZE, f);&#xA;        if (ferror(f))&#xA;            break;&#xA;        eof = !data_size;&#xA;&#xA;        data = inbuf;&#xA;        while (data_size > 0 || eof) {&#xA;            ret = av_parser_parse2(parser, c, &amp;pkt->data, &amp;pkt->size,&#xA;                                   data, data_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);&#xA;            if (ret &lt; 0) {&#xA;                fprintf(stderr, "Error while parsing\n");&#xA;                exit(1);&#xA;            }&#xA;            data      &#x2B;= ret;&#xA;            data_size -= ret;&#xA;&#xA;            if (pkt->size)&#xA;                decode(c, frame, pkt);&#xA;            else if (eof)&#xA;                break;&#xA;        }&#xA;    } while (!eof);&#xA;&#xA;    return 0;&#xA;}&#xA;

    &#xA;

    Here's a histogram of the CPU time spent in that avcodec_send_packet function call with and without opening the device by commenting out that avformat_open_input call above.

    &#xA;

    Without opening the V4L2 device :

    &#xA;

    fread_cpu

    &#xA;

    With opening the V4L2 device :

    &#xA;

    webcam_cpu

    &#xA;

    Interestingly we can see a significant number of function calls are in that 25ms time bin ! But most of them are 78ms... why ?

    &#xA;

    So what's going on here ? Why does opening the device destroy my decode performance ?

    &#xA;

    Additionally, if I try and run a seemingly equivalent pipeline through the ffmpeg tool itself, I don't hit this problem. Running this command :

    &#xA;

    ffmpeg -f v4l2 -input_format mjpeg -video_size 1920x1080 -r 30 -c:v mjpeg -i /dev/video0 -c:v copy out.mjpeg&#xA;

    &#xA;

    Is generating an output file with a reported speed of just barely over 1.0x, aka. 30 FPS. Perfect, why doesn't the C API give me the same results ? One thing to note is I do get periodic errors from the MJPEG decoder (about every second), not sure if these are a concern or not :

    &#xA;

    [mjpeg @ 0x5590d6b7b0] Application provided invalid, non monotonically increasing dts to muxer in stream 0: 27 >= 27&#xA;[mjpeg @ 0x5590d6b7b0] Application provided invalid, non monotonically increasing dts to muxer in stream 0: 30 >= 30&#xA;...&#xA;

    &#xA;

    I'm running on a Raspberry Pi CM4 with FFmpeg 6.1.1

    &#xA;

  • Segmentation fault with avcodec_encode_video2() while encoding H.264

    16 juillet 2015, par Baris Demiray

    I’m trying to convert a cv::Mat to an AVFrame 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 with sws_scale() from AV_PIX_FMT_BGR24 to AV_PIX_FMT_YUV420P keeping the dimensions the same, and it all goes fine until I call avcodec_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 fault

    And that sample.jpg file’s details by identify 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 &lt;&lt; "cv::Mat [width=" &lt;&lt; width &lt;&lt; ", height=" &lt;&lt; height &lt;&lt; ", depth=" &lt;&lt; cvFrame.depth() &lt;&lt; ", channels=" &lt;&lt; cvFrame.channels() &lt;&lt; ", step=" &lt;&lt; cvFrame.step &lt;&lt; "]" &lt;&lt; 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 &lt; 250; i++)
       {
           /**
            * Allocate source frame, i.e. input to sws_scale()
            */
           avpicture_alloc((AVPicture*)sourceAvFrame, sourcePixelFormat, width, height);

           for (int h = 0; h &lt; height; h++)
               memcpy(&amp;(sourceAvFrame->data[0][h*sourceAvFrame->linesize[0]]), &amp;(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(&amp;avEncodedPacket);
           avEncodedPacket.data = NULL;
           avEncodedPacket.size = 0;
           // av_free_packet(&amp;avEncodedPacket); w/ or w/o result doesn't change

           cerr &lt;&lt; "I'll soon crash.." &lt;&lt; endl;
           if (avcodec_encode_video2(h264outputstream->codec, &amp;avEncodedPacket, destAvFrame, &amp;got_frame) &lt; 0)
               exit(1);

           cerr &lt;&lt; "Checking if we have a frame" &lt;&lt; endl;
           if (got_frame)
               av_write_frame(cv2avFormatContext, &amp;avEncodedPacket);

           av_free_packet(&amp;avEncodedPacket);
           av_frame_free(&amp;sourceAvFrame);
           av_frame_free(&amp;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:99

    EDIT2 : 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 boyuna1720

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

    &#xA;

    Here’s a summary of my setup :

    &#xA;

    Nginx RTMP : Used for streaming.

    &#xA;

    FFmpeg : Used to handle the video stream.

    &#xA;

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

    &#xA;

    #!/usr/bin/env python3&#xA;&#xA;import sys&#xA;import socket&#xA;import threading&#xA;import requests&#xA;import time&#xA;&#xA;def accept_connections(server_socket, clients, clients_lock):&#xA;    """&#xA;    Continuously accept new client connections, perform a minimal read of the&#xA;    client&#x27;s HTTP request, send back a valid HTTP/1.1 response header, and&#xA;    add the socket to the broadcast list.&#xA;    """&#xA;    while True:&#xA;        client_socket, addr = server_socket.accept()&#xA;        print(f"[&#x2B;] New client connected from {addr}")&#xA;        threading.Thread(&#xA;            target=handle_client,&#xA;            args=(client_socket, addr, clients, clients_lock),&#xA;            daemon=True&#xA;        ).start()&#xA;&#xA;def handle_client(client_socket, addr, clients, clients_lock):&#xA;    """&#xA;    Read the client&#x27;s HTTP request minimally, send back a proper HTTP/1.1 200 OK header,&#xA;    and then add the socket to our broadcast list.&#xA;    """&#xA;    try:&#xA;        # Read until we reach the end of the request headers&#xA;        request_data = b""&#xA;        while b"\r\n\r\n" not in request_data:&#xA;            chunk = client_socket.recv(1024)&#xA;            if not chunk:&#xA;                break&#xA;            request_data &#x2B;= chunk&#xA;&#xA;        # Send a proper HTTP response header to satisfy clients like curl&#xA;        response_header = (&#xA;            "HTTP/1.1 200 OK\r\n"&#xA;            "Content-Type: application/octet-stream\r\n"&#xA;            "Connection: close\r\n"&#xA;            "\r\n"&#xA;        )&#xA;        client_socket.sendall(response_header.encode("utf-8"))&#xA;&#xA;        with clients_lock:&#xA;            clients.append(client_socket)&#xA;        print(f"[&#x2B;] Client from {addr} is ready to receive stream.")&#xA;    except Exception as e:&#xA;        print(f"[!] Error handling client {addr}: {e}")&#xA;        client_socket.close()&#xA;&#xA;def read_from_source_and_broadcast(source_url, clients, clients_lock):&#xA;    """&#xA;    Continuously connect to the source URL (following redirects) using custom headers&#xA;    so that it mimics a curl-like request. In case of connection errors (e.g. connection reset),&#xA;    wait a bit and then try again.&#xA;    &#xA;    For each successful connection, stream data in chunks and broadcast each chunk&#xA;    to all connected clients.&#xA;    """&#xA;    # Set custom headers to mimic curl&#xA;    headers = {&#xA;        "User-Agent": "curl/8.5.0",&#xA;        "Accept": "*/*"&#xA;    }&#xA;&#xA;    while True:&#xA;        try:&#xA;            print(f"[&#x2B;] Fetching from source URL (with redirects): {source_url}")&#xA;            with requests.get(source_url, stream=True, allow_redirects=True, headers=headers) as resp:&#xA;                if resp.status_code >= 400:&#xA;                    print(f"[!] Got HTTP {resp.status_code} from the source. Retrying in 5 seconds.")&#xA;                    time.sleep(5)&#xA;                    continue&#xA;&#xA;                # Stream data and broadcast each chunk&#xA;                for chunk in resp.iter_content(chunk_size=4096):&#xA;                    if not chunk:&#xA;                        continue&#xA;                    with clients_lock:&#xA;                        for c in clients[:]:&#xA;                            try:&#xA;                                c.sendall(chunk)&#xA;                            except Exception as e:&#xA;                                print(f"[!] A client disconnected or send failed: {e}")&#xA;                                c.close()&#xA;                                clients.remove(c)&#xA;        except requests.exceptions.RequestException as e:&#xA;            print(f"[!] Source connection error, retrying in 5 seconds: {e}")&#xA;            time.sleep(5)&#xA;&#xA;def main():&#xA;    if len(sys.argv) != 3:&#xA;        print(f"Usage: {sys.argv[0]}  <port>")&#xA;        sys.exit(1)&#xA;&#xA;    source_url = sys.argv[1]&#xA;    port = int(sys.argv[2])&#xA;&#xA;    # Create a TCP socket to listen for incoming connections&#xA;    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)&#xA;    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)&#xA;    server_socket.bind(("0.0.0.0", port))&#xA;    server_socket.listen(5)&#xA;    print(f"[&#x2B;] Listening on port {port}...")&#xA;&#xA;    # List of currently connected client sockets&#xA;    clients = []&#xA;    clients_lock = threading.Lock()&#xA;&#xA;    # Start a thread to accept incoming client connections&#xA;    t_accept = threading.Thread(&#xA;        target=accept_connections,&#xA;        args=(server_socket, clients, clients_lock),&#xA;        daemon=True&#xA;    )&#xA;    t_accept.start()&#xA;&#xA;    # Continuously read from the source URL and broadcast to connected clients&#xA;    read_from_source_and_broadcast(source_url, clients, clients_lock)&#xA;&#xA;if __name__ == "__main__":&#xA;    main()&#xA;</port>

    &#xA;

    When i write command python3 proxy_server.py &#x27;http://channelurl&#x27; 9999&#xA;I getting error.

    &#xA;

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

    &#xA;