-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGUI_pyqt6_WINFF.py
More file actions
592 lines (535 loc) · 26.7 KB
/
GUI_pyqt6_WINFF.py
File metadata and controls
592 lines (535 loc) · 26.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# GUI_pyqt6_WINFF.py
# Conversão da interface Tkinter para PyQt6
import os
import sys
import subprocess
import json
import platform
import threading
import webbrowser
import tempfile
import zipfile
import shlex
import tarfile
import ssl
from io import BytesIO
from functools import partial
from utils_safe_extract import safe_tar_extract, safe_zip_extract
from PyQt6 import QtWidgets, QtCore
from PyQt6.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QTextEdit, QComboBox, QFileDialog, QCheckBox, QHBoxLayout, QVBoxLayout, QProgressDialog
class FFmpegGuiPyQt6(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Conversor de Vídeo Avançado (PyQt6)')
self.resize(900, 700)
self._proc = None # QProcess for non-blocking conversion
self._build_ui()
def _build_ui(self):
layout = QVBoxLayout()
# top buttons
top_layout = QHBoxLayout()
about_btn = QPushButton('About')
about_btn.clicked.connect(self.show_about)
info_btn = QPushButton('Informações do video')
info_btn.clicked.connect(self.show_video_info)
dl_btn = QPushButton('Baixar FFmpeg')
dl_btn.clicked.connect(self.download_ffmpeg_and_maybe_install)
winget_btn = QPushButton('Instalar FFmpeg (winget)')
winget_btn.clicked.connect(self.install_ffmpeg_via_winget)
top_layout.addWidget(about_btn)
top_layout.addStretch()
top_layout.addWidget(info_btn)
top_layout.addWidget(dl_btn)
top_layout.addWidget(winget_btn)
layout.addLayout(top_layout)
# input file
h = QHBoxLayout()
h.addWidget(QLabel('Selecione o Arquivo de Vídeo:'))
self.input_edit = QLineEdit()
self.input_edit.textChanged.connect(self.update_command_display)
h.addWidget(self.input_edit)
browse_btn = QPushButton('Procurar')
browse_btn.clicked.connect(self.select_file)
h.addWidget(browse_btn)
layout.addLayout(h)
# output dir
h = QHBoxLayout()
h.addWidget(QLabel('Selecione o Diretório de Saída:'))
self.output_edit = QLineEdit()
self.output_edit.textChanged.connect(self.update_command_display)
h.addWidget(self.output_edit)
out_browse = QPushButton('Procurar')
out_browse.clicked.connect(self.select_output_directory)
h.addWidget(out_browse)
layout.addLayout(h)
# same dir checkbox / overwrite
h = QHBoxLayout()
self.same_dir_chk = QCheckBox('Utilizar o mesmo diretório do arquivo de entrada')
self.same_dir_chk.stateChanged.connect(self.toggle_output_dir)
h.addWidget(self.same_dir_chk)
self.overwrite_chk = QCheckBox('Sobrescrever arquivos existentes')
self.overwrite_chk.setChecked(True)
h.addWidget(self.overwrite_chk)
layout.addLayout(h)
# format + codecs
grid = QtWidgets.QGridLayout()
grid.addWidget(QLabel('Formato de Saída:'), 0, 0)
self.format_combo = QComboBox(); self.format_combo.addItems(['mp4','avi','mkv','flv','mov','mp3','wmv','asf'])
self.format_combo.currentIndexChanged.connect(self.update_command_display)
grid.addWidget(self.format_combo, 0, 1)
grid.addWidget(QLabel('Codec de Vídeo:'), 1, 0)
self.video_codec_combo = QComboBox(); self.video_codec_combo.addItems(['auto','libx264','libx265','mpeg4','wmv2'])
self.video_codec_combo.currentIndexChanged.connect(self.update_command_display)
grid.addWidget(self.video_codec_combo, 1, 1)
grid.addWidget(QLabel('Codec de Áudio:'), 2, 0)
self.audio_codec_combo = QComboBox(); self.audio_codec_combo.addItems(['auto','aac','mp3','ac3','wmav2'])
self.audio_codec_combo.currentIndexChanged.connect(self.update_command_display)
grid.addWidget(self.audio_codec_combo, 2, 1)
grid.addWidget(QLabel('Resolução:'), 3, 0)
self.resolution_combo = QComboBox(); self.resolution_combo.addItems(['original','1920x1080','1280x720','640x480','320x240'])
self.resolution_combo.currentIndexChanged.connect(self.update_command_display)
grid.addWidget(self.resolution_combo, 3, 1)
grid.addWidget(QLabel('Bitrate de Vídeo:'), 4, 0)
self.video_bitrate = QLineEdit(); self.video_bitrate.textChanged.connect(self.update_command_display)
grid.addWidget(self.video_bitrate, 4, 1)
grid.addWidget(QLabel('Bitrate de Áudio:'), 5, 0)
self.audio_bitrate = QLineEdit(); self.audio_bitrate.textChanged.connect(self.update_command_display)
grid.addWidget(self.audio_bitrate, 5, 1)
grid.addWidget(QLabel('FPS (frame rate):'), 6, 0)
self.frame_rate = QLineEdit(); self.frame_rate.textChanged.connect(self.update_command_display)
grid.addWidget(self.frame_rate, 6, 1)
grid.addWidget(QLabel('Audio sample rate:'), 7, 0)
self.audio_sample_rate = QLineEdit(); self.audio_sample_rate.textChanged.connect(self.update_command_display)
grid.addWidget(self.audio_sample_rate, 7, 1)
grid.addWidget(QLabel('Audio channels:'), 8, 0)
self.audio_channels = QComboBox(); self.audio_channels.addItems(['1','2'])
self.audio_channels.currentIndexChanged.connect(self.update_command_display)
grid.addWidget(self.audio_channels, 8, 1)
# no-audio checkbox positioned near audio controls
no_audio_row = QHBoxLayout()
self.no_audio_chk = QCheckBox('Arquivo sem áudio (-an)')
self.no_audio_chk.stateChanged.connect(self.on_no_audio_change)
no_audio_row.addWidget(self.no_audio_chk)
grid.addLayout(no_audio_row, 9, 0, 1, 2)
layout.addLayout(grid)
# ffmpeg path
h = QHBoxLayout()
h.addWidget(QLabel('Caminho do Executável FFmpeg:'))
self.ffmpeg_path = QLineEdit()
self.ffmpeg_path.setText('ffmpeg')
self.ffmpeg_path.textChanged.connect(self.update_command_display)
h.addWidget(self.ffmpeg_path)
ff_browse = QPushButton('Procurar')
ff_browse.clicked.connect(self.select_ffmpeg)
h.addWidget(ff_browse)
layout.addLayout(h)
# command display
layout.addWidget(QLabel('Comando FFmpeg:'))
self.command_display = QTextEdit(); self.command_display.setReadOnly(True)
# cap log length to avoid unbounded growth (drop oldest lines automatically)
try:
self.command_display.document().setMaximumBlockCount(2000)
except Exception:
pass
layout.addWidget(self.command_display)
# buttons
btn_layout = QHBoxLayout()
default_btn = QPushButton('Opções Padrão'); default_btn.clicked.connect(self.set_default_options)
btn_layout.addWidget(default_btn)
load_btn = QPushButton('Carregar Configuração'); load_btn.clicked.connect(self.load_config)
btn_layout.addWidget(load_btn)
save_btn = QPushButton('Salvar Configuração'); save_btn.clicked.connect(self.save_config)
btn_layout.addWidget(save_btn)
self.convert_btn = QPushButton('Converter'); self.convert_btn.clicked.connect(self.convert_video)
btn_layout.addWidget(self.convert_btn)
self.cancel_btn = QPushButton('Cancelar'); self.cancel_btn.setEnabled(False); self.cancel_btn.clicked.connect(self.cancel_convert)
btn_layout.addWidget(self.cancel_btn)
layout.addLayout(btn_layout)
self.setLayout(layout)
self.set_default_options()
def select_file(self):
file, _ = QFileDialog.getOpenFileName(self, 'Selecione o arquivo de vídeo')
if file:
self.input_edit.setText(file)
def select_output_directory(self):
d = QFileDialog.getExistingDirectory(self, 'Selecione o diretório de saída')
if d:
self.output_edit.setText(d)
def toggle_output_dir(self):
if self.same_dir_chk.isChecked():
self.output_edit.setDisabled(True)
else:
self.output_edit.setDisabled(False)
self.update_command_display()
def select_ffmpeg(self):
file, _ = QFileDialog.getOpenFileName(self, 'Selecione o FFmpeg')
if file:
self.ffmpeg_path.setText(file)
def set_default_options(self):
self.format_combo.setCurrentText('wmv')
self.resolution_combo.setCurrentText('original')
self.video_codec_combo.setCurrentText('wmv2')
self.audio_codec_combo.setCurrentText('wmav2')
self.video_bitrate.setText('204800')
self.audio_bitrate.setText('65536')
self.frame_rate.setText('20')
self.audio_sample_rate.setText('22050')
self.audio_channels.setCurrentText('1')
self.output_edit.clear()
self.ffmpeg_path.setText('ffmpeg')
self.same_dir_chk.setChecked(False)
self.overwrite_chk.setChecked(True)
self.no_audio_chk.setChecked(False)
self.update_command_display()
def load_config(self):
file, _ = QFileDialog.getOpenFileName(self, 'Carregar Configuração', filter='INI Files (*.ini)')
if not file:
return
import configparser
cp = configparser.ConfigParser(); cp.read(file)
d = cp['DEFAULT'] if 'DEFAULT' in cp else {}
self.ffmpeg_path.setText(d.get('ffmpeg_path','ffmpeg'))
self.format_combo.setCurrentText(d.get('default_format','wmv'))
self.output_edit.setText(d.get('default_output_dir',''))
self.video_codec_combo.setCurrentText(d.get('default_video_codec','wmv2'))
self.audio_codec_combo.setCurrentText(d.get('default_audio_codec','wmav2'))
self.resolution_combo.setCurrentText(d.get('default_resolution','original'))
self.video_bitrate.setText(d.get('video_bitrate','204800'))
self.audio_bitrate.setText(d.get('audio_bitrate','65536'))
self.frame_rate.setText(d.get('frame_rate','20'))
self.audio_sample_rate.setText(d.get('audio_sample_rate','22050'))
self.audio_channels.setCurrentText(d.get('audio_channels','1'))
self.same_dir_chk.setChecked(d.get('use_same_directory','False')=='True')
self.overwrite_chk.setChecked(d.get('overwrite_existing','True')=='True')
self.no_audio_chk.setChecked(d.get('no_audio','False')=='True')
self.on_no_audio_change() # apply UI disable state
self.update_command_display()
def save_config(self):
file, _ = QFileDialog.getSaveFileName(self, 'Salvar Configuração', filter='INI Files (*.ini)')
if not file:
return
import configparser
cp = configparser.ConfigParser()
cp['DEFAULT'] = {
'ffmpeg_path': self.ffmpeg_path.text(),
'default_format': self.format_combo.currentText(),
'default_output_dir': self.output_edit.text(),
'default_video_codec': self.video_codec_combo.currentText(),
'default_audio_codec': self.audio_codec_combo.currentText(),
'default_resolution': self.resolution_combo.currentText(),
'video_bitrate': self.video_bitrate.text(),
'audio_bitrate': self.audio_bitrate.text(),
'frame_rate': self.frame_rate.text(),
'audio_sample_rate': self.audio_sample_rate.text(),
'audio_channels': self.audio_channels.currentText(),
'use_same_directory': str(self.same_dir_chk.isChecked()),
'overwrite_existing': str(self.overwrite_chk.isChecked()),
'no_audio': str(self.no_audio_chk.isChecked()),
}
with open(file, 'w') as f:
cp.write(f)
def build_command_list(self):
inp = self.input_edit.text()
fmt = self.format_combo.currentText()
video_bitrate = self.video_bitrate.text()
audio_bitrate = self.audio_bitrate.text()
resolution = self.resolution_combo.currentText()
video_codec = self.video_codec_combo.currentText()
audio_codec = self.audio_codec_combo.currentText()
frame_rate = self.frame_rate.text()
audio_sample_rate = self.audio_sample_rate.text()
audio_channels = self.audio_channels.currentText()
ffmpeg = self.ffmpeg_path.text()
if self.same_dir_chk.isChecked():
out_dir = os.path.dirname(inp)
else:
out_dir = self.output_edit.text()
output_file = os.path.join(out_dir, os.path.splitext(os.path.basename(inp))[0] + '.' + fmt) if inp else ''
if not inp:
return []
args = [ffmpeg, '-y', '-i', inp]
if video_bitrate:
args += ['-b:v', video_bitrate]
if self.no_audio_chk.isChecked():
args += ['-an']
elif audio_bitrate:
args += ['-b:a', audio_bitrate]
if resolution != 'original':
args += ['-s', resolution]
if frame_rate:
args += ['-r', frame_rate]
if not self.no_audio_chk.isChecked() and audio_sample_rate:
args += ['-ar', audio_sample_rate]
if not self.no_audio_chk.isChecked() and audio_channels:
args += ['-ac', audio_channels]
if video_codec != 'auto':
args += ['-vcodec', video_codec]
if not self.no_audio_chk.isChecked() and audio_codec != 'auto':
args += ['-acodec', audio_codec]
if output_file:
args += [output_file]
return args
def update_command_display(self):
args = self.build_command_list()
if not args:
self.command_display.setPlainText('')
return
self.command_display.setPlainText(' '.join(shlex.quote(a) for a in args))
def convert_video(self):
if self._proc is not None:
QtWidgets.QMessageBox.warning(self, 'Em execução', 'Uma conversão já está em andamento.')
return
args = self.build_command_list()
if not args:
QtWidgets.QMessageBox.warning(self, 'Erro', 'Preencha os campos necessários')
return
# Use QProcess to avoid freezing UI
self._proc = QtCore.QProcess(self)
self._proc.setProgram(args[0])
self._proc.setArguments(args[1:])
self._proc.setProcessChannelMode(QtCore.QProcess.ProcessChannelMode.MergedChannels)
self._proc.readyReadStandardOutput.connect(self._on_proc_output)
self._proc.finished.connect(self._on_proc_finished)
self._proc.errorOccurred.connect(self._on_proc_error)
self.convert_btn.setEnabled(False)
self.cancel_btn.setEnabled(True)
self._append_log('Iniciando conversão...')
self._proc.start()
def cancel_convert(self):
if self._proc is not None:
self._append_log('Cancelando conversão...')
self._proc.kill()
def _on_proc_output(self):
if self._proc is None:
return
data = self._proc.readAllStandardOutput()
try:
text = bytes(data).decode('utf-8', errors='ignore')
except Exception:
text = str(data)
self._append_log(text)
def _finalize_proc(self):
self.convert_btn.setEnabled(True)
self.cancel_btn.setEnabled(False)
self._proc = None
def _on_proc_finished(self, code, status):
ok = (code == 0)
# Show dialog first, then finalize to avoid brief window where Convert is re-enabled during dialog
if ok:
QtWidgets.QMessageBox.information(self, 'Sucesso', 'Vídeo convertido com sucesso!')
else:
QtWidgets.QMessageBox.critical(self, 'Erro', f'Falha ao converter vídeo (código {code}).')
self._finalize_proc()
def _on_proc_error(self, err):
QtWidgets.QMessageBox.critical(self, 'Erro', f'Erro de processo: {err}')
self._finalize_proc()
def _append_log(self, msg):
# Efficient append without rewriting whole buffer
self.command_display.append(msg)
def show_about(self):
QtWidgets.QMessageBox.information(self, 'About', 'Mauricio Menon (+AI)\nhttps://github.com/mauriciomenon\nPyQt6 version of the GUI')
def show_video_info(self):
inp = self.input_edit.text()
if not inp:
QtWidgets.QMessageBox.warning(self, 'Atenção', 'Nenhum arquivo selecionado')
return
# Resolve ffprobe path: if ffmpeg_path is a directory or a full path, try alongside; otherwise fall back to PATH
configured = self.ffmpeg_path.text().strip()
ffprobe_name = 'ffprobe.exe' if os.name == 'nt' else 'ffprobe'
candidate = None
if configured and os.path.isabs(configured):
base = configured
if os.path.isdir(base):
candidate = os.path.join(base, ffprobe_name)
else:
candidate = os.path.join(os.path.dirname(base), ffprobe_name)
if not candidate or not os.path.exists(candidate):
candidate = ffprobe_name # rely on PATH
ffprobe = candidate
# Run ffprobe non-blocking using QProcess
try:
self._info_proc = QtCore.QProcess(self)
self._info_proc.setProgram(ffprobe)
self._info_proc.setArguments(['-v', 'quiet', '-print_format', 'json', '-show_streams', '-show_format', inp])
self._info_proc.setProcessChannelMode(QtCore.QProcess.ProcessChannelMode.MergedChannels)
self._info_proc.finished.connect(self._on_info_finished)
self._info_proc.errorOccurred.connect(lambda err: QtWidgets.QMessageBox.critical(self, 'Erro', f'Erro ao executar ffprobe: {err}'))
self._info_proc.start()
except FileNotFoundError:
QtWidgets.QMessageBox.critical(self, 'Erro', 'ffprobe não encontrado (verifique PATH ou caminho configurado).')
except Exception as e:
QtWidgets.QMessageBox.critical(self, 'Erro', f'Falha ao iniciar ffprobe: {e}')
def _on_info_finished(self, code, status):
try:
out = bytes(self._info_proc.readAllStandardOutput()).decode('utf-8', errors='ignore') if hasattr(self, '_info_proc') else ''
if code != 0:
QtWidgets.QMessageBox.critical(self, 'Erro', f'ffprobe falhou (código {code}).')
return
data = json.loads(out or '{}')
info_text = json.dumps(data, indent=2, ensure_ascii=False)
dlg = QtWidgets.QDialog(self)
dlg.setWindowTitle('Informações detalhadas do vídeo')
v = QVBoxLayout()
te = QTextEdit(); te.setPlainText(info_text); te.setReadOnly(True)
v.addWidget(te)
b = QPushButton('Fechar'); b.clicked.connect(dlg.accept)
v.addWidget(b)
dlg.setLayout(v)
dlg.exec()
finally:
try:
self._info_proc.deleteLater()
except Exception:
pass
self._info_proc = None
def on_no_audio_change(self):
disabled = self.no_audio_chk.isChecked()
self.audio_codec_combo.setDisabled(disabled)
self.audio_bitrate.setDisabled(disabled)
self.audio_sample_rate.setDisabled(disabled)
self.audio_channels.setDisabled(disabled)
self.update_command_display()
# -------- FFmpeg download helpers --------
def _http_get(self, url: str, timeout: int = 60) -> bytes:
"""Download URL returning raw bytes. Tries requests first, then urllib as fallback."""
try:
import requests # type: ignore
resp = requests.get(url, timeout=timeout, verify=True)
resp.raise_for_status()
return resp.content
except Exception:
# Fallback to urllib
import urllib.request
ctx = ssl.create_default_context()
ctx.check_hostname = True
ctx.verify_mode = ssl.CERT_REQUIRED
with urllib.request.urlopen(url, timeout=timeout, context=ctx) as resp: # nosec B310
if resp.status != 200:
raise RuntimeError(f"HTTP {resp.status}")
return resp.read()
def _get_latest_ffmpeg_windows_zip_url(self):
# Try GitHub API (BtbN/FFmpeg-Builds) for latest win64 gpl zip; fallback to a known asset name
try:
import urllib.request, json as _json
api = 'https://api.github.com/repos/BtbN/FFmpeg-Builds/releases/latest'
req = urllib.request.Request(api, headers={'User-Agent': 'ffmpeg-gui'})
with urllib.request.urlopen(req, timeout=10) as resp: # nosec B310
if resp.status == 200:
data = _json.loads(resp.read().decode('utf-8'))
for asset in data.get('assets', []):
name = asset.get('name','')
if name.endswith('win64-gpl.zip'):
return asset.get('browser_download_url')
except Exception:
pass
# Fallback to latest/download with a common asset name
return 'https://github.com/BtbN/FFmpeg-Builds/releases/latest/download/ffmpeg-master-latest-win64-gpl.zip'
def _extract_ffmpeg_zip(self, zip_bytes):
# Extract to ./bin and return inferred ffmpeg path
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'bin'))
os.makedirs(base_dir, exist_ok=True)
with zipfile.ZipFile(BytesIO(zip_bytes)) as zf:
safe_zip_extract(zf, base_dir)
# try to find ffmpeg(.exe)
ffmpeg_path = None
for root, dirs, files in os.walk(base_dir):
for f in files:
if f.lower() == ('ffmpeg.exe' if os.name == 'nt' else 'ffmpeg'):
ffmpeg_path = os.path.join(root, f)
break
if ffmpeg_path:
break
return ffmpeg_path
def download_ffmpeg_and_maybe_install(self):
# Provide non-blocking download with a progress dialog and platform handling
prog = QProgressDialog('Baixando FFmpeg...', 'Cancelar', 0, 0, self)
prog.setWindowModality(QtCore.Qt.WindowModality.ApplicationModal)
prog.setAutoClose(True)
prog.show()
def worker():
try:
sysname = platform.system()
if sysname == 'Windows':
url = self._get_latest_ffmpeg_windows_zip_url()
content = self._http_get(url, timeout=60)
ff = self._extract_ffmpeg_zip(content)
if ff:
QtCore.QTimer.singleShot(0, lambda: self.ffmpeg_path.setText(ff))
QtCore.QTimer.singleShot(0, lambda: self.show_info_msg('FFmpeg baixado e extraído com sucesso.'))
else:
QtCore.QTimer.singleShot(0, lambda: self.show_error_msg('Não foi possível localizar o executável ffmpeg após extração.'))
else:
# Linux/macOS: tentar um build estático conhecido (johnvansickle para Linux; Brew instruções no macOS)
if sysname == 'Linux':
arch = platform.machine().lower()
if arch in ('aarch64', 'arm64'):
url = 'https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-arm64-static.tar.xz'
else:
url = 'https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-amd64-static.tar.xz'
content = self._http_get(url, timeout=60)
# extrair para ./bin e apontar para bin/ffmpeg
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'bin'))
os.makedirs(base_dir, exist_ok=True)
with tarfile.open(fileobj=BytesIO(content), mode='r:xz') as tf:
safe_tar_extract(tf, base_dir)
# procurar binário
ffmpeg_path = None
for root, dirs, files in os.walk(base_dir):
for f in files:
if f == 'ffmpeg':
ffmpeg_path = os.path.join(root, f)
break
if ffmpeg_path:
break
if ffmpeg_path:
QtCore.QTimer.singleShot(0, lambda: self.ffmpeg_path.setText(ffmpeg_path))
QtCore.QTimer.singleShot(0, lambda: self.show_info_msg('FFmpeg baixado e pronto (build estático).'))
else:
QtCore.QTimer.singleShot(0, lambda: self.show_error_msg('Não foi possível localizar o ffmpeg extraído.'))
elif sysname == 'Darwin':
QtCore.QTimer.singleShot(0, lambda: webbrowser.open('https://formulae.brew.sh/formula/ffmpeg'))
QtCore.QTimer.singleShot(0, lambda: self.show_info_msg('No macOS, instale via Homebrew: brew install ffmpeg'))
except Exception as e:
QtCore.QTimer.singleShot(0, lambda: self.show_error_msg(f'Falha no download: {e}'))
finally:
QtCore.QTimer.singleShot(0, prog.cancel)
t = threading.Thread(target=worker, daemon=True)
t.start()
def install_ffmpeg_via_winget(self):
if platform.system() != 'Windows':
self.show_error_msg('Instalação via winget só está disponível no Windows.')
return
def worker():
try:
# Try common ids: Gyan.FFmpeg, then FFmpeg.FFmpeg
cmds = [
['winget', 'install', '-e', '--id', 'Gyan.FFmpeg'],
['winget', 'install', '-e', '--id', 'FFmpeg.FFmpeg']
]
ok = False
for c in cmds:
p = subprocess.run(c, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if p.returncode == 0:
ok = True
break
if ok:
# After install, assume ffmpeg is on PATH
QtCore.QTimer.singleShot(0, lambda: self.ffmpeg_path.setText('ffmpeg'))
QtCore.QTimer.singleShot(0, lambda: self.show_info_msg('FFmpeg instalado via winget.'))
else:
QtCore.QTimer.singleShot(0, lambda: self.show_error_msg('Falha ao instalar via winget.'))
except Exception as e:
QtCore.QTimer.singleShot(0, lambda: self.show_error_msg(f'Erro winget: {e}'))
threading.Thread(target=worker, daemon=True).start()
@QtCore.pyqtSlot(str)
def show_info_msg(self, msg):
QtWidgets.QMessageBox.information(self, 'Info', msg)
@QtCore.pyqtSlot(str)
def show_error_msg(self, msg):
QtWidgets.QMessageBox.critical(self, 'Erro', msg)
# ---- security helpers moved to utils_safe_extract ----
if __name__ == '__main__':
app = QApplication(sys.argv)
w = FFmpegGuiPyQt6()
w.show()
sys.exit(app.exec())