
Recherche avancée
Autres articles (63)
-
Le profil des utilisateurs
12 avril 2011, parChaque utilisateur dispose d’une page de profil lui permettant de modifier ses informations personnelle. Dans le menu de haut de page par défaut, un élément de menu est automatiquement créé à l’initialisation de MediaSPIP, visible uniquement si le visiteur est identifié sur le site.
L’utilisateur a accès à la modification de profil depuis sa page auteur, un lien dans la navigation "Modifier votre profil" est (...) -
Configurer la prise en compte des langues
15 novembre 2010, parAccéder à la configuration et ajouter des langues prises en compte
Afin de configurer la prise en compte de nouvelles langues, il est nécessaire de se rendre dans la partie "Administrer" du site.
De là, dans le menu de navigation, vous pouvez accéder à une partie "Gestion des langues" permettant d’activer la prise en compte de nouvelles langues.
Chaque nouvelle langue ajoutée reste désactivable tant qu’aucun objet n’est créé dans cette langue. Dans ce cas, elle devient grisée dans la configuration et (...) -
XMP PHP
13 mai 2011, parDixit Wikipedia, XMP signifie :
Extensible Metadata Platform ou XMP est un format de métadonnées basé sur XML utilisé dans les applications PDF, de photographie et de graphisme. Il a été lancé par Adobe Systems en avril 2001 en étant intégré à la version 5.0 d’Adobe Acrobat.
Étant basé sur XML, il gère un ensemble de tags dynamiques pour l’utilisation dans le cadre du Web sémantique.
XMP permet d’enregistrer sous forme d’un document XML des informations relatives à un fichier : titre, auteur, historique (...)
Sur d’autres sites (7745)
-
C++ FFmpeg encode stream to mp4 wrong fps and kbs
22 mars 2024, par elmomoJackyi'm new to FFmpeg, i'm trying to learn how to encode images to an mp4 using a stream.
But even tough i can generate a playable file, my file is "broken", it does does past 1sec, and if i check it's data with ffmpeg i can see that it's duration is accordly wrong with the kb/s fps value




Duration : 00:00:00.01 .... 2635232 kb/s, 15463.09 fps.




ffmpeg -i 25_5.mp4 -f ffmetadata 25_5.txt


Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '25_5.mp4':
 Metadata:
 major_brand : isom
 minor_version : 512
 compatible_brands: isomiso2mp41
 title : Your Title Here
 encoder : Lavf60.16.100
 comment : Your Comment Here
 copyright : Copyright Information
 Duration: 00:00:00.01, start: 0.000000, bitrate: 2557680 kb/s
 Stream #0:0(und): Video: mpeg4 (Simple Profile) (mp4v / 0x7634706D), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 2635232 kb/s, 15463.09 fps, 15360 tbr, 15360 tbn, 30 tbc (default)
 Metadata:
 handler_name : VideoHandler
 vendor_id : [0][0][0][0]
File '25_5.txt' already exists. Overwrite? [y/N] y
Output #0, ffmetadata, to '25_5.txt':
 Metadata:
 major_brand : isom
 minor_version : 512
 compatible_brands: isomiso2mp41
 title : Your Title Here
 copyright : Copyright Information
 comment : Your Comment Here
 encoder : Lavf58.76.100



Here is my cpp and header code (using visual studio and vcpkg install ffmpeg)
file ffmpeg_example.cpp



#include "ffmpeg_example.h"

#include 
#include 
#include 
#include <iostream>
#include <map>

extern "C" {
#include <libavcodec></libavcodec>avcodec.h>
#include <libavformat></libavformat>avformat.h>
#include <libavutil></libavutil>imgutils.h>
#include <libavutil></libavutil>opt.h>
#include <libswscale></libswscale>swscale.h>

}

#define COMMON_AV_FRAME_FORMAT AV_PIX_FMT_YUV420P 

ffmpeg_example::ffmpeg_example()
{

}

ffmpeg_example::~ffmpeg_example()
{

}

void ffmpeg_example::set_codec_params(AVFormatContext*& fctx, AVCodecContext*& codec_ctx, double width, double height, int fps, int bitrate) {
 std::cout << "encoding video for width:" << width << ", height:" << height << ", fps:" << fps << ", bitrate:" << bitrate << std::endl;
 codec_ctx->codec_id = fctx->oformat->video_codec;
 codec_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
 codec_ctx->width = width;
 codec_ctx->height = height;
 codec_ctx->gop_size = 12;
 codec_ctx->pix_fmt = COMMON_AV_FRAME_FORMAT;
 codec_ctx->framerate = AVRational{ fps, 1 };
 codec_ctx->time_base = AVRational{ 1, fps };
 if (bitrate) codec_ctx->bit_rate = bitrate;
 if (fctx->oformat->flags & AVFMT_GLOBALHEADER) {
 codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
 }
}

AVStream* ffmpeg_example::create_stream(AVFormatContext*& fctx, AVCodecContext*& codec_ctx) {
 AVStream* stream = avformat_new_stream(fctx, nullptr);
 avcodec_parameters_from_context(stream->codecpar, codec_ctx);
 stream->time_base = codec_ctx->time_base;
 //stream->r_frame_rate = codec_ctx->framerate;
 //stream->avg_frame_rate = stream->r_frame_rate;
 return stream;
}

AVFrame* ffmpeg_example::create_frame(int width, int height) {
 AVFrame* frame = av_frame_alloc();
 frame->format = COMMON_AV_FRAME_FORMAT;
 frame->width = width;
 frame->height = height;
 av_frame_get_buffer(frame, 0);
 return frame;
}

void ffmpeg_example::fill_fake_yuv_image(AVFrame* frame, int frame_index, int width, int height) {
 /* Ensure the data buffers are writable */
 av_frame_make_writable(frame);

 // This is where you could load actual image data into the frame.
 // For demonstration, we fill the frame with a color.
 // Y
 for (int y = 0; y < height; y++) {
 for (int x = 0; x < width; x++) {
 frame->data[0][y * frame->linesize[0] + x] = x + y + frame_index * 3;
 }
 }

 // Cb and Cr
 for (int y = 0; y < height / 2; y++) {
 for (int x = 0; x < width / 2; x++) {
 frame->data[1][y * frame->linesize[1] + x] = 128 + y + frame_index * 2;
 frame->data[2][y * frame->linesize[2] + x] = 64 + x + frame_index * 5;
 }
 }
}

int ffmpeg_example::initFfmpegcontext()
{
 int ret;


 // Initialize the AVFormatContext
 if (avformat_alloc_output_context2(&output_format_context, nullptr, _ouput_format, nullptr) < 0 || !output_format_context) {
 std::cout << "Could not allocat output context." << std::endl;
 return -1;
 }


 // Find the encoder
 encoder = avcodec_find_encoder(output_format_context->oformat->video_codec);
 if (!encoder) {
 std::cout << "Could not find encoder." << std::endl;
 return -1;
 }

 // Create a new codec context
 codec_context = avcodec_alloc_context3(encoder);
 if (!codec_context) {
 std::cout << "Could not allocate codec context." << std::endl;
 return -1;
 }

 // Set codec parameters
 set_codec_params(output_format_context, codec_context, 1920, 1080, video_fps, 0);

 // Open the codec
 ret = avcodec_open2(codec_context, encoder, nullptr);
 if (ret < 0) {
 std::cout << "Could not open encoder with context." << std::endl;
 return -1;
 }

 // Create a new video stream
 video_stream = create_stream(output_format_context, codec_context);
 if (!video_stream) {
 std::cout << "Could not create stream." << std::endl;
 return -1;
 }

 // Initialize the IO context
 if (!(output_format_context->oformat->flags & AVFMT_NOFILE)) {
 std::cout << "Init IO, AVFMT_NOFILE not detected." << std::endl;
 if (avio_open(&output_format_context->pb, output, AVIO_FLAG_WRITE) < 0) {
 std::cout << "Could not open output file." << std::endl;
 return -1;
 }
 }

 // Write the file header
 ret = avformat_write_header(output_format_context, nullptr);
 if (ret < 0) {
 std::cout << "Could not write file header." << std::endl;
 return -1;
 }

 // Create a new frame
 frame = create_frame(codec_context->width, codec_context->height);
 if (!frame) {
 std::cout << "Could not create frame." << std::endl;
 return -1;
 }

 // Create a new packet
 pkt = av_packet_alloc();
 if (!pkt) {
 std::cout << "Could not allocate packet." << std::endl;
 return -1;
 }
 return 0;
}


void ffmpeg_example::set_metadata() {
 // Ensure the format context exists
 if (!output_format_context) return;
 std::cout << "Setting metadata." << std::endl;

 // Create or get the existing metadata dictionary
 AVDictionary** metadata = &output_format_context->metadata;

 // Set various metadata fields
 av_dict_set(metadata, "title", "Your Title Here", 0);
 av_dict_set(metadata, "author", "Author Name", 0);
 av_dict_set(metadata, "copyright", "Copyright Information", 0);
 av_dict_set(metadata, "comment", "Your Comment Here", 0);
 av_dict_set(metadata, "rating", "5", 0); // Assuming rating is a simple numeric value

 // Note: The last parameter of av_dict_set is a flag; 0 means the entry will be added to the dictionary
 // if it doesn't exist, or the existing entry will be updated if it does exist.
}

int ffmpeg_example::start()
{
 int ret;
 if (initFfmpegcontext() < 0) {
 std::cout << "quitting" << std::endl;
 return -1;
 }

 set_metadata();
 std::cout << "filling stream with frames data." << std::endl;
 // Write frames
 for (int i = 0; i < video_fps * 4; i++) { // 5 seconds at video_fps fps
 frame->pts = i;
 fill_fake_yuv_image(frame, i, codec_context->width, codec_context->height);

 // Encode the image
 ret = avcodec_send_frame(codec_context, frame);
 while (ret >= 0) {
 ret = avcodec_receive_packet(codec_context, pkt);
 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
 break;
 }
 pkt->stream_index = video_stream->index;
 av_interleaved_write_frame(output_format_context, pkt);
 av_packet_unref(pkt);
 }
 }

 std::cout << "closing." << std::endl;
 // Send a null frame to the encoder to flush it
 avcodec_send_frame(codec_context, NULL);
 while (ret >= 0) {
 ret = avcodec_receive_packet(codec_context, pkt);
 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
 break;
 }
 pkt->stream_index = video_stream->index;
 av_interleaved_write_frame(output_format_context, pkt);
 av_packet_unref(pkt);
 }

 // Write the file trailer
 av_write_trailer(output_format_context);

 cleanup();
 std::cout << "done." << std::endl;

 return 0;
}

void ffmpeg_example::cleanup() {
 // Clean up
 avcodec_free_context(&codec_context);
 av_frame_free(&frame);
 av_packet_free(&pkt);
 avio_closep(&output_format_context->pb);
 avformat_free_context(output_format_context);
}
</map></iostream>


Header file :


#pragma once

class AVFormatContext;
class AVCodecContext;
class AVStream;
class AVCodec;
class AVFrame;
class AVPacket;
class AVOutputFormat;

class ffmpeg_example {
private:
 const AVCodec* encoder = nullptr;
 AVFormatContext* output_format_context = nullptr;
 AVCodecContext* codec_context = nullptr;
 AVStream* video_stream = nullptr;
 AVFrame* frame = nullptr;
 AVPacket* pkt = nullptr;

 const char* output = "output.mp4";
 const char* _ouput_format = "mp4";

 int video_fps = 30;
public:

 ffmpeg_example();
 virtual ~ffmpeg_example();

 int start();
private:
 int initFfmpegcontext();
 AVFrame* create_frame(int width, int height);
 void fill_fake_yuv_image(AVFrame* frame, int frame_index, int width, int height);
 void set_codec_params(AVFormatContext*& fctx, AVCodecContext*& codec_ctx, double width, double height, int fps, int bitrate);
 AVStream* create_stream(AVFormatContext*& fctx, AVCodecContext*& codec_ctx);

 void cleanup();
 void set_metadata();
};



You just have to call the start() function to make it work.


I understand that the problem come surely from a flag disabling my fps setting, or it's an incorrect param while generating the header, but i can't find which one.
I searched other similar examples (ffmpeg example like encode_video.c or stackoverflow post : video-too-fast, speed-encoding-problem, ffmpeg-create-mp4 )
But whatever change i make i cannot make it work (and chatgpt is as lost as me).


— edit


The only way i find to impact the fps of the ouputed video is to invers
codec_ctx->framerate = AVRational{ 1, fps };
but even with that, my video is marked 30sec (should be 5) and doesn't past 1sec.
I'M LOST, i can count the number of packet -> 150



ffprobe -v error -select_streams v:0 -count_packets -show_entries stream=nb_read_packets -of csv=p=0 output.mp4
150




Each frame has the correct pts so that it know in which order to play, my stream has the same avg_frame_rate as my codec framerate.


I don't know what i do wrong


-
How to use hardware acceleration for ffmpeg [closed]
11 mars 2024, par Kevin GilbertI am try to get hardware acceleration going on my Dell Inspiron AMD laptop. It appears that
vaapi
is installed but how to I use it inffmpeg
?

For testing, all I want is to accelerate


ffmpeg -i input.ts output.mp4



Currently, the unaccelerated command I am currently using is


ffmpeg -y -i input.ts -c:v libx264 -preset slower -tune film -filter_complex scale=1080:608 -sws_flags lanczos output.mp4



BTW : Environment is fully up-to-date Fedora 39 with stock
ffmpeg
.

-
Ffmpeg encoding too slow
8 mars 2024, par Marc CuadrasI'm using a Python script to encode mp4 videos in various qualities, in my case 360 +720 +1080.
Ffmpeg encoding videos very slow, 1 video taking 2 hours or more, I'm using good dedicated server from hetzner (ryzen 5 3600 + 64gm ram), any suggestion to improve speed will be really appreciated


import os
import glob
from datetime import datetime
import subprocess
from rich import print
import time
import sys
import pymysql as sql
import move

MYSQL_HOST = "127.0.0.1"
MYSQL_USER = ""
MYSQL_PASSWORD = ""
MYSQL_DB = ""

BASE_PATH = ''
UPLOAD_PATH = os.path.join(BASE_PATH, 'upload')
UPLOAD_PATH2 = os.path.join(BASE_PATH, 'upload2')
VIDEO_PATH = os.path.join(BASE_PATH, 'video')
LOGO_PATH = os.path.join(BASE_PATH, 'logo.png')
ERROR_PATH = os.path.join(BASE_PATH, 'error')
RCLONE_PATH = os.path.join(BASE_PATH, 'rclone')
WAIT = 60
VIDEO_LENGTH = 10
MOVE_CMD = "screen -dmS move python3 move.py --folder {}"

global current_video_id

db = sql.connect(
 host=MYSQL_HOST,
 user=MYSQL_USER,
 password=MYSQL_PASSWORD,
 database=MYSQL_DB
 )

def executedb(query):
 cursor = db.cursor()
 cursor.execute(query)
 db.commit()

def time_now():
 now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
 return now

def write_log(msg):
 log_msg = f"{time_now()}: {msg}"
 with open('log.txt','a') as f:
 f.write(log_msg)
 f.write('\n')

def change_extension(files):
 for file in files:
 os.rename(file, file.split('.')[0] + '.mkv')

def change_all_videos_extension():
 # changing all the vidoe's extension to mkv format
 MKV_files = glob.glob('*.MKV')
 AVI_files = glob.glob('*.AVI')
 avi_files = glob.glob('*.avi')
 MP4_files = glob.glob('*.MK4')
 mp4_files = glob.glob('*.mp4')
 webm_files = glob.glob('*.webm')
 ts_files = glob.glob('*.ts')

 if len(avi_files) > 0:
 print(f'[{time_now()}] Converting avi videos to mkv format')
 change_extension(avi_files)

 if len(MKV_files) > 0:
 print(f'[{time_now()}] Converting MKV videos to mkv format')
 change_extension(MKV_files)

 if len(AVI_files) > 0:
 print(f'[{time_now()}] Converting AVI videos to mkv format')
 change_extension(AVI_files)

 if len(MP4_files) > 0:
 print(f'[{time_now()}] Converting MP4 videos to mkv format')
 change_extension(MP4_files)

 if len(mp4_files) > 0:
 print(f'[{time_now()}] Converting mp4 videos to mkv format')
 change_extension(mp4_files)

 if len(webm_files) > 0:
 print(f'[{time_now()}] Converting webm videos to mkv format')
 change_extension(webm_files)

 if len(ts_files) > 0:
 print(f'[{time_now()}] Converting ts videos to mkv format')
 change_extension(ts_files)
 
def encode_480(filename):
 FILENAME_PATH = filename
 newname = filename.split('.')[0]
 newname_path = os.path.join(VIDEO_PATH, newname)

 poster_cmd = f'ffmpeg -y -ss 00:00:10 -i {FILENAME_PATH} -vframes 1 -q:v 2 poster.jpg'
 os.system(poster_cmd)
 
 if not os.path.exists(newname_path):
 os.mkdir(newname_path)

 os.replace('poster.jpg', os.path.join(newname_path, 'poster.jpg'))
 

 ffmpeg480_cmd = f'ffmpeg -hide_banner -y -i {FILENAME_PATH} -sn -c:a aac -ac 2 -c:v libx264 -crf 23 -preset fast -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod -maxrate 1024k -bufsize 1536k -b:a 128k -pix_fmt yuv420p -hls_segment_filename 4835JRK9%03d.ts 480p.m3u8'
 os.system(ffmpeg480_cmd)
 
 # os.remove(FILENAME_PATH)
 
 ts_files = glob.glob('*.ts')
 for ts_file in ts_files:
 os.replace(ts_file, os.path.join(newname_path, ts_file))
 
 master_text = '''#EXTM3U
#EXT-X-STREAM-INF:BANDWIDTH=1500000,RESOLUTION=854x480
480p.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=840000,RESOLUTION=640x360
360p.m3u8
'''
 with open('master.m3u8', 'w') as f:
 f.write(master_text)
 
 m3u8_files = glob.glob('*.m3u8')
 for m3u8_file in m3u8_files:
 os.replace(m3u8_file, os.path.join(newname_path, m3u8_file))


def encode_360(filename):
 FILENAME_PATH = filename
 newname = filename.split('.')[0]
 newname_path = os.path.join(VIDEO_PATH,newname)
 poster_cmd = f'ffmpeg -y -ss 00:00:10 -i {FILENAME_PATH} -vframes 1 -q:v 2 poster.jpg'
 os.system(poster_cmd)
 if not os.path.exists(newname_path):
 os.mkdir(newname_path)
 os.replace('poster.jpg',os.path.join(newname_path, 'poster.jpg'))

 
 ffmpeg360_cmd = f'ffmpeg -hide_banner -y -i {FILENAME_PATH} -sn -c:a aac -ac 2 -c:v libx264 -crf 23 -preset fast -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod -maxrate 512k -bufsize 768k -b:a 128k -pix_fmt yuv420p -hls_segment_filename 365RL6TJ%03d.ts 360p.m3u8'
 os.system(ffmpeg360_cmd)
 # return
 
 
 ts_files = glob.glob('*.ts')
 for ts_file in ts_files:
 os.replace(ts_file, os.path.join(newname_path,ts_file))
 master_text = '''#EXTM3U
#EXT-X-STREAM-INF:BANDWIDTH=840000,RESOLUTION=640x360
360p.m3u8
 '''
 with open('master.m3u8', 'w') as f:
 f.write(master_text)
 m3u8_files = glob.glob('*.m3u8')
 for m3u8_file in m3u8_files:
 os.replace(m3u8_file, os.path.join(newname_path, m3u8_file))


def encode_720(filename):
 FILENAME_PATH = filename
 newname = filename.split('.')[0]
 newname_path = os.path.join(VIDEO_PATH,newname)
 poster_cmd = f'ffmpeg -y -ss 00:00:10 -i {FILENAME_PATH} -vframes 1 -q:v 2 poster.jpg'
 os.system(poster_cmd)

 if not os.path.exists(newname_path):
 os.mkdir(newname_path)

 os.replace('poster.jpg',os.path.join(newname_path, 'poster.jpg'))

 ffmpeg720_cmd = f'ffmpeg -hide_banner -y -i {FILENAME_PATH} -sn -c:a aac -ac 2 -c:v libx264 -crf 23 -preset fast -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod -maxrate 2048k -bufsize 3072k -b:a 160k -pix_fmt yuv420p -hls_segment_filename 7269TKL0%03d.ts 720p.m3u8'
 os.system(ffmpeg720_cmd)

 # os.remove(FILENAME_PATH)

 ts_files = glob.glob('*.ts')
 for ts_file in ts_files:
 os.replace(ts_file, os.path.join(newname_path,ts_file))
 
 m3u8_text = '''#EXTM3U
#EXT-X-STREAM-INF:BANDWIDTH=2800000,RESOLUTION=1280x720
720p.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=840000,RESOLUTION=640x360
360p.m3u8 
 '''

 with open('master.m3u8','w') as f:
 f.write(m3u8_text)
 
 m3u8_files = glob.glob('*.m3u8')
 for m3u8_file in m3u8_files:
 os.replace(m3u8_file, os.path.join(newname_path,m3u8_file)) 


def encode_1080(filename):
 FILENAME_PATH = filename
 newname = filename.split('.')[0]
 newname_path = os.path.join(VIDEO_PATH, newname)
 poster_cmd = f'ffmpeg -y -ss 00:00:10 -i {FILENAME_PATH} -vframes 1 -q:v 2 poster.jpg'
 os.system(poster_cmd)

 if not os.path.exists(newname_path):
 os.mkdir(newname_path)

 os.replace('poster.jpg', os.path.join(newname_path, 'poster.jpg'))

 ffmpeg1080_cmd = f'ffmpeg -hide_banner -y -i {FILENAME_PATH} -sn -c:a aac -ac 2 -c:v libx264 -crf 23 -preset fast -sc_threshold 0 -g 48 -keyint_min 48 -hls_time 4 -hls_playlist_type vod -maxrate 4000k -bufsize 6000k -b:a 192k -pix_fmt yuv420p -hls_segment_filename 108YUT8T%03d.ts 1080p.m3u8'
 os.system(ffmpeg1080_cmd)

 # os.remove(FILENAME_PATH)

 ts_files = glob.glob('*.ts')
 for ts_file in ts_files:
 os.replace(ts_file, os.path.join(newname_path, ts_file))

 m3u8_text = '''#EXTM3U
#EXT-X-STREAM-INF:BANDWIDTH=4000000,RESOLUTION=1920x1080
1080p.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=2800000,RESOLUTION=1280x720
720p.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=840000,RESOLUTION=640x360
360p.m3u8
'''

 with open('master.m3u8', 'w') as f:
 f.write(m3u8_text)

 m3u8_files = glob.glob('*.m3u8')
 for m3u8_file in m3u8_files:
 os.replace(m3u8_file, os.path.join(newname_path, m3u8_file))



def vod(filename, resolution):
 os.replace(filename,filename.replace(' ','_'))
 filename = filename.replace(' ','_')
 FILENAME_PATH = filename
 width_cmd = f'ffprobe -v error -select_streams v:0 -show_entries stream=width -of default=nw=1:nk=1 {FILENAME_PATH}'
 height_cmd= f'ffprobe -v error -select_streams v:0 -show_entries stream=height -of default=nw=1:nk=1 {FILENAME_PATH}'

 width_result = subprocess.run(width_cmd.split(), stdout=subprocess.PIPE)
 width = width_result.stdout.strip().decode('utf-8')

 height_result = subprocess.run(height_cmd.split(), stdout=subprocess.PIPE)
 height = height_result.stdout.strip().decode('utf-8')

 if not os.path.exists(VIDEO_PATH):
 os.mkdir(VIDEO_PATH)

 if resolution == 360: 
 write_log(f'Encoding {filename} in 360p') 
 encode_360(filename)

 if resolution == 720 :
 if int(height) >=400 :
 if int(height) <= 700:
 query = f"""UPDATE videos SET encoding_status = 'encoding480' WHERE file_uid LIKE '%{filename.replace(".mkv","")}'"""
 executedb(query)
 write_log(f'Encoding {filename} in 480p')
 encode_480(filename) 
 query = f"""UPDATE videos SET encoding_status = 'done480' WHERE file_uid LIKE '%{filename.replace(".mkv","")}'"""
 executedb(query)
 query = f"""UPDATE videos SET quality = 2 WHERE file_uid LIKE '%{filename.replace(".mkv","")}'"""
 executedb(query)
 else:
 if int(height) >= 800:
 query = f"""UPDATE videos SET encoding_status = 'encoding720' WHERE file_uid LIKE '%{filename.replace(".mkv","")}'"""
 executedb(query)
 write_log(f'Encoding {filename} in 720p')
 encode_720(filename) 
 query = f"""UPDATE videos SET encoding_status = 'done720' WHERE file_uid LIKE '%{filename.replace(".mkv","")}'"""
 executedb(query)
 query = f"""UPDATE videos SET quality = 3 WHERE file_uid LIKE '%{filename.replace(".mkv","")}'"""
 executedb(query)
 query = f"""UPDATE videos SET encoding_status = 'encoding1080' WHERE file_uid LIKE '%{filename.replace(".mkv","")}'"""
 executedb(query)
 write_log(f'Encoding {filename} in 720p')
 encode_1080(filename) 
 query = f"""UPDATE videos SET encoding_status = 'done1080' WHERE file_uid LIKE '%{filename.replace(".mkv","")}'"""
 executedb(query)
 query = f"""UPDATE videos SET quality = 4 WHERE file_uid LIKE '%{filename.replace(".mkv","")}'"""
 executedb(query)
 else:
 query = f"""UPDATE videos SET encoding_status = 'encoding720' WHERE file_uid LIKE '%{filename.replace(".mkv","")}'"""
 executedb(query)
 write_log(f'Encoding {filename} in 720p')
 encode_720(filename) 
 query = f"""UPDATE videos SET encoding_status = 'done720' WHERE file_uid LIKE '%{filename.replace(".mkv","")}'"""
 executedb(query)
 query = f"""UPDATE videos SET quality = 3 WHERE file_uid LIKE '%{filename.replace(".mkv","")}'"""
 executedb(query)
 
 
 
 os.remove(filename)


def move_to_rclone():
 if not os.path.exists(RCLONE_PATH):
 os.mkdir(RCLONE_PATH)
 folders = os.listdir(VIDEO_PATH)
 if len(folders) > 0:
 for folder in folders:
 folder_in_rclone = os.path.join(RCLONE_PATH, folder)
 if not os.path.exists(folder_in_rclone):
 os.mkdir(folder_in_rclone)
 files = os.listdir(os.path.join(VIDEO_PATH, folder))
 for file in files:
 os.replace(os.path.join(VIDEO_PATH, folder, file), os.path.join(folder_in_rclone, file))
 os.system(MOVE_CMD.format(folder_in_rclone))
 if len(os.listdir(os.path.join(VIDEO_PATH, folder))) == 0:
 os.rmdir(os.path.join(VIDEO_PATH, folder))
 # rclone_folders = os.listdir(RCLONE_PATH)
 # if len(rclone_folders)> 0:
 # for rclone_folder in rclone_folders:
 # os.system(MOVE_CMD.format(rclone_folder))

def get_length(input_video):
 result = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', input_video], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
 try:
 output = float(result.stdout)
 except:
 output = 0
 return output

def move_to_error(file):
 if not os.path.exists(ERROR_PATH):
 os.mkdir(ERROR_PATH)
 print(f'[red][-][/red] Moving {file} to the error folder')
 os.replace(file, os.path.join(ERROR_PATH, file.split('/')[-1]))

def main():
 db = sql.connect(
 host=MYSQL_HOST,
 user=MYSQL_USER,
 password=MYSQL_PASSWORD,
 database=MYSQL_DB
 )

 def get_video_data(file_uid):
 cursor = db.cursor()
 query = f"""SELECT id, post_title, file_uid, group_id FROM videos WHERE file_uid LIKE %s"""
 cursor.execute(query, (f'%{file_uid}%',))
 data = cursor.fetchone()
 return data if data else None
 
 if os.path.exists(UPLOAD_PATH):
 upload_files = os.listdir(UPLOAD_PATH)
 upload_files = [os.path.join(UPLOAD_PATH, x) for x in upload_files]
 upload_files.sort(key=lambda x: os.path.getmtime(x))
 else:
 upload_files = []

 if len(upload_files) > 0:
 for upload_file in upload_files:
 if get_length(upload_file) < VIDEO_LENGTH:
 move_to_error(upload_file)
 write_log(f'Length of {upload_file} is less than 60 sec. Moving to error folder')
 continue
 try:
 os.replace(upload_file, upload_file.split('/')[-1])
 query = f"""UPDATE videos SET encoding_status = 'uploaded' WHERE file_uid LIKE '%{upload_file.replace(".mkv","").replace(".mp4","")}'"""
 executedb(query)
 except:
 print(e)
 continue
 change_all_videos_extension()

 mkv_files = glob.glob('*.mkv')
 if len(mkv_files) > 0:
 for mkv_file in mkv_files:
 try:
 query = f"""UPDATE videos SET encoding_status = 'encoding360' WHERE file_uid LIKE '%{mkv_file.replace(".mkv","")}'"""
 executedb(query)
 vod(mkv_file, 360)
 query = f"""UPDATE videos SET encoding_status = 'done360' WHERE file_uid LIKE '%{mkv_file.replace(".mkv","")}'"""
 executedb(query)
 query = f"""UPDATE videos SET quality = 1 WHERE file_uid LIKE '%{mkv_file.replace(".mkv","")}'"""
 executedb(query)

 
 vod(mkv_file, 720)
 
 except Exception as e:
 query = f"""UPDATE videos SET encoding_status = 'error' WHERE file_uid LIKE '%{mkv_file.replace(".mkv","")}'"""
 executedb(query)
 video_data = get_video_data(
 mkv_file.replace(".mkv", ""))
 if video_data:
 cursor = db.cursor()
 video_id, video_title, video_uid, group_id = video_data
 error_log_query = f"""INSERT INTO error_logs (video_id, video_title, video_uid, group_id, log, created_at, updated_at) 
 VALUES (%s, %s, %s, %s, %s, NOW(), NOW())"""
 cursor.execute(
 error_log_query, (video_id, video_title, video_uid, group_id, str(e)))
 db.commit()
 write_log(f'Error: {e}')
 move_to_error(mkv_file)
 move_to_rclone()
 else:
 print(f'[{time_now()}] No new video found on upload folder')

 if os.path.exists(UPLOAD_PATH2):
 upload_files2 = os.listdir(UPLOAD_PATH2)
 upload_files2 = [os.path.join(UPLOAD_PATH2, x) for x in upload_files2]
 upload_files2.sort(key=lambda x: os.path.getmtime(x))
 else:
 upload_files2 = []

 if len(upload_files2) > 0:
 for upload_file2 in upload_files2:
 if get_length(upload_file2) < VIDEO_LENGTH:
 move_to_error(upload_file2)
 continue
 if len(os.listdir(UPLOAD_PATH)) != 0:
 main()
 try:
 os.replace(upload_file2, upload_file2.split('/')[-1])
 query = f"""UPDATE videos SET encoding_status = 'uploaded' WHERE file_uid LIKE '%{upload_file2.replace(".mkv","").replace(".mp4","")}'"""
 executedb(query)
 except:
 continue

 change_all_videos_extension()

 mkv_files = glob.glob('*.mkv')
 if len(mkv_files) > 0:
 for mkv_file in mkv_files:
 try:
 query = f"""UPDATE videos SET encoding_status = 'encoding360' WHERE file_uid LIKE '%{mkv_file.replace(".mkv","")}'"""
 executedb(query)
 vod(mkv_file, 360)
 query = f"""UPDATE videos SET encoding_status = 'done360' WHERE file_uid LIKE '%{mkv_file.replace(".mkv","")}'"""
 executedb(query)
 query = f"""UPDATE videos SET quality = 1 WHERE file_uid LIKE '%{mkv_file.replace(".mkv","")}'"""
 executedb(query)


 vod(mkv_file, 720)

 except Exception as e:
 query = f"""UPDATE videos SET encoding_status = 'error' WHERE file_uid LIKE '%{mkv_file.replace(".mkv","")}'"""
 executedb(query)
 video_data = get_video_data(
 mkv_file.replace(".mkv", ""))
 if video_data:
 cursor = db.cursor()
 video_id, video_title, video_uid, group_id = video_data
 error_log_query = f"""INSERT INTO error_logs (video_id, video_title, video_uid, group_id, log, created_at, updated_at) 
 VALUES (%s, %s, %s, %s, %s, NOW(), NOW())"""
 cursor.execute(
 error_log_query, (video_id, video_title, video_uid, group_id, str(e)))
 db.commit()
 write_log(f'Error: {e}')
 move_to_error(mkv_file)
 move_to_rclone()
 else:
 print(f'[{time_now()}] No new video found on upload2 folder.')
 move_to_rclone()
 db.close()

if __name__=="__main__":
 while True:
 try:
 main()
 except Exception as e:
 print(f'Error: {e}')
 for i in range(WAIT):
 print(f'[green][+][/green] Waiting for {WAIT-i} seconds ', end="\r")
 time.sleep(1)





looking for suggestion to improve encoding speed