14 Commits

Author SHA1 Message Date
c572a3cabe Merge pull request 'Версия 0.1.1' (#1) from develop into main
Reviewed-on: kor-elf/ffmpeg-gui#1
2024-01-20 17:42:02 +06:00
7cc22e1553 Edit Reademe.md.
Added a screenshot from the program.
2024-01-20 17:39:18 +06:00
9bb19a0263 Sometimes the progressbar is not displayed, so I decided not to hide it. 2024-01-20 17:05:16 +06:00
fc38a1b20c Fix after closing the program so that ffmpeg would also stop if it was running. 2024-01-20 14:58:16 +06:00
2596e822bd Fix progress bar not always shown during conversion. 2024-01-20 14:57:22 +06:00
4fa977347c Fix ffmpeg processes not terminating. 2024-01-20 02:24:14 +06:00
77b847dde6 Fix error in OS windows.
Changed the progressbar to the pipe protocol.
2024-01-20 01:53:25 +06:00
ebc8832d4d Made it possible to choose where to save. 2024-01-18 20:23:23 +06:00
5051c65ec6 Fix path to ffmpeg and ffprobe.
Added the ability to select the path to ffmpeg and ffprobe.
2024-01-18 01:39:20 +06:00
10aa917c24 I made it so that an error would be displayed if ffmpeg was not found. 2024-01-16 18:08:50 +06:00
1070b796cc Fix RunConvert.
Fixed an error converting videos with a file name that has spaces.
2024-01-16 00:15:45 +06:00
176189c9d0 Adjusted display of error text when an error occurs during video conversion. 2024-01-16 00:04:50 +06:00
dddbfa65bc Refactor package "convertor" "Main" method.
Moved the button for selecting a video file into a separate function.
2024-01-15 20:28:02 +06:00
97dd0f4b32 Refactor getSockPath.
Removed extra code.
2024-01-14 17:25:35 +06:00
16 changed files with 696 additions and 161 deletions

View File

@@ -1,3 +1,5 @@
# ffmpeg-gui
Простенький интерфейс к программе ffmpeg.
<img src="images/screenshot-ffmpeg-gui.png">

BIN
images/screenshot-ffmpeg-gui.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

View File

@@ -1,19 +1,43 @@
package convertor
import (
"errors"
"ffmpegGui/helper"
"io"
"os/exec"
"regexp"
"strconv"
"strings"
)
type ServiceContract interface {
RunConvert(setting ConvertSetting) error
GetTotalDuration(file File) (float64, error)
RunConvert(setting ConvertSetting, progress ProgressContract) error
GetTotalDuration(file *File) (float64, error)
GetFFmpegVesrion() (string, error)
GetFFprobeVersion() (string, error)
ChangeFFmpegPath(path string) (bool, error)
ChangeFFprobePath(path string) (bool, error)
GetRunningProcesses() map[int]*exec.Cmd
}
type ProgressContract interface {
GetProtocole() string
Run(stdOut io.ReadCloser, stdErr io.ReadCloser) error
}
type FFPathUtilities struct {
FFmpeg string
FFprobe string
}
type runningProcesses struct {
items map[int]*exec.Cmd
numberOfStarts int
}
type Service struct {
pathFFmpeg string
pathFFprobe string
ffPathUtilities *FFPathUtilities
runningProcesses runningProcesses
}
type File struct {
@@ -23,43 +47,55 @@ type File struct {
}
type ConvertSetting struct {
VideoFileInput File
SocketPath string
VideoFileInput *File
VideoFileOut *File
OverwriteOutputFiles bool
}
type ConvertData struct {
totalDuration float64
}
func NewService(pathFFmpeg string, pathFFprobe string) *Service {
func NewService(ffPathUtilities FFPathUtilities) *Service {
return &Service{
pathFFmpeg: pathFFmpeg,
pathFFprobe: pathFFprobe,
ffPathUtilities: &ffPathUtilities,
runningProcesses: runningProcesses{items: map[int]*exec.Cmd{}, numberOfStarts: 0},
}
}
func (s Service) RunConvert(setting ConvertSetting) error {
//args := strings.Split("-report -n -c:v libx264", " ")
//args := strings.Split("-n -c:v libx264", " ")
//args = append(args, "-progress", "unix://"+setting.SocketPath, "-i", setting.VideoFileInput.Path, "file-out.mp4")
//args := "-report -n -i " + setting.VideoFileInput.Path + " -c:v libx264 -progress unix://" + setting.SocketPath + " output-file.mp4"
//args := "-n -i " + setting.VideoFileInput.Path + " -c:v libx264 -progress unix://" + setting.SocketPath + " output-file.mp4"
args := "-y -i " + setting.VideoFileInput.Path + " -c:v libx264 -progress unix://" + setting.SocketPath + " output-file.mp4"
cmd := exec.Command("ffmpeg", strings.Split(args, " ")...)
func (s Service) RunConvert(setting ConvertSetting, progress ProgressContract) error {
overwriteOutputFiles := "-n"
if setting.OverwriteOutputFiles == true {
overwriteOutputFiles = "-y"
}
args := []string{overwriteOutputFiles, "-i", setting.VideoFileInput.Path, "-c:v", "libx264", "-progress", progress.GetProtocole(), setting.VideoFileOut.Path}
cmd := exec.Command(s.ffPathUtilities.FFmpeg, args...)
helper.PrepareBackgroundCommand(cmd)
//stderr, _ := cmd.StdoutPipe()
err := cmd.Start()
stdOut, err := cmd.StdoutPipe()
if err != nil {
return err
}
stdErr, err := cmd.StderrPipe()
if err != nil {
return err
}
//scanner := bufio.NewScanner(stderr)
////scanner.Split(bufio.ScanWords)
//for scanner.Scan() {
// m := scanner.Text()
// fmt.Println(m)
//}
err = cmd.Start()
if err != nil {
return err
}
index := s.runningProcesses.numberOfStarts
s.runningProcesses.numberOfStarts++
s.runningProcesses.items[index] = cmd
errProgress := progress.Run(stdOut, stdErr)
err = cmd.Wait()
delete(s.runningProcesses.items, index)
if errProgress != nil {
return errProgress
}
if err != nil {
return err
}
@@ -67,12 +103,71 @@ func (s Service) RunConvert(setting ConvertSetting) error {
return nil
}
func (s Service) GetTotalDuration(file File) (duration float64, err error) {
args := "-v error -select_streams v:0 -count_packets -show_entries stream=nb_read_packets -of csv=p=0 " + file.Path
cmd := exec.Command(s.pathFFprobe, strings.Split(args, " ")...)
func (s Service) GetTotalDuration(file *File) (duration float64, err error) {
args := []string{"-v", "error", "-select_streams", "v:0", "-count_packets", "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0", file.Path}
cmd := exec.Command(s.ffPathUtilities.FFprobe, args...)
helper.PrepareBackgroundCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
errString := strings.TrimSpace(string(out))
if len(errString) > 1 {
return 0, errors.New(errString)
}
return 0, err
}
return strconv.ParseFloat(strings.TrimSpace(string(out)), 64)
}
func (s Service) GetFFmpegVesrion() (string, error) {
cmd := exec.Command(s.ffPathUtilities.FFmpeg, "-version")
helper.PrepareBackgroundCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
return "", err
}
text := regexp.MustCompile("\r?\n").Split(strings.TrimSpace(string(out)), -1)
return text[0], nil
}
func (s Service) GetFFprobeVersion() (string, error) {
cmd := exec.Command(s.ffPathUtilities.FFprobe, "-version")
helper.PrepareBackgroundCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
return "", err
}
text := regexp.MustCompile("\r?\n").Split(strings.TrimSpace(string(out)), -1)
return text[0], nil
}
func (s Service) ChangeFFmpegPath(path string) (bool, error) {
cmd := exec.Command(path, "-version")
helper.PrepareBackgroundCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
return false, err
}
if strings.Contains(strings.TrimSpace(string(out)), "ffmpeg") == false {
return false, nil
}
s.ffPathUtilities.FFmpeg = path
return true, nil
}
func (s Service) ChangeFFprobePath(path string) (bool, error) {
cmd := exec.Command(path, "-version")
helper.PrepareBackgroundCommand(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
return false, err
}
if strings.Contains(strings.TrimSpace(string(out)), "ffprobe") == false {
return false, nil
}
s.ffPathUtilities.FFprobe = path
return true, nil
}
func (s Service) GetRunningProcesses() map[int]*exec.Cmd {
return s.runningProcesses.items
}

View File

@@ -1,6 +1,7 @@
package convertor
import (
"errors"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/canvas"
"fyne.io/fyne/v2/container"
@@ -11,8 +12,7 @@ import (
type ViewContract interface {
Main(
runConvert func(setting HandleConvertSetting) error,
getSocketPath func(File, *widget.ProgressBar) (string, error),
runConvert func(setting HandleConvertSetting, progressbar *widget.ProgressBar) error,
)
}
@@ -21,8 +21,15 @@ type View struct {
}
type HandleConvertSetting struct {
VideoFileInput File
SocketPath string
VideoFileInput *File
DirectoryForSave string
OverwriteOutputFiles bool
}
type enableFormConversionStruct struct {
fileVideoForConversion *widget.Button
buttonForSelectedDir *widget.Button
form *widget.Form
}
func NewView(w fyne.Window) *View {
@@ -30,24 +37,77 @@ func NewView(w fyne.Window) *View {
}
func (v View) Main(
runConvert func(setting HandleConvertSetting) error,
getSocketPath func(File, *widget.ProgressBar) (string, error),
runConvert func(setting HandleConvertSetting, progressbar *widget.ProgressBar) error,
) {
var fileInput File
var form *widget.Form
fileVideoForConversionMessage := canvas.NewText("", color.RGBA{255, 0, 0, 255})
fileVideoForConversionMessage.TextSize = 16
fileVideoForConversionMessage.TextStyle = fyne.TextStyle{Bold: true}
form := &widget.Form{}
conversionMessage := canvas.NewText("", color.RGBA{255, 0, 0, 255})
conversionMessage.TextSize = 16
conversionMessage.TextStyle = fyne.TextStyle{Bold: true}
progress := widget.NewProgressBar()
progress.Hide()
fileVideoForConversion := widget.NewButton("выбрать", func() {
fileVideoForConversion, fileVideoForConversionMessage, fileInput := v.getButtonFileVideoForConversion(form, progress, conversionMessage)
buttonForSelectedDir, buttonForSelectedDirMessage, pathToSaveDirectory := v.getButtonForSelectingDirectoryForSaving()
isOverwriteOutputFiles := false
checkboxOverwriteOutputFiles := widget.NewCheck("Разрешить перезаписать файл", func(b bool) {
isOverwriteOutputFiles = b
})
form.Items = []*widget.FormItem{
{Text: "Файл для ковертации:", Widget: fileVideoForConversion},
{Widget: fileVideoForConversionMessage},
{Text: "Папка куда будет сохраняться:", Widget: buttonForSelectedDir},
{Widget: buttonForSelectedDirMessage},
{Widget: checkboxOverwriteOutputFiles},
}
form.SubmitText = "Конвертировать"
enableFormConversionStruct := enableFormConversionStruct{
fileVideoForConversion: fileVideoForConversion,
buttonForSelectedDir: buttonForSelectedDir,
form: form,
}
form.OnSubmit = func() {
if len(*pathToSaveDirectory) == 0 {
showConversionMessage(conversionMessage, errors.New("Не выбрали папку для сохранения!"))
enableFormConversion(enableFormConversionStruct)
return
}
conversionMessage.Text = ""
fileVideoForConversion.Disable()
buttonForSelectedDir.Disable()
form.Disable()
setting := HandleConvertSetting{
VideoFileInput: fileInput,
DirectoryForSave: *pathToSaveDirectory,
OverwriteOutputFiles: isOverwriteOutputFiles,
}
err := runConvert(setting, progress)
if err != nil {
showConversionMessage(conversionMessage, err)
enableFormConversion(enableFormConversionStruct)
return
}
enableFormConversion(enableFormConversionStruct)
}
v.w.SetContent(widget.NewCard("Конвертор видео файлов в mp4", "", container.NewVBox(form, conversionMessage, progress)))
form.Disable()
}
func (v View) getButtonFileVideoForConversion(form *widget.Form, progress *widget.ProgressBar, conversionMessage *canvas.Text) (*widget.Button, *canvas.Text, *File) {
fileInput := &File{}
fileVideoForConversionMessage := canvas.NewText("", color.RGBA{255, 0, 0, 255})
fileVideoForConversionMessage.TextSize = 16
fileVideoForConversionMessage.TextStyle = fyne.TextStyle{Bold: true}
button := widget.NewButton("выбрать", func() {
fileDialog := dialog.NewFileOpen(
func(r fyne.URIReadCloser, err error) {
if err != nil {
@@ -55,59 +115,57 @@ func (v View) Main(
setStringErrorStyle(fileVideoForConversionMessage)
return
}
if r == nil {
return
}
fileInput = File{
Path: r.URI().Path(),
Name: r.URI().Name(),
Ext: r.URI().Extension(),
}
fileInput.Path = r.URI().Path()
fileInput.Name = r.URI().Name()
fileInput.Ext = r.URI().Extension()
fileVideoForConversionMessage.Text = r.URI().Path()
setStringSuccessStyle(fileVideoForConversionMessage)
form.Enable()
progress.Value = 0
progress.Refresh()
conversionMessage.Text = ""
}, v.w)
fileDialog.Show()
})
form = &widget.Form{
Items: []*widget.FormItem{
{Text: "Файл для ковертации:", Widget: fileVideoForConversion},
{Widget: fileVideoForConversionMessage},
},
SubmitText: "Конвертировать",
OnSubmit: func() {
fileVideoForConversion.Disable()
form.Disable()
return button, fileVideoForConversionMessage, fileInput
}
socketPath, err := getSocketPath(fileInput, progress)
func (v View) getButtonForSelectingDirectoryForSaving() (button *widget.Button, buttonMessage *canvas.Text, dirPath *string) {
buttonMessage = canvas.NewText("", color.RGBA{255, 0, 0, 255})
buttonMessage.TextSize = 16
buttonMessage.TextStyle = fyne.TextStyle{Bold: true}
path := ""
dirPath = &path
button = widget.NewButton("выбрать", func() {
fileDialog := dialog.NewFolderOpen(
func(r fyne.ListableURI, err error) {
if err != nil {
conversionMessage.Text = err.Error()
setStringErrorStyle(conversionMessage)
fileVideoForConversion.Enable()
form.Enable()
buttonMessage.Text = err.Error()
setStringErrorStyle(buttonMessage)
return
}
if r == nil {
return
}
setting := HandleConvertSetting{
VideoFileInput: fileInput,
SocketPath: socketPath,
}
err = runConvert(setting)
if err != nil {
conversionMessage.Text = err.Error()
setStringErrorStyle(conversionMessage)
}
fileVideoForConversion.Enable()
form.Enable()
},
}
path = r.Path()
v.w.SetContent(widget.NewCard("Конвертор видео файлов", "", container.NewVBox(form, conversionMessage, progress)))
form.Disable()
buttonMessage.Text = r.Path()
setStringSuccessStyle(buttonMessage)
}, v.w)
fileDialog.Show()
})
return
}
func setStringErrorStyle(text *canvas.Text) {
@@ -119,3 +177,14 @@ func setStringSuccessStyle(text *canvas.Text) {
text.Color = color.RGBA{49, 127, 114, 255}
text.Refresh()
}
func showConversionMessage(conversionMessage *canvas.Text, err error) {
conversionMessage.Text = err.Error()
setStringErrorStyle(conversionMessage)
}
func enableFormConversion(enableFormConversionStruct enableFormConversionStruct) {
enableFormConversionStruct.fileVideoForConversion.Enable()
enableFormConversionStruct.buttonForSelectedDir.Enable()
enableFormConversionStruct.form.Enable()
}

2
src/data/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*
!.gitignore

View File

@@ -17,7 +17,10 @@ require (
github.com/go-text/typesetting v0.0.0-20230616162802-9c17dd34aa4a // indirect
github.com/godbus/dbus/v5 v5.1.0 // indirect
github.com/gopherjs/gopherjs v1.17.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/jsummers/gobmp v0.0.0-20151104160322-e2ba15ffa76e // indirect
github.com/mattn/go-sqlite3 v1.14.19 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c // indirect
github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef // indirect
@@ -30,5 +33,7 @@ require (
golang.org/x/sys v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/driver/sqlite v1.5.4 // indirect
gorm.io/gorm v1.25.5 // indirect
honnef.co/go/js/dom v0.0.0-20210725211120-f030747120f2 // indirect
)

View File

@@ -191,6 +191,10 @@ github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/J
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk=
@@ -206,6 +210,8 @@ github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-sqlite3 v1.14.19 h1:fhGleo2h1p8tVChob4I9HpmVFIAkKGpiukdrgQbWfGI=
github.com/mattn/go-sqlite3 v1.14.19/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
@@ -647,6 +653,12 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.5.4 h1:IqXwXi8M/ZlPzH/947tn5uik3aYQslP9BVveoax0nV0=
gorm.io/driver/sqlite v1.5.4/go.mod h1:qxAuCol+2r6PannQDpOP1FP6ag3mKi4esLnB/jHed+4=
gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55 h1:sC1Xj4TYrLqg1n3AN10w871An7wJM0gzgcm8jkIkECQ=
gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
gorm.io/gorm v1.25.5 h1:zR9lOiiYf09VNh5Q1gphfyia1JpiClIWG9hQaxB/mls=
gorm.io/gorm v1.25.5/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
honnef.co/go/js/dom v0.0.0-20210725211120-f030747120f2 h1:oomkgU6VaQDsV6qZby2uz1Lap0eXmku8+2em3A/l700=
honnef.co/go/js/dom v0.0.0-20210725211120-f030747120f2/go.mod h1:sUMDUKNB2ZcVjt92UnLy3cdGs+wDAcrPdV3JP6sVgA4=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

View File

@@ -1,112 +1,205 @@
package handler
import (
"bufio"
"errors"
"ffmpegGui/convertor"
myError "ffmpegGui/error"
"fmt"
"ffmpegGui/helper"
"ffmpegGui/setting"
"fyne.io/fyne/v2/widget"
"log"
"math/rand"
"net"
"os"
"path"
"io"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
type ConvertorHandler struct {
convertorService convertor.ServiceContract
convertorView convertor.ViewContract
errorView myError.ViewContract
settingView setting.ViewContract
settingRepository setting.RepositoryContract
}
func NewConvertorHandler(
convertorService convertor.ServiceContract,
convertorView convertor.ViewContract,
errorView myError.ViewContract,
settingView setting.ViewContract,
settingRepository setting.RepositoryContract,
) *ConvertorHandler {
return &ConvertorHandler{
convertorService,
convertorView,
errorView,
settingView,
settingRepository,
}
}
func (h ConvertorHandler) GetConvertor() {
h.convertorView.Main(h.runConvert, h.getSockPath)
}
func (h ConvertorHandler) getSockPath(file convertor.File, progressbar *widget.ProgressBar) (string, error) {
totalDuration, err := h.getTotalDuration(file)
if err != nil {
return "", err
}
progressbar.Value = 0
progressbar.Max = totalDuration
progressbar.Show()
progressbar.Refresh()
rand.Seed(time.Now().Unix())
sockFileName := path.Join(os.TempDir(), fmt.Sprintf("%d_sock", rand.Int()))
l, err := net.Listen("unix", sockFileName)
if err != nil {
return "", err
}
go func() {
re := regexp.MustCompile(`frame=(\d+)`)
fd, err := l.Accept()
if err != nil {
log.Fatal("accept error:", err)
}
buf := make([]byte, 16)
data := ""
progress := 0.0
progressMessage := ""
for {
_, err := fd.Read(buf)
if err != nil {
if h.checkingFFPathUtilities() == true {
h.convertorView.Main(h.runConvert)
return
}
data += string(buf)
a := re.FindAllStringSubmatch(data, -1)
cp := ""
if len(a) > 0 && len(a[len(a)-1]) > 0 {
c, _ := strconv.Atoi(a[len(a)-1][len(a[len(a)-1])-1])
progress = float64(c)
cp = fmt.Sprintf("%.2f", float64(c)/totalDuration*100)
}
if strings.Contains(data, "progress=end") {
cp = "done"
progress = totalDuration
}
if cp == "" {
cp = ".0"
}
if cp != progressMessage {
progressbar.Value = progress
progressbar.Refresh()
progressMessage = cp
fmt.Println("progress: ", progressMessage)
}
}
}()
return sockFileName, nil
h.settingView.SelectFFPath(h.saveSettingFFPath)
}
func (h ConvertorHandler) runConvert(setting convertor.HandleConvertSetting) error {
func (h ConvertorHandler) runConvert(setting convertor.HandleConvertSetting, progressbar *widget.ProgressBar) error {
totalDuration, err := h.convertorService.GetTotalDuration(setting.VideoFileInput)
if err != nil {
return err
}
progress := NewProgress(totalDuration, progressbar)
return h.convertorService.RunConvert(
convertor.ConvertSetting{
VideoFileInput: setting.VideoFileInput,
SocketPath: setting.SocketPath,
VideoFileOut: &convertor.File{
Path: setting.DirectoryForSave + helper.PathSeparator() + setting.VideoFileInput.Name + ".mp4",
Name: setting.VideoFileInput.Name,
Ext: ".mp4",
},
OverwriteOutputFiles: setting.OverwriteOutputFiles,
},
progress,
)
}
func (h ConvertorHandler) getTotalDuration(file convertor.File) (float64, error) {
return h.convertorService.GetTotalDuration(file)
func (h ConvertorHandler) checkingFFPathUtilities() bool {
if h.checkingFFPath() == true {
return true
}
var pathsToFF []convertor.FFPathUtilities
if runtime.GOOS == "windows" {
pathsToFF = []convertor.FFPathUtilities{{"ffmpeg\\bin\\ffmpeg.exe", "ffmpeg\\bin\\ffprobe.exe"}}
} else {
pathsToFF = []convertor.FFPathUtilities{{"ffmpeg/bin/ffmpeg", "ffmpeg/bin/ffprobe"}, {"ffmpeg", "ffprobe"}}
}
for _, item := range pathsToFF {
ffmpegChecking, _ := h.convertorService.ChangeFFmpegPath(item.FFmpeg)
if ffmpegChecking == false {
continue
}
ffprobeChecking, _ := h.convertorService.ChangeFFprobePath(item.FFprobe)
if ffprobeChecking == false {
continue
}
ffmpegEntity := setting.Setting{Code: "ffmpeg", Value: item.FFmpeg}
_, _ = h.settingRepository.Create(ffmpegEntity)
ffprobeEntity := setting.Setting{Code: "ffprobe", Value: item.FFprobe}
_, _ = h.settingRepository.Create(ffprobeEntity)
return true
}
return false
}
func (h ConvertorHandler) saveSettingFFPath(ffmpegPath string, ffprobePath string) error {
ffmpegChecking, _ := h.convertorService.ChangeFFmpegPath(ffmpegPath)
if ffmpegChecking == false {
return errors.New("это не FFmpeg")
}
ffprobeChecking, _ := h.convertorService.ChangeFFprobePath(ffprobePath)
if ffprobeChecking == false {
return errors.New("это не FFprobe")
}
ffmpegEntity := setting.Setting{Code: "ffmpeg", Value: ffmpegPath}
_, _ = h.settingRepository.Create(ffmpegEntity)
ffprobeEntity := setting.Setting{Code: "ffprobe", Value: ffprobePath}
_, _ = h.settingRepository.Create(ffprobeEntity)
h.GetConvertor()
return nil
}
func (h ConvertorHandler) checkingFFPath() bool {
_, err := h.convertorService.GetFFmpegVesrion()
if err != nil {
return false
}
_, err = h.convertorService.GetFFprobeVersion()
if err != nil {
return false
}
return true
}
type progress struct {
totalDuration float64
progressbar *widget.ProgressBar
protocol string
}
func NewProgress(totalDuration float64, progressbar *widget.ProgressBar) progress {
return progress{
totalDuration: totalDuration,
progressbar: progressbar,
protocol: "pipe:",
}
}
func (p progress) GetProtocole() string {
return p.protocol
}
func (p progress) Run(stdOut io.ReadCloser, stdErr io.ReadCloser) error {
isProcessCompleted := false
var errorText string
p.progressbar.Value = 0
p.progressbar.Max = p.totalDuration
p.progressbar.Refresh()
progress := 0.0
go func() {
scannerErr := bufio.NewScanner(stdErr)
for scannerErr.Scan() {
errorText = scannerErr.Text()
}
if err := scannerErr.Err(); err != nil {
errorText = err.Error()
}
}()
scannerOut := bufio.NewScanner(stdOut)
for scannerOut.Scan() {
if isProcessCompleted != true {
isProcessCompleted = true
}
data := scannerOut.Text()
re := regexp.MustCompile(`frame=(\d+)`)
a := re.FindAllStringSubmatch(data, -1)
if len(a) > 0 && len(a[len(a)-1]) > 0 {
c, err := strconv.Atoi(a[len(a)-1][len(a[len(a)-1])-1])
if err != nil {
continue
}
progress = float64(c)
}
if strings.Contains(data, "progress=end") {
p.progressbar.Value = p.totalDuration
p.progressbar.Refresh()
isProcessCompleted = true
}
if p.progressbar.Value != progress {
p.progressbar.Value = progress
p.progressbar.Refresh()
}
}
if isProcessCompleted == false {
if len(errorText) == 0 {
errorText = "не смогли отконвертировать видео"
}
return errors.New(errorText)
}
return nil
}

10
src/helper/helper.go Normal file
View File

@@ -0,0 +1,10 @@
package helper
import "runtime"
func PathSeparator() string {
if runtime.GOOS == "windows" {
return "\\"
}
return "/"
}

View File

@@ -0,0 +1,12 @@
//go:build !windows
// +build !windows
package helper
import (
"os/exec"
)
func PrepareBackgroundCommand(cmd *exec.Cmd) {
}

View File

@@ -0,0 +1,13 @@
//go:build windows
// +build windows
package helper
import (
"os/exec"
"syscall"
)
func PrepareBackgroundCommand(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
}

View File

@@ -1,30 +1,97 @@
package main
import (
"errors"
"ffmpegGui/convertor"
myError "ffmpegGui/error"
"ffmpegGui/handler"
"ffmpegGui/migration"
"ffmpegGui/setting"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
_ "github.com/mattn/go-sqlite3"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"os"
)
const appVersion string = "0.1.0"
//const appVersion string = "0.1.1"
func main() {
a := app.New()
w := a.NewWindow("GUI FFMpeg!")
w.Resize(fyne.Size{800, 600})
w.Resize(fyne.Size{Width: 800, Height: 600})
w.CenterOnScreen()
errorView := myError.NewView(w)
pathFFmpeg := "ffmpeg"
pathFFprobe := "ffprobe"
if canCreateFile("data/database") != true {
errorView.PanicError(errors.New("не смогли создать файл 'database' в папке 'data'"))
w.ShowAndRun()
return
}
db, err := gorm.Open(sqlite.Open("data/database"), &gorm.Config{})
if err != nil {
errorView.PanicError(err)
w.ShowAndRun()
return
}
defer appCloseWithDb(db)
err = migration.Run(db)
if err != nil {
errorView.PanicError(err)
w.ShowAndRun()
return
}
settingRepository := setting.NewRepository(db)
pathFFmpeg, err := settingRepository.GetValue("ffmpeg")
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) == false {
errorView.PanicError(err)
w.ShowAndRun()
return
}
pathFFprobe, err := settingRepository.GetValue("ffprobe")
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) == false {
errorView.PanicError(err)
w.ShowAndRun()
return
}
ffPathUtilities := convertor.FFPathUtilities{FFmpeg: pathFFmpeg, FFprobe: pathFFprobe}
convertorView := convertor.NewView(w)
convertorService := convertor.NewService(pathFFmpeg, pathFFprobe)
mainHandler := handler.NewConvertorHandler(convertorService, convertorView, errorView)
settingView := setting.NewView(w)
convertorService := convertor.NewService(ffPathUtilities)
defer appCloseWithConvert(convertorService)
mainHandler := handler.NewConvertorHandler(convertorService, convertorView, settingView, settingRepository)
mainHandler.GetConvertor()
w.ShowAndRun()
}
func appCloseWithDb(db *gorm.DB) {
sqlDB, err := db.DB()
if err == nil {
_ = sqlDB.Close()
}
}
func appCloseWithConvert(convertorService convertor.ServiceContract) {
for _, cmd := range convertorService.GetRunningProcesses() {
_ = cmd.Process.Kill()
}
}
func canCreateFile(path string) bool {
file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return false
}
_ = file.Close()
return true
}

View File

@@ -0,0 +1,15 @@
package migration
import (
"ffmpegGui/setting"
"gorm.io/gorm"
)
func Run(db *gorm.DB) error {
err := db.AutoMigrate(&setting.Setting{})
if err != nil {
return err
}
return nil
}

7
src/setting/entity.go Normal file
View File

@@ -0,0 +1,7 @@
package setting
type Setting struct {
ID uint `gorm:"primary_key"`
Code string `gorm:"type:varchar(100);uniqueIndex;not null"`
Value string `gorm:"type:text"`
}

35
src/setting/repository.go Normal file
View File

@@ -0,0 +1,35 @@
package setting
import (
"gorm.io/gorm"
)
type RepositoryContract interface {
Create(setting Setting) (Setting, error)
GetValue(code string) (value string, err error)
}
type Repository struct {
db *gorm.DB
}
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db}
}
func (r Repository) GetValue(code string) (value string, err error) {
var setting Setting
err = r.db.Where("code = ?", code).First(&setting).Error
if err != nil {
return "", err
}
return setting.Value, err
}
func (r Repository) Create(setting Setting) (Setting, error) {
err := r.db.Create(&setting).Error
if err != nil {
return setting, err
}
return setting, err
}

98
src/setting/view.go Normal file
View File

@@ -0,0 +1,98 @@
package setting
import (
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/canvas"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/dialog"
"fyne.io/fyne/v2/widget"
"image/color"
"net/url"
)
type ViewContract interface {
SelectFFPath(func(ffmpegPath string, ffprobePath string) error)
}
type View struct {
w fyne.Window
}
func NewView(w fyne.Window) *View {
return &View{w}
}
func (v View) SelectFFPath(save func(ffmpegPath string, ffprobePath string) error) {
errorMessage := canvas.NewText("", color.RGBA{255, 0, 0, 255})
errorMessage.TextSize = 16
errorMessage.TextStyle = fyne.TextStyle{Bold: true}
ffmpegPath, buttonFFmpeg, buttonFFmpegMessage := v.getButtonSelectFile()
ffprobePath, buttonFFprobe, buttonFFprobeMessage := v.getButtonSelectFile()
link := widget.NewHyperlink("https://ffmpeg.org/download.html", &url.URL{
Scheme: "https",
Host: "ffmpeg.org",
Path: "download.html",
})
form := &widget.Form{
Items: []*widget.FormItem{
{Text: "Скачать можно от сюда", Widget: link},
{Text: "Путь к ffmpeg:", Widget: buttonFFmpeg},
{Widget: buttonFFmpegMessage},
{Text: "Путь к ffprobe:", Widget: buttonFFprobe},
{Widget: buttonFFprobeMessage},
{Widget: errorMessage},
},
SubmitText: "Сохранить",
OnSubmit: func() {
err := save(string(*ffmpegPath), string(*ffprobePath))
if err != nil {
errorMessage.Text = err.Error()
}
},
}
v.w.SetContent(widget.NewCard("Укажите путь к FFmpeg и к FFprobe", "", container.NewVBox(form)))
}
func (v View) getButtonSelectFile() (filePath *string, button *widget.Button, buttonMessage *canvas.Text) {
path := ""
filePath = &path
buttonMessage = canvas.NewText("", color.RGBA{255, 0, 0, 255})
buttonMessage.TextSize = 16
buttonMessage.TextStyle = fyne.TextStyle{Bold: true}
button = widget.NewButton("выбрать", func() {
fileDialog := dialog.NewFileOpen(
func(r fyne.URIReadCloser, err error) {
if err != nil {
buttonMessage.Text = err.Error()
setStringErrorStyle(buttonMessage)
return
}
if r == nil {
return
}
path = r.URI().Path()
buttonMessage.Text = r.URI().Path()
setStringSuccessStyle(buttonMessage)
}, v.w)
fileDialog.Show()
})
return
}
func setStringErrorStyle(text *canvas.Text) {
text.Color = color.RGBA{255, 0, 0, 255}
text.Refresh()
}
func setStringSuccessStyle(text *canvas.Text) {
text.Color = color.RGBA{49, 127, 114, 255}
text.Refresh()
}