Recherche avancée

Médias (29)

Mot : - Tags -/Musique

Autres articles (78)

  • Participer à sa traduction

    10 avril 2011

    Vous pouvez nous aider à améliorer les locutions utilisées dans le logiciel ou à traduire celui-ci dans n’importe qu’elle nouvelle langue permettant sa diffusion à de nouvelles communautés linguistiques.
    Pour ce faire, on utilise l’interface de traduction de SPIP où l’ensemble des modules de langue de MediaSPIP sont à disposition. ll vous suffit de vous inscrire sur la liste de discussion des traducteurs pour demander plus d’informations.
    Actuellement MediaSPIP n’est disponible qu’en français et (...)

  • 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 (...)

Sur d’autres sites (12275)

  • MoviePy write_videofile is very slow [closed]

    3 novembre 2024, par RukshanJS

    I've seen multiple questions on SO relating with this, but couldn't find a solid answer. The following is my code.

    


    async def write_final_video(clip, output_path, results_dir):
    cpu_count = psutil.cpu_count(logical=False)
    threads = max(1, min(cpu_count - 1, 16))

    os.makedirs(results_dir, exist_ok=True)

    output_params = {
        "codec": await detect_hardware_encoder(),
        "audio_codec": "aac",
        "fps": 24,
        "threads": threads,
        "preset": "medium",
        "bitrate": "5000k",
        "audio_bitrate": "192k",
    }

    logger.info(f"Starting video writing process with codec: {output_params['codec']}")
    try:
        await asyncio.to_thread(
            clip.write_videofile,
            output_path,
            **output_params,
        )
    except Exception as e:
        logger.error(f"Error during video writing with {output_params['codec']}: {str(e)}")
        logger.info("Falling back to libx264 software encoding")
        output_params["codec"] = "libx264"
        output_params["preset"] = "medium"
        try:
            await asyncio.to_thread(
                clip.write_videofile,
                output_path,
                **output_params,
            )
        except Exception as e:
            logger.error(f"Error during fallback video writing: {str(e)}")
            raise
    finally:
        logger.info("Video writing process completed")

    # Calculate and return the relative path
    relative_path = os.path.relpath(output_path, start=os.path.dirname(ARTIFACTS_DIR))
    return relative_path


    


    and the helper function to get encoder is below

    


    async def detect_hardware_encoder():
    try:
        result = await asyncio.to_thread(
            subprocess.run,
            ["ffmpeg", "-encoders"],
            capture_output=True,
            text=True
        )

        # Check for hardware encoders in order of preference
        if "h264_videotoolbox" in result.stdout:
            return "h264_videotoolbox"
        elif "h264_nvenc" in result.stdout:
            return "h264_nvenc"
        elif "h264_qsv" in result.stdout:
            return "h264_qsv"

        return "libx264"  # Default software encoder
    except Exception:
        logger.warning("Failed to check for hardware acceleration. Using default encoder.")
        return "libx264"


    


    This code makes the rendering of a 15s video around 6min+ which is not acceptable.

    


    t:  62%|██████▏   | 223/361 [04:40<03:57,  1.72s/it, now=None]

    


    My config is MPS (Apple Silicon Metal Performance Shader), but also should work with NVIDIA CUDA.

    


    Update :
Question :
How can i reduce the time to write the video.

    


  • FFMPEG C Library : Encoding h264 stream into Matroska .mkv on MacOS

    2 mai 2024, par KaisoHHH

    FFMPEG C Library : Encoding h264 stream into Matroska .mkv container creates corrupt files

    


    Above is the related question, and the answer of allocating memory for extradata of codec context works.

    


    But on MacOS, with the encoder videotoolbox, this approach creates corrupted video file for any container, including mp4 and mkv. But what it does better for mkv is that at least the corrupted file is not 0 size.

    


    I was wondering what is the correct way to encode stream to mkv on MacOS ?

    


    Below is my code initiating the outputcodec

    


        auto path = previewPath.toStdString(); // Convert file path to standard string&#xA;&#xA;    // qInfo() &lt;&lt; "[test0306] output path is " &lt;&lt; _filePath;&#xA;&#xA;    // Allocate the output media context&#xA;    avformat_alloc_output_context2(&amp;_outputFormat, NULL, NULL, path.c_str());&#xA;    if (!_outputFormat) {&#xA;        printf("Could not deduce output format from file extension: using MPEG.\n");&#xA;        avformat_alloc_output_context2(&amp;_outputFormat, NULL, "mp4", path.c_str());&#xA;    }&#xA;    if (!_outputFormat) {&#xA;        emit cacheError(previewPath, "Could not create output context\n");&#xA;        return;&#xA;    }&#xA;&#xA;    // Find the video encoder&#xA;    auto codecName = metaData["encoderId"].toString().toStdString();&#xA;    const AVCodec *codec = avcodec_find_encoder_by_name(codecName.c_str());&#xA;    qDebug() &lt;&lt; "[test0307] this is the meta data encoder info: " &lt;&lt; codecName;&#xA;&#xA;    if (!codec) {&#xA;        qDebug() &lt;&lt; "Cannot find encoder by name";&#xA;        emit cacheError(previewPath, "Cannot find encoder by name");&#xA;        return;&#xA;    }&#xA;&#xA;    // Set up the sar, time base and frame rate from metadata&#xA;    // AVRational timeBase = {metaData["timeBaseNum"].toInt(), metaData["timeBaseDen"].toInt()};&#xA;    AVRational timeBase = {metaData["outputTimeBaseNum"].toInt(), metaData["outputTimeBaseDen"].toInt()};&#xA;    // AVRational framerate = {metaData["framerateNum"].toInt(), metaData["framerateDen"].toInt()};&#xA;    AVRational framerate = av_d2q(metaData["outputFps"].toDouble(), 100000);&#xA;    AVRational sar = {metaData["sarNum"].toInt(), metaData["sarDen"].toInt()};&#xA;    AVRational avg_frame_rate = {metaData["avg_frame_rate_num"].toInt(), metaData["avg_frame_rate_den"].toInt()};&#xA;    AVRational r_frame_rate = {metaData["r_frame_rate_num"].toInt(), metaData["r_frame_rate_den"].toInt()};&#xA;&#xA;    qInfo() &lt;&lt; "Diskcache is gonna cache video on fps" &lt;&lt; metaData["outputFps"].toDouble();&#xA;    // Create a new stream in the output file&#xA;    AVStream* outSt = avformat_new_stream(_outputFormat, codec);&#xA;    if (!outSt) {&#xA;        emit cacheError(previewPath, "Failed to create output stream\n");&#xA;        return;&#xA;    }&#xA;    // outSt->time_base = timeBase;&#xA;    // outSt->id = _outputFormat->nb_streams - 1;&#xA;&#xA;    // Allocate the codec context for the encoder&#xA;    _outputCodecContext = avcodec_alloc_context3(codec);&#xA;    if (!_outputCodecContext) {&#xA;        emit cacheError(previewPath, "Could not alloc an encoding context\n");&#xA;        return;&#xA;    }&#xA;&#xA;    // Configure the codec context&#xA;    _outputCodecContext->codec_id = codec->id;&#xA;    _outputCodecContext->codec_type = codec->type;&#xA;    // if(metaData["bitrate"].toInt() > 0){&#xA;    _outputCodecContext->bit_rate = metaData["bitrate"].toInt();&#xA;    // }&#xA;    // else{&#xA;    //     _outputCodecContext->bit_rate = 80000;&#xA;    // }&#xA;    _outputCodecContext->max_b_frames = 0;&#xA;    _outputCodecContext->width = metaData["outputWidth"].toInt();&#xA;    _outputCodecContext->height = metaData["outputHeight"].toInt();&#xA;    _outputCodecContext->framerate = framerate; // Set from metadata&#xA;    _outputCodecContext->time_base = timeBase;//timeBase; // Set from metadata&#xA;    _outputCodecContext->pix_fmt = AV_PIX_FMT_YUV420P; // img need yuv420p&#xA;&#xA;    outSt->time_base           = _outputCodecContext->time_base;&#xA;    outSt->avg_frame_rate      = framerate;&#xA;    outSt->r_frame_rate        = framerate;&#xA;    outSt->disposition         = metaData["disposition"].toInt();&#xA;    outSt->discard             = static_cast<avdiscard>(metaData["discard"].toInt());&#xA;    outSt->sample_aspect_ratio = sar;&#xA;    outSt->event_flags         = metaData["event_flags"].toInt();&#xA;    outSt->pts_wrap_bits       = metaData["pts_wrap_bits "].toInt();&#xA;&#xA;    // // codecpar->extradata needed for MKV, this break mac playing back to preview&#xA;#ifdef Q_OS_WINDOWS&#xA;    _outputCodecContext->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;&#xA;    _outputCodecContext->extradata = (uint8_t*)av_mallocz(sizeof(int) * sizeof(int) * sizeof(int) / 2);&#xA;    _outputCodecContext->extradata_size = sizeof(int) * sizeof(int) * sizeof(int) / 2;&#xA;#elif defined(Q_OS_MACOS)&#xA;&#xA;#endif&#xA;&#xA;&#xA;    // Open the codec&#xA;    AVDictionary *opt = NULL;&#xA;    int ret = avcodec_open2(_outputCodecContext, codec, &amp;opt);&#xA;    av_dict_free(&amp;opt);&#xA;    if (ret &lt; 0) {&#xA;        emit cacheError(previewPath, "Could not open video codec\n");&#xA;        return;&#xA;    }&#xA;&#xA;    // Copy codec parameters from context to the stream&#xA;    ret = avcodec_parameters_from_context(outSt->codecpar, _outputCodecContext);&#xA;    if (ret &lt; 0) {&#xA;        emit cacheError(previewPath, "Could not copy the stream parameters\n");&#xA;        return;&#xA;    }&#xA;&#xA;    // Print format details&#xA;    av_dump_format(_outputFormat, 0, path.c_str(), 1);&#xA;&#xA;    // Open the output file&#xA;    ret = avio_open(&amp;_outputFormat->pb, path.c_str(), AVIO_FLAG_WRITE);&#xA;    if (ret &lt; 0) {&#xA;        emit cacheError(previewPath, "Could not open output file\n");&#xA;        return;&#xA;    }&#xA;&#xA;    // Write the stream header&#xA;    AVDictionary *params = NULL;&#xA;    //av_dict_set(&amp;params, "movflags", "frag_keyframe&#x2B;empty_moov&#x2B;delay_moov&#x2B;use_metadata_tags&#x2B;write_colr", 0);&#xA;    ret = avformat_write_header(_outputFormat, NULL);&#xA;    if (ret &lt; 0) {&#xA;        char err_buf[AV_ERROR_MAX_STRING_SIZE];  // Define a buffer for error strings.&#xA;        if (av_strerror(ret, err_buf, sizeof(err_buf)) == 0) {  // Safely get the error string.&#xA;            qInfo() &lt;&lt; "write header error:" &lt;&lt; err_buf;  // Now use the buffer for logging.&#xA;            emit cacheError(previewPath, "Error occurred when opening output file", ret);&#xA;        } else {&#xA;            qInfo() &lt;&lt; "write header error: Unknown error with code" &lt;&lt; ret;&#xA;            emit cacheError(previewPath, "Error occurred when opening output file: Unknown error", ret);&#xA;        }&#xA;        return;&#xA;&#xA;    }&#xA;</avdiscard>

    &#xA;

    I have tried to limit this approach only on windows and waiting to find a solution to do it with videotoolbox on MacOS.

    &#xA;

  • Why doesn't the ffmpeg output display the stream in the browser ? [closed]

    10 mai 2024, par Tebyy

    Why is it that when I create a livestream in Python using ffmpeg, and then I open the browser and visit the page, the page keeps loading continuously, and in PyCharm logs, I see binary data ? There are no errors displayed, and the code seems correct to me. I even tried saving to a file for testing purposes, and when I play the video, everything works fine. Does anyone know what might be wrong here ?

    &#xA;

    Code :

    &#xA;

    def generate_frames():&#xA;    cap = cv2.VideoCapture(os.path.normpath(app_root_dir().joinpath("data/temp", "video-979257305707693982.mp4")))&#xA;    while cap.isOpened():&#xA;        ret, frame = cap.read()&#xA;        if not ret:&#xA;            break&#xA;&#xA;        yield frame&#xA;&#xA;&#xA;@app.route(&#x27;/video_feed&#x27;)&#xA;def video_feed():&#xA;    ffmpeg_command = [&#xA;        &#x27;ffmpeg&#x27;, &#x27;-f&#x27;, &#x27;rawvideo&#x27;, &#x27;-pix_fmt&#x27;, &#x27;bgr24&#x27;,&#xA;        &#x27;-s:v&#x27;, &#x27;1920x1080&#x27;, &#x27;-r&#x27;, &#x27;60&#x27;,&#xA;        &#x27;-i&#x27;, &#x27;-&#x27;, &#x27;-vf&#x27;, &#x27;setpts=2.5*PTS&#x27;, # Video Speed&#xA;        &#x27;-c:v&#x27;, &#x27;libvpx-vp9&#x27;, &#x27;-g&#x27;, &#x27;60&#x27;, &#x27;-keyint_min&#x27;, &#x27;60&#x27;,&#xA;        &#x27;-b:v&#x27;, &#x27;6M&#x27;, &#x27;-minrate&#x27;, &#x27;4M&#x27;, &#x27;-maxrate&#x27;, &#x27;12M&#x27;, &#x27;-bufsize&#x27;, &#x27;8M&#x27;,&#xA;        &#x27;-crf&#x27;, &#x27;0&#x27;, &#x27;-deadline&#x27;, &#x27;realtime&#x27;, &#x27;-tune&#x27;, &#x27;psnr&#x27;, &#x27;-quality&#x27;, &#x27;good&#x27;,&#xA;        &#x27;-tile-columns&#x27;, &#x27;6&#x27;, &#x27;-threads&#x27;, &#x27;8&#x27;, &#x27;-lag-in-frames&#x27;, &#x27;16&#x27;,&#xA;        &#x27;-f&#x27;, &#x27;webm&#x27;, &#x27;-&#x27;&#xA;    ]&#xA;    ffmpeg_process = subprocess.Popen(ffmpeg_command, stdin=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1)&#xA;    frames_generator = generate_frames()&#xA;    for frame in frames_generator:&#xA;        ffmpeg_process.stdin.write(frame)&#xA;        ffmpeg_process.stdin.flush()&#xA;&#xA;    ffmpeg_process.stdin.close()&#xA;    ffmpeg_process.wait()&#xA;&#xA;    def generate_video_stream(process):&#xA;        startTime = time.time()&#xA;        buffer = []&#xA;        sentBurst = False&#xA;        for chunk in iter(lambda: process.stderr.read(4096), b&#x27;&#x27;):&#xA;            buffer.append(chunk)&#xA;&#xA;            # Minimum buffer time, 3 seconds&#xA;            if sentBurst is False and time.time() > startTime &#x2B; 3 and len(buffer) > 0:&#xA;                sentBurst = True&#xA;                for i in range(0, len(buffer) - 2):&#xA;                    print("Send initial burst #", i)&#xA;                    yield buffer.pop(0)&#xA;&#xA;            elif time.time() > startTime &#x2B; 3 and len(buffer) > 0:&#xA;                yield buffer.pop(0)&#xA;&#xA;            process.poll()&#xA;            if isinstance(process.returncode, int):&#xA;                if process.returncode > 0:&#xA;                    print(&#x27;FFmpeg Error&#x27;, process.returncode)&#xA;&#xA;                break&#xA;&#xA;    return Response(stream_with_context(generate_video_stream(ffmpeg_process)), mimetype=&#x27;video/webm&#x27;, content_type="video/webm; codecs=vp9", headers=Headers([("Connection", "close")]))&#xA;&#xA;

    &#xA;