Recherche avancée

Médias (91)

Autres articles (112)

  • Script d’installation automatique de MediaSPIP

    25 avril 2011, par

    Afin de palier aux difficultés d’installation dues principalement aux dépendances logicielles coté serveur, un script d’installation "tout en un" en bash a été créé afin de faciliter cette étape sur un serveur doté d’une distribution Linux compatible.
    Vous devez bénéficier d’un accès SSH à votre serveur et d’un compte "root" afin de l’utiliser, ce qui permettra d’installer les dépendances. Contactez votre hébergeur si vous ne disposez pas de cela.
    La documentation de l’utilisation du script d’installation (...)

  • Demande de création d’un canal

    12 mars 2010, par

    En fonction de la configuration de la plateforme, l’utilisateur peu avoir à sa disposition deux méthodes différentes de demande de création de canal. La première est au moment de son inscription, la seconde, après son inscription en remplissant un formulaire de demande.
    Les deux manières demandent les mêmes choses fonctionnent à peu près de la même manière, le futur utilisateur doit remplir une série de champ de formulaire permettant tout d’abord aux administrateurs d’avoir des informations quant à (...)

  • La sauvegarde automatique de canaux SPIP

    1er avril 2010, par

    Dans le cadre de la mise en place d’une plateforme ouverte, il est important pour les hébergeurs de pouvoir disposer de sauvegardes assez régulières pour parer à tout problème éventuel.
    Pour réaliser cette tâche on se base sur deux plugins SPIP : Saveauto qui permet une sauvegarde régulière de la base de donnée sous la forme d’un dump mysql (utilisable dans phpmyadmin) mes_fichiers_2 qui permet de réaliser une archive au format zip des données importantes du site (les documents, les éléments (...)

Sur d’autres sites (11872)

  • Queue in Python processing more than one video at a time ? [closed]

    12 novembre 2024, par Mateus Coelho

    I have an raspberry pi, that i proccess videos, rotate and put 4 water marks, but, when i run into the raspberry pi, it uses 100% of 4CPUS threads and it reboots. I solved this using -threads 1, to prevent the usage of just one of the 4 CPUS cores, it worked.

    


    I made a Queue to procces one at a time, because i have 4 buttons that trigger the videos. But, when i send more then 3 videos to the Queue, the rasp still reboots, and im monitoring the CPU usage, is 100% for only one of the four CPUS
enter image description here

    


    But, if i send 4 or 5 videos to the thread folder, it completly reboots, and the most awkward, its after the reboot, it made its way to proceed all the videos.

    


    
import os
import time
import subprocess
from google.cloud import storage
import shutil

QUEUE_DIR = "/home/abidu/Desktop/ApertaiRemoteClone"
ERROR_VIDEOS_DIR = "/home/abidu/Desktop/ApertaiRemoteClone/ErrorVideos"
CREDENTIALS_PATH = "/home/abidu/Desktop/keys.json"
BUCKET_NAME = "videos-283812"

def is_valid_video(file_path):
    try:
        result = subprocess.run(
            ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', file_path],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        return result.returncode == 0
    except Exception as e:
        print(f"Erro ao verificar o vídeo: {e}")
        return False

def overlay_images_on_video(input_file, image_files, output_file, positions, image_size=(100, 100), opacity=0.7):
    inputs = ['-i', input_file]
    for image in image_files:
        if image:
            inputs += ['-i', image]
    filter_complex = "[0:v]transpose=2[rotated];"
    current_stream = "[rotated]"
    for i, (x_offset, y_offset) in enumerate(positions):
        filter_complex += f"[{i+1}:v]scale={image_size[0]}:{image_size[1]},format=rgba,colorchannelmixer=aa={opacity}[img{i}];"
        filter_complex += f"{current_stream}[img{i}]overlay={x_offset}:{y_offset}"
        if i < len(positions) - 1:
            filter_complex += f"[tmp{i}];"
            current_stream = f"[tmp{i}]"
        else:
            filter_complex += ""
    command = ['ffmpeg', '-y', '-threads', '1'] + inputs + ['-filter_complex', filter_complex, '-threads', '1', output_file]

    try:
        result = subprocess.run(command, check=True)
        result.check_returncode()  # Verifica se o comando foi executado com sucesso
        print(f"Vídeo processado com sucesso: {output_file}")
    except subprocess.CalledProcessError as e:
        print(f"Erro ao processar o vídeo: {e}")
        if "moov atom not found" in str(e):
            print("Vídeo corrompido ou sem o moov atom. Pulando o arquivo.")
        raise  # Relança a exceção para ser tratada no nível superior

def process_and_upload_video():
    client = storage.Client.from_service_account_json(CREDENTIALS_PATH)
    bucket = client.bucket(BUCKET_NAME)
    
    while True:
        # Aguarda 10 segundos antes de verificar novos vídeos
        time.sleep(10)

        # Verifica se há arquivos no diretório de fila
        queue_files = [f for f in os.listdir(QUEUE_DIR) if f.endswith(".mp4")]
        
        if queue_files:
            video_file = os.path.join(QUEUE_DIR, queue_files[0])  # Pega o primeiro vídeo na fila
            
            # Define o caminho de saída após o processamento com o mesmo nome do arquivo de entrada
            output_file = os.path.join(QUEUE_DIR, "processed_" + os.path.basename(video_file))
            if not is_valid_video(video_file):
                print(f"Arquivo de vídeo inválido ou corrompido: {video_file}. Pulando.")
                os.remove(video_file)  # Remove arquivo corrompido
                continue

            # Processa o vídeo com a função overlay_images_on_video
            try:
                overlay_images_on_video(
                    video_file,
                    ["/home/abidu/Desktop/ApertaiRemoteClone/Sponsor/image1.png", 
                     "/home/abidu/Desktop/ApertaiRemoteClone/Sponsor/image2.png", 
                     "/home/abidu/Desktop/ApertaiRemoteClone/Sponsor/image3.png", 
                     "/home/abidu/Desktop/ApertaiRemoteClone/Sponsor/image4.png"],
                    output_file,
                    [(10, 10), (35, 1630), (800, 1630), (790, 15)],
                    image_size=(250, 250),
                    opacity=0.8
                )
                
                if os.path.exists(output_file):
                    blob = bucket.blob(os.path.basename(video_file).replace("-", "/"))
                    blob.upload_from_filename(output_file, content_type='application/octet-stream')
                    print(f"Uploaded {output_file} to {BUCKET_NAME}")
                    os.remove(video_file)
                    os.remove(output_file)
                    print(f"Processed and deleted {video_file} and {output_file}.")
            
            except subprocess.CalledProcessError as e:
                print(f"Erro ao processar {video_file}: {e}")
                
                move_error_video_to_error_directory(video_file)

                continue  # Move para o próximo vídeo na fila após erro

def move_error_video_to_error_directory(video_file):
    print(f"Movendo arquivo de vídeo com erro {video_file} para {ERROR_VIDEOS_DIR}")

    if not os.path.exists(ERROR_VIDEOS_DIR):
        os.makedirs(ERROR_VIDEOS_DIR)
                
    shutil.move(video_file, ERROR_VIDEOS_DIR)

if __name__ == "__main__":
    process_and_upload_video()



    


  • Compile FFmpeg with x264 for MacOS and Windows on Linux

    9 mars 2023, par RobinFrcd

    I successfully managed to compile a minimal standalone FFmpeg binary to create MP4 videos from JPG images encoded with x264. The binary is 100% functional and is 5.2MB.

    


    To do that, I used :

    


    ./configure \
--disable-everything \
--enable-decoder=mjpeg \
--enable-encoder=libx264 \
--enable-protocol=concat,file \
--enable-demuxer=image2 \
--enable-muxer=mp4 \
--enable-filter=scale \
--enable-gpl \
--enable-libx264 \
--extra-ldexeflags="-static" \
--pkg-config="pkg-config --static"


    


    I now would like to build the macOS and windows binaries directly from my Linux machine. I tried this repo and replaced the config args with mine, but the output exe is 30MB+. And I don't find anything about building for MacOS.

    


    Is there a solution to make this minimal build cross-platform compatible ?

    


  • FFMPEG to OpenGL Texture

    23 avril 2014, par Spamdark

    I was here to ask, how can I convert an AVFrame to an opengl texture. Actually, I created a renderer the outputs me the audio (Audio is working) and the video, but the video is not outputing. Here is my code :

    Texture creation :

    glGenTextures(1,&_texture);
    glBindTexture(GL_TEXTURE_2D,_texture);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

    Code Info : _texture variable is a GLuint that keeps the texture ID

    Function that gets the AVFrame and convert it to OpenGL Texture :

    int VideoGL::NextVideoFrame(){
    // Get a packet from the queue
    AVPacket *videopacket = this->DEQUEUE(VIDEO);
    int frameFinished;
    if(videopacket!=0){
       avcodec_decode_video2(_codec_context_video, _std_frame,&frameFinished,videopacket);

       if(frameFinished){

           sws_scale(sws_ctx, _std_frame->data, _std_frame->linesize, 0, _codec_context_video->height, _rgb_frame->data, _rgb_frame->linesize);

           if(_firstrendering){
           glBindTexture(GL_TEXTURE_2D,_texture);
           glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, _codec_context_video->width,_codec_context_video->height,0,GL_RGB,GL_UNSIGNED_BYTE,_rgb_frame->data[0]);

           _firstrendering = false;

           }else{

               glActiveTexture(_texture);
               glBindTexture(GL_TEXTURE_2D,_texture);
               glTexSubImage2D(GL_TEXTURE_2D,0,0,0,_codec_context_video->width,_codec_context_video->height,GL_RGB,GL_UNSIGNED_BYTE,_rgb_frame->data[0]);

           }
           av_free_packet(videopacket);
           return 0;
       }else{

           av_free_packet(videopacket);
           return -1;
       }

    }else{
       return -1;
    }
    return 0;
    }

    Code Information : There is a queue where a thread store the AVFrames, this function is frequently called to get the AVFrames, until it gets a NULL it stops to being called.

    That’s actually not working. (I tried to look at some questions in stack overflow, it’s still not working)
    Any example, or someone that helps me to correct any error there ?

    Additional Data : I tried to change the GL_RGB to GL_RGBA and started to play with the formats, anyway it crashes when I try GL_RGBA (Because the width and height are very big, anyway I tried to resize them). I have tried to change the sizes to Power Of 2, stills not working.

    1 Edit :

    Thread function :

    DWORD WINAPI VideoGL::VidThread(LPVOID myparam){

    VideoGL * instance = (VideoGL*) myparam;
    instance->wave_audio->Start();

    int quantity=0;

    AVPacket packet;
    while(av_read_frame(instance->_format_context,&packet) >= 0){
       if(packet.stream_index==instance->videoStream){
           instance->ENQUEUE(VIDEO,&packet);
       }
       if(packet.stream_index==instance->audioStream){
           instance->ENQUEUE(AUDIO,&packet);
       }
    }

    instance->ENQUEUE(AUDIO,NULL);
    instance->ENQUEUE(VIDEO,NULL);

    return 0;
    }

    Thread creation function :

    CreateThread(NULL, 0, VidThread, this, NULL, NULL);

    Where this refers to the class that contains the NextVideoFrame, and the _texture members.

    Solved :

    I followed some of the datenwolf tips, and now the video is displaying correctly with the audio/video :

    Screenshot took