-
Notifications
You must be signed in to change notification settings - Fork 2
/
AutoRender.ahk
1297 lines (1209 loc) · 47.5 KB
/
AutoRender.ahk
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
; Setting the compiler directives to customize the EXE properties.
;@Ahk2Exe-SetCompanyName Lordscales91
;@Ahk2Exe-SetCopyright Copyright(c) 2021
;@Ahk2Exe-SetDescription MMD VR AutoRender
;@Ahk2Exe-SetVersion 0.1.0-beta
;@Ahk2Exe-SetName MMD VR AutoRender
#Include DataModel.ahk
#SingleInstance, force
SetWorkingDir, %A_ScriptDir%
SetControlDelay, 100
SetTitleMatchMode, 2
global VR_180_MODE := 1
global VR_360_MODE := 2
global VR_SIDE_LEFT = "L"
global VR_SIDE_RIGHT = "R"
global VR_SIDE_TOP = "T"
global VR_SIDE_BOTTOM = "B"
global VR_SIDE_FRONT = "F"
global EYE_LEFT := "L"
global EYE_RIGHT := "R"
global FILETYPE_RENDER = 1
global FILETYPE_ENCODED = 2
global FILETYPE_FOLDER = 3
global FATAL_ERROR := "FatalError"
global WORKDIR_PREFIX := "workDir\"
if (A_IsCompiled) {
WORKDIR_PREFIX := ""
}
global userPreferencesFile := "preferences.ini"
global userPrefs := ""
global defaultRenderCodec := "MJPEG"
global defaultEncodingFormat := "MP4"
global defaultEncodingQuality := "medium"
global defaultFrameRate := 60
IsFatalError(val) {
Return val == FATAL_ERROR
}
FatalError() {
Return FATAL_ERROR
}
InitPhase() {
userPrefs := GetOrCreateUserPreferences()
jobs := GetPendingJobs()
if(jobs.Length()) {
if(jobs[1].jobStatus != JobData.STATUS_PENDING) {
MsgBox, 0x24, % "Confirmation", % "A previous Job couldn't finish`nDo you want to resume it?"
IfMsgBox, Yes
{
StartMMDPhase(jobs[1])
} else {
StartMMDPhase()
}
} else {
; Automatically launch a pending job
StartMMDPhase(jobs[1])
}
} else {
StartMMDPhase()
}
}
ReadUserPreferences() {
IniRead, MMDExecutable, %userPreferencesFile%, General, MMDExecutable
IniRead, deleteStagingFiles, %userPreferencesFile%, General, deleteStagingFiles, 0
IniRead, fps, %userPreferencesFile%, Render, fps, %defaultFrameRate%
IniRead, renderCodec, %userPreferencesFile%, Render, renderCodec, %defaultRenderCodec%
IniRead, finalEncodingFormat, %userPreferencesFile%, Encoding, finalEncodingFormat, %defaultEncodingFormat%
IniRead, finalEncodingQuality, %userPreferencesFile%, Encoding, finalEncodingQuality, %defaultEncodingQuality%
IniRead, finalVideoOutDir, %userPreferencesFile%, Encoding, finalVideoOutDir, %A_Space%
if (!finalVideoOutDir) {
finalVideoOutDir := DetermineDefaultOutputDir()
}
prefs := new UserPreferences
prefs.MMDExecutable := MMDExecutable
prefs.deleteStagingFiles := deleteStagingFiles
prefs.fps := fps
prefs.renderCodec := renderCodec
prefs.finalEncodingFormat := finalEncodingFormat
prefs.finalEncodingQuality := finalEncodingQuality
prefs.finalVideoOutDir := finalVideoOutDir
Return prefs
}
WriteUserPreferences(prefs) {
isNew := true
try {
if(InStr(FileExist(userPreferencesFile), "A")) {
isNew := false
}
IniWrite % prefs.MMDExecutable, %userPreferencesFile%, General, MMDExecutable
IniWrite % prefs.deleteStagingFiles, %userPreferencesFile%, General, deleteStagingFiles
IniWrite % prefs.fps, %userPreferencesFile%, Render, fps
IniWrite % prefs.renderCodec, %userPreferencesFile%, Render, renderCodec
IniWrite % prefs.finalEncodingFormat, %userPreferencesFile%, Encoding, finalEncodingFormat
IniWrite % prefs.finalEncodingQuality, %userPreferencesFile%, Encoding, finalEncodingQuality
IniWrite % prefs.finalVideoOutDir, %userPreferencesFile%, Encoding, finalVideoOutDir
} catch {
action := "created"
if(!isNew) {
action := "updated"
}
MsgBox, 0x10, % "Error", % "Preferences file couldn't be " action ".`nEnsure you have write permissions to this folder"
ExitApp, 1
}
}
GetOrCreateUserPreferences() {
prefs := new UserPreferences
if (InStr(FileExist(userPreferencesFile), "A")) {
prefs := ReadUserPreferences()
} else {
prefs.finalVideoOutDir := DetermineDefaultOutputDir()
WriteUserPreferences(prefs)
}
Return prefs
}
GetPendingJobs() {
jobs := []
; first take a look at the jobs started but never finished
Loop, Files, % WORKDIR_PREFIX "status\processing\*.main"
{
if(RegExMatch(A_LoopFileName, "(.*?)\.", jobId)) {
job := ReadJobData(jobId1)
if (IsObject(job)) {
jobs.Push(job)
}
}
}
; Get the pending jobs
Loop, Files, % WORKDIR_PREFIX "status\pending\*.main"
{
if(RegExMatch(A_LoopFileName, "(.*?)\.", jobId)) {
job := ReadJobData(jobId1)
if(IsObject(job)) {
jobs.Push(job)
}
}
}
Return jobs
}
ReadJobData(pJobId, readTasks:=true) {
jobIniFile := WORKDIR_PREFIX . "jobs\" . pJobId . "\main.ini"
if(!InStr(FileExist(jobIniFile), "A")) {
; TODO: Log the error in a log file
; For now put a toast
TrayTip % "Warning", % "Job data file couldn't be found", 1, 2
Return ""
}
IniRead, jobId, %jobIniFile%, General, jobId
IniRead, jobShortId, %jobIniFile%, General, jobShortId
IniRead, jobStatus, %jobIniFile%, General, jobStatus
IniRead, pmmFile, %jobIniFile%, General, pmmFile
IniRead, baseVideoName, %jobIniFile%, General, baseVideoName
IniRead, fps, %jobIniFile%, General, fps
IniRead, VRFormat, %jobIniFile%, General, VRFormat, 0
IniRead, parallaxEnabled, %jobIniFile%, General, parallaxEnabled, 0
IniRead, sidesPerEye, %jobIniFile%, General, sidesPerEye, 0
IniRead, resolutionStr, %jobIniFile%, General, resolution
IniRead, recordingFramesStr, %jobIniFile%, General, recordingFrames
IniRead, taskNamesStr, %jobIniFile%, General, taskNames, %A_Space%
if(!taskNamesStr) {
; This shouldn't happen unless the user messed up the ini file
Return ""
}
job := new JobData
job.jobId := jobId
job.jobShortId := jobShortId
job.jobStatus := jobStatus
job.pmmFile := pmmFile
job.baseVideoName := baseVideoName
job.fps := fps
job.VRFormat := VRFormat
job.parallaxEnabled := parallaxEnabled
job.sidesPerEye := sidesPerEye
job.resolution := StrSplit(resolutionStr, ",")
job.recordingFrames := StrSplit(recordingFramesStr, ",")
if(readTasks) {
taskNamesArr := StrSplit(taskNamesStr, ",")
tasks := ReadTaskData(pJobId, taskNamesArr)
if (!tasks.Length()) {
job := ""
TrayTip % "Warning", % "Job contains no tasks (or tasks couldn't be loaded)", 1, 2
Return ""
}
job.tasks := tasks
}
Return job
}
WriteJobData(job, writeTasks:=false) {
success := true
if(!InStr(FileExist(WORKDIR_PREFIX . "jobs\" . job.jobId), "D")) {
try {
FileCreateDir % WORKDIR_PREFIX "jobs\" job.jobId
} catch {
success := false
TrayTip % "Error", % "Couldn't store information about the job.`nIt won't be possible to proceed to the Encoding Phase.", 2, 3
}
}
if(success) {
try {
jobId := job.jobId
jobIniFile := WORKDIR_PREFIX . "jobs\" . jobId . "\main.ini"
IniWrite % jobId, %jobIniFile%, General, jobId
if(job.jobShortId != -1) {
IniWrite % job.jobShortId, %jobIniFile%, General, jobShortId
}
IniWrite % job.jobStatus, %jobIniFile%, General, jobStatus
UpdateJobStatus(job, job.jobStatus)
IniWrite % job.pmmFile, %jobIniFile%, General, pmmFile
IniWrite % job.baseVideoName, %jobIniFile%, General, baseVideoName
IniWrite % job.fps, %jobIniFile%, General, fps
if(job.VRFormat) {
IniWrite % job.VRFormat, %jobIniFile%, General, VRFormat
}
if(job.parallaxEnabled) {
IniWrite % job.parallaxEnabled, %jobIniFile%, General, parallaxEnabled
}
if(job.sidesPerEye) {
IniWrite % job.sidesPerEye, %jobIniFile%, General, sidesPerEye
}
if(IsObject(job.resolution) && job.resolution.Count() == 2) {
IniWrite % job.resolution[1] "," job.resolution[2], %jobIniFile%, General, resolution
}
if(IsObject(job.recordingFrames) && job.recordingFrames.Count() == 2) {
IniWrite % job.recordingFrames[1] "," job.recordingFrames[2], %jobIniFile%, General, recordingFrames
}
if(IsObject(job.tasks) && job.tasks.Length() > 0) {
taskNames := ""
for i, task in job.tasks {
if (i > 1) {
taskNames .= ","
}
taskNames .= task.taskId
if(writeTasks) {
WriteTaskData(task)
}
}
IniWrite % taskNames, %jobIniFile%, General, taskNames
}
} catch {
success := false
TrayTip % "Error", % "Couldn't store information about the job.`nIt won't be possible to proceed to the Encoding Phase.", 2, 3
}
}
Return success
}
ReadTaskData(pJobId, taskNames) {
tasks := []
for i, name in taskNames {
taskIniFile := WORKDIR_PREFIX . "jobs\" . pJobId . "\" . name . ".ini"
if(InStr(FileExist(taskIniFile), "A")) {
IniRead, taskShortId, %taskIniFile%, General, taskShortId
IniRead, taskType, %taskIniFile%, General, taskType
IniRead, taskStatus, %taskIniFile%, General, taskStatus
IniRead, taskResult, %taskIniFile%, General, taskResult, %A_Space%
IniRead, side, %taskIniFile%, General, side
IniRead, dependsOnStr, %taskIniFile%, General, dependsOn, %A_Space%
task := new TaskData
task.taskId := name
task.taskShortId := taskShortId
task.taskType := taskType
task.taskStatus := taskStatus
task.taskResult := taskResult
task.jobId := pJobId
task.side := side
task.dependsOn := StrSplit(dependsOnStr, ",")
tasks.Push(task)
}
}
Return tasks
}
WriteTaskData(task) {
success := true
if(!InStr(FileExist(WORKDIR_PREFIX . "jobs\" . task.jobId), "D")) {
try {
FileCreateDir % WORKDIR_PREFIX "jobs\" task.jobId
} catch {
success := false
TrayTip % "Error", % "Couldn't store information about the job.`nIt won't be possible to proceed to the Encoding Phase.", 2, 3
}
}
if(success) {
try {
taskIniFile := WORKDIR_PREFIX . "jobs\" . task.jobId . "\" . task.taskId . ".ini"
IniWrite % task.taskId, %taskIniFile%, General, taskId
if(task.taskShortId != -1) {
IniWrite % task.taskShortId, %taskIniFile%, General, taskShortId
}
IniWrite % task.taskId, %taskIniFile%, General, taskId
IniWrite % task.taskType, %taskIniFile%, General, taskType
IniWrite % task.taskStatus, %taskIniFile%, General, taskStatus
IniWrite % task.taskResult, %taskIniFile%, General, taskResult
IniWrite % task.jobId, %taskIniFile%, General, jobId
IniWrite % task.side, %taskIniFile%, General, side
if (IsObject(task.dependsOn) && task.dependsOn.Length() > 0) {
dependsOnStr := ""
for i, d in task.dependsOn {
if (i > 1) {
dependsOnStr .= ","
}
dependsOnStr .= d
}
IniWrite % dependsOnStr, %taskIniFile%, General, dependsOn
}
} catch {
success := false
TrayTip % "Error", % "Couldn't store information about the job.`nIt won't be possible to proceed to the Encoding Phase.", 2, 3
}
}
Return success
}
UpdateJobStatus(ByRef job, newStatus) {
success := true
action := "created"
try {
oldStatusFile := DetermineJobStatusFilePath(job.jobId, job.jobStatus)
newStatusFile := DetermineJobStatusFilePath(job.jobId, newStatus)
if(InStr(FileExist(oldStatusFile), "A")) {
; Move file
action := "updated"
FileMove, %oldStatusFile%, %newStatusFile%
} else {
FileAppend,, %newStatusFile%
}
job.jobStatus := newStatus
IniWrite % job.jobStatus, % WORKDIR_PREFIX "jobs\" job.jobId "\main.ini", General, jobStatus
} catch {
success := false
TrayTip % "Warning", % "Job status file couldn't be " action, 1, 2
}
Return success
}
UpdateTaskStatus(ByRef task, newStatus) {
success := true
try {
IniWrite % newStatus, % WORKDIR_PREFIX "jobs\" task.jobId "\" task.taskId ".ini", General, taskStatus
task.taskStatus := newStatus
} catch {
success := false
TrayTip % "Warning", % "Couldn't update the task status", 1, 2
}
Return success
}
PullTaskStatus(ByRef task) {
IniRead, taskStatus, % WORKDIR_PREFIX "jobs\" task.jobId "\" task.taskId ".ini", General, taskStatus
IniRead, taskResult, % WORKDIR_PREFIX "jobs\" task.jobId "\" task.taskId ".ini", General, taskResult, %A_Space%
task.taskStatus := taskStatus
task.taskResult := taskResult
}
DetermineJobStatusFilePath(jobId, jobStatus) {
directory := WORKDIR_PREFIX . "status\pending\"
if(jobStatus == JobData.STATUS_PROCESSING) {
directory := WORKDIR_PREFIX . "status\processing\"
}
if(jobStatus == JobData.STATUS_COMPLETED) {
directory := WORKDIR_PREFIX . "status\completed\"
}
if(!InStr(FileExist(directory), "D")) {
FileCreateDir % directory
}
filePath := directory . jobId . ".main"
Return filePath
}
DetermineDefaultOutputDir() {
outputDir := A_WorkingDir . "\" . WORKDIR_PREFIX . "out"
EnvGet, userpf, UserProfile
if (InStr(FileExist(userpf . "\Videos"), "D")) {
try {
FileCreateDir % userpf . "\Videos\MMDVideos"
if (ErrorLevel == 0) {
outputDir := userpf . "\Videos\MMDVideos"
}
} catch {}
}
Return outputDir
}
StartMMDPhase(job:="") {
; Locating an MMD instance
WinGet, mmdInstances, List, ahk_class Polygon Movie Maker
if (mmdInstances == 1) {
if(!userPrefs.MMDExecutable) {
; Try to fill up the MMD executable path if needed
mmdPath := DetermineMMDExecutablePath(mmdInstances1)
if (mmdPath) {
userPrefs.MMDExecutable := mmdPath
WriteUserPreferences(userPrefs)
}
}
success := true
if(!job) {
Random, rand1, 10000, 99999
Random, rand2
job := new JobData
job.jobId := A_Now . "_" . rand1
job.jobShortId := Format("{:08x}", rand2)
; Determine the data from the running MMD instance
; Create a job holding that data and persist it
success := DetermineJobDataFromMMD(job, mmdInstances1)
if(IsFatalError(success)) {
; TODO: Ideally here we should trigger some retry behaviour
MsgBox, 0x10, % "Error", % "Process couldn't be finished."
ExitApp, 1
} else {
InitializeTasks(job)
WriteJobData(job, true)
}
}
aux := StartVR180Rendering(mmdInstances1, job)
success := (IsFatalError(aux))?FatalError():(success && aux)
if(IsFatalError(success)) {
MsgBox, 0x10, % "Error", % "Process couldn't be finished."
ExitApp, 1
} else if(success) {
MsgBox % "Process complete"
ExitApp
} else {
MsgBox, 0x10, % "Error", % "Process ended with errors."
ExitApp, 1
}
} else if (mmdInstances > 1) {
; TODO: Implement batch mode
MsgBox, 0x10, % "Error", % "More than one MMD instance was found.`nPlease close one and try again"
ExitApp, 1
} else {
MsgBox, 0x10, % "Error", % "No MMD instances found.`nOpen MMD before executing this program"
ExitApp, 1
}
}
InitializeTasks(ByRef job) {
; TODO: Create the proper tasks depending on the job data
eyes := [EYE_LEFT, EYE_RIGHT]
sides := [VR_SIDE_LEFT, VR_SIDE_RIGHT, VR_SIDE_TOP, VR_SIDE_BOTTOM, VR_SIDE_FRONT]
taskCounter := 1
tasks := []
; First render and encode the left eye, then the right one
for i, eye in eyes {
for j, side in sides {
Random, rand1
task := new TaskData
task.jobId := job.jobId
task.taskShortId := Format("{:08x}", rand1)
task.taskId := Format("{:05d}", taskCounter) . "_rendering"
task.taskType := TaskData.T_RENDERING
task.taskStatus := TaskData.STATUS_PENDING
task.side := eye . side
tasks.Push(task)
taskCounter++
}
Random, rand1
task := new TaskData
task.jobId := job.jobId
task.taskShortId := Format("{:08x}", rand1)
task.taskId := Format("{:05d}", taskCounter) . "_encoding"
task.taskType := TaskData.T_ENCODING
task.taskStatus := TaskData.STATUS_PENDING
task.side := eye
tasks.Push(task)
taskCounter++
}
; Now we only need the final encoding (merging the left and right videos), inject the metadata and upload it
Random, rand1
task := new TaskData
task.jobId := job.jobId
task.taskShortId := Format("{:08x}", rand1)
task.taskId := Format("{:05d}", taskCounter) . "_encoding"
task.taskType := TaskData.T_ENCODING
task.taskStatus := TaskData.STATUS_PENDING
task.side := "F"
tasks.Push(task)
taskCounter++
Random, rand1
injectTask := new TaskData
injectTask.jobId := job.jobId
injectTask.taskShortId := Format("{:08x}", rand1)
injectTask.taskId := Format("{:05d}", taskCounter) . "_inject_metadata"
injectTask.taskType := TaskData.T_INJECT_METADATA
injectTask.taskStatus := TaskData.STATUS_PENDING
tasks.Push(injectTask)
taskCounter++
; Add an uploading task if there are API credentials
if(FileExist("config\youtube_oauth.ini")) {
Random, rand1
injectTask := new TaskData
injectTask.jobId := job.jobId
injectTask.taskShortId := Format("{:08x}", rand1)
injectTask.taskId := Format("{:05d}", taskCounter) . "_upload"
injectTask.taskType := TaskData.T_UPLOAD
injectTask.taskStatus := TaskData.STATUS_PENDING
tasks.Push(injectTask)
taskCounter++
}
job.tasks := tasks
}
StartVR180Rendering(mmdWin, job) {
UpdateJobStatus(job, JobData.STATUS_PROCESSING)
success := CreateStagingDir(job, fullPathStaging)
if(!success) {
Return FatalError()
}
videoName := job.baseVideoName
viewpointModel := FindViewpointModelName(mmdWin, videoName)
if(!viewpointModel) {
MsgBox, 0x10, % "Error", % "Viewpoint model not found"
ExitApp, 1
}
preferredCodecs := []
; Set the preferred codecs, in priority order, first the job and then the user preferences
if (job.renderCodec) {
preferredCodecs.Push(job.renderCodec)
}
if (userPrefs.renderCodec) {
preferredCodecs.Push(userPrefs.renderCodec)
}
; Set some fallback codecs
preferredCodecs.Push("MJPEG", "ffdshow video encoder")
encodingOptions := {startFrame: job.recordingFrames[1], endFrame: job.recordingFrames[2], enableAudio: true, fps: 60
, preferredCodecs: preferredCodecs}
finalEncodedVideoPath := ""
injectedVideoPath := ""
for i, task in job.tasks {
shouldProcess := (task.taskStatus != TaskData.STATUS_COMPLETED)?1:0
if(i > 1) {
encodingOptions.enableAudio := false
}
if(shouldProcess && task.taskType == TaskData.T_RENDERING) {
eye := SubStr(task.side, 1, 1)
side := SubStr(task.side, 2, 1)
prefix := eye . side . "_"
videoFilepath := fullPathStaging . "\" . prefix . videoName . ".avi"
if (FileExist(videoFilepath)) {
; If a previous file with the same name exists it means it's from a previous failed attempt.
; Get rid of it before starting the process
FileDelete, %videoFilepath%
}
UpdateTaskStatus(task, TaskData.STATUS_PREPARING)
success := (success && PrepareRenderVRSide(mmdWin, videoName, viewpointModel, side, eye))
if (success) {
UpdateTaskStatus(task, TaskData.STATUS_PROCESSING)
success := RenderVideo(mmdWin, prefix . videoName, fullPathStaging, encodingOptions)
encodingOptions.enableAudio := false
if (!success) {
Break
}
task.taskStatus := TaskData.STATUS_COMPLETED
WriteTaskData(task)
}
}
if(shouldProcess && task.taskType == TaskData.T_ENCODING) {
side := task.side
expectedFilename := fullPathStaging . "\" side . "_encoded_" . videoName . "." . Format("{:L}", job.finalEncodingFormat)
if(side != "F" && FileExist(expectedFilename)) {
FileDelete, %expectedFilename%
}
success := StartEncodingTask(job, task)
if(!success) {
Break
}
; Cleanup the renders as soon as they are merged, if enabled
if(side != "F" && userPrefs.deleteStagingFiles) {
CleanupStagingFiles(job, fullPathStaging, FILETYPE_RENDER, side)
} else if(side == "F" && userPrefs.deleteStagingFiles) {
CleanupStagingFiles(job, fullPathStaging, FILETYPE_ENCODED, "L")
CleanupStagingFiles(job, fullPathStaging, FILETYPE_ENCODED, "R")
}
}
if(task.taskType == TaskData.T_ENCODING && task.side == "F" && task.taskStatus == TaskData.STATUS_COMPLETED) {
finalEncodedVideoPath := task.taskResult
}
if(shouldProcess && task.taskType == TaskData.T_INJECT_METADATA && finalEncodedVideoPath) {
success := StartInjectMetadataTask(job, task, finalEncodedVideoPath)
if(!success) {
Break
}
}
if(task.taskType == TaskData.T_INJECT_METADATA && task.taskStatus == TaskData.STATUS_COMPLETED) {
injectedVideoPath := task.taskResult
}
if(shouldProcess && task.taskType == TaskData.T_UPLOAD && injectedVideoPath) {
StartUploadingTask(job, task, injectedVideoPath)
}
}
if (success) {
UpdateJobStatus(job, JobData.STATUS_COMPLETED)
}
Return success
}
RenderVideo(mmdWin, videoName, directory, encodingOptions) {
; TrayTip, % "Debug", % "RenderVideo " videoName " start", 1, 1
success := true
txtPid := 0
try {
renderStarted := -1
recWindowId := 0
; Get the PID to find the dialogs
WinGet, mmdPid, PID, ahk_id %mmdWin%
; Just to be sure the WinMenuSelectItem works, activate the MMD window first
; this way we ensure it is in a "non-minimized" state. See: https://www.autohotkey.com/docs/commands/WinMenuSelectItem.htm
WinActivate, ahk_id %mmdWin%
WinWaitActive, ahk_id %mmdWin%,, 120
if (ErrorLevel) {
success := false
}
if(success) {
; Activate another window before selecting the menu item
Run % "notepad.exe data\placeholder.txt",,, txtPid
WinWait, ahk_pid %txtPid%,, 120
if (ErrorLevel) {
success := false
}
}
if(success) {
WinActivate, ahk_pid %txtPid%
WinWaitActive, ahk_pid %txtPid%,, 120
if (ErrorLevel) {
success := false
}
}
if (success) {
WinMenuSelectItem, ahk_id %mmdWin%,, file, render to AVI
WinWait, output AVI ahk_pid %mmdPid%,, 120
WinGet, dialogId, ID
if (ErrorLevel) {
success := false
TrayTip, % "Couldn't render video", % "Video " videoName " could not be rendered.`nRender to AVI file dialog not found", 3, 3
}
}
if(success) {
ControlSetText, Edit1, %directory%\%videoName%, ahk_id %dialogId%
; ControlClick, Button2, ahk_id %dialogId%
ClickWithDelayChange("Button2", "ahk_id " dialogId)
WinWait, AVI ahk_pid %mmdPid%,, 120
WinGet, dialogId, ID
if (ErrorLevel) {
success := false
TrayTip, % "Couldn't render video", % "Video " videoName " could not be rendered.`nAVI-out dialog not found", 3, 3
}
}
if(success) {
ControlSetText, Edit3, % encodingOptions.fps, ahk_id %dialogId%
ControlSetText, Edit4, % encodingOptions.startFrame, ahk_id %dialogId%
ControlSetText, Edit5, % encodingOptions.endFrame, ahk_id %dialogId%
ControlGet, isWAV, Enabled, , Button1, ahk_id %dialogId%
if (isWAV) {
if (encodingOptions.enableAudio) {
Control, Check,, Button1, ahk_id %dialogId%
} else {
Control, UnCheck,, Button1, ahk_id %dialogId%
}
}
codecFound := false
for i, codec in encodingOptions.preferredCodecs {
Control, ChooseString, % codec, ComboBox1, ahk_id %dialogId%
ControlGet, selected, Choice,, ComboBox1, ahk_id %dialogId%
if(!ErrorLevel && InStr(selected, codec)) {
; Try the preferredCodecs until one succeeds
codecFound := true
Break
}
}
if (!codecFound) {
TrayTip, % "Couldn't find a preferred codec", % "No preferred codec was found to render " videoName, 3, 2
}
ClickWithDelayChange("Button5", "ahk_id " dialogId)
WinWait, ahk_class RecWindow ahk_pid %mmdPid%,, 120
if(ErrorLevel) {
success := false
TrayTip, % "Problem rendering", % "Rendering window for video " videoName " couldn't be found", 3, 3
} else {
WinGet, recWindowId, ID, ahk_class RecWindow ahk_pid %mmdPid%
if(recWindowId) {
renderStarted := A_TickCount
} else {
success := false
}
; TrayTip, % "Rendering started", % "Rendering " videoName "...", 3, 1
}
}
if(txtPid) {
; Kill the window we just created
WinKill, ahk_pid %txtPid%
}
if(success) {
timeBeforeCheckHung := 30 * 60 * 1000 ; 30 minutes in millis
periodOfGrace := 10 * 60 * 1000 ; 10 minutes
hungStart := -1
while(WinExist("ahk_id " recWindowId)) {
; Wait until the rendering window becomes hidden or is closed
renderEllapsed := A_TickCount - renderStarted
if(renderEllapsed > timeBeforeCheckHung) {
; After 30 minutes start checking if the MMD Render froze
; If it froze give it some time and if it's still frozen. Kill it
isHung := IsHungWindow(recWindowId)
if(IsHung == 0) {
; It has recovered within the period of grace. Keep it going
hungStart := -1
}
if(hungStart != -1) {
hungEllapsed := hungStart - A_TickCount
if(hungEllapsed > periodOfGrace) {
Process, Close, %mmdPid%
MsgBox, 0x10, % "Error", % "MMD froze during rendering and had to be killed"
ExitApp, 1
}
}else {
if(IsHung == 1) {
hungStart := A_TickCount
}
}
}
Sleep, 100
}
}
} catch {
success := false
TrayTip % "Error", % "Unknown error while rendering the video", 2, 3
if(txtPid) {
; Kill the window we just created
WinKill, ahk_pid %txtPid%
}
}
; TrayTip, % "Debug", % "RenderVideo " videoName " end", 1, 1
Return success
}
PrepareRenderVRSide(mmdWin, videoName, viewpointModel, side, eye) {
success := true
try {
if (viewpointModel) {
; Set the camera to follow the correct eye bone
eyeBone := "Viewpoint_" . eye
Control, ChooseString, %eyeBone%, ComboBox6, ahk_id %mmdWin%
ClickWithDelayChange("Button32", "ahk_id " mmdWin)
; Ensure EquirectangularX is selected in the accessory panel
Control, ChooseString, % "EquirectangularX", ComboBox7, ahk_id %mmdWin%
rotX := 0.0
rotY := 0.0
accRx := 0.0
accRy := 0.0
angle := 92
switch side
{
case VR_SIDE_LEFT:
rotY := 45.0
accRy := -45.0
case VR_SIDE_RIGHT:
rotY := -45.0
accRy := 45.0
case VR_SIDE_TOP:
rotY := 45.0
accRy := -45.0
rotX := -90.0
accRx := -90.0
angle := 103
case VR_SIDE_BOTTOM:
rotY := 45.0
accRy := -45.0
rotX := 90.0
accRx := 90.0
angle := 103
}
success := SetVRCameraParams(mmdWin, videoName, rotX, rotY, accRx, accRy, angle)
; MsgBox % "Params set for eye: " eye ", side: " side
} else {
; TODO: Implement static camera handling
; or maybe try to find and set the viewpointModel first
}
} catch {
success := false
TrayTip % "Error", % "Problem setting up the camera settings for VR", 2, 3
}
Return success
}
SetVRCameraParams(mmdWin, videoName, rotX, rotY, accRx, accRy, angle := 92) {
success := true
WinActivate, ahk_id %mmdWin%
WinWaitActive, ahk_id %mmdWin%,, 120
if(ErrorLevel) {
success := false
TrayTip % "Error", % "Problem setting camera parameters for " videoName, 3, 3
} else {
ControlFocus, Edit29, ahk_id %mmdWin%
ControlSetText, Edit29, %rotX%, ahk_id %mmdWin%
ControlFocus, Edit30, ahk_id %mmdWin%
ControlSetText, Edit30, %rotY%, ahk_id %mmdWin%
ControlFocus, Edit14, ahk_id %mmdWin%
ControlSetText, Edit14, %accRx%, ahk_id %mmdWin%
ControlFocus, Edit15, ahk_id %mmdWin%
ControlSetText, Edit15, %accRy%, ahk_id %mmdWin%
ControlFocus, Edit4, ahk_id %mmdWin%
ControlSetText, Edit4, %angle%, ahk_id %mmdWin%
ControlFocus, Edit15, ahk_id %mmdWin%
ClickWithDelayChange("Button32", "ahk_id " mmdWin)
ClickWithDelayChange("Button48", "ahk_id " mmdWin)
}
Return success
}
StartEncodingTask(job, ByRef task) {
success := true
try {
scriptPid := 0
scriptWin := 0
encodingStarted := -1
if (A_IsCompiled) {
; For the compiled exe we can get the PID directly from the Run command
Run % A_WorkingDir . "\scripts\encode_video.exe " task.jobId " " task.taskId,,, scriptPid
WinWait, ahk_pid %scriptPid%,, 10
encodingStarted := A_TickCount
WinGet, scriptWin, ID, ahk_pid %scriptPid%
} else {
toolsDir := A_WorkingDir
toolsDirClean := StrReplace(toolsDir, ":")
toolsDirBash := "/" . StrReplace(toolsDirClean, "\", "/")
pythonScript := toolsDirBash . "/scripts/python/encode_video.py"
Run % "C:\msys64\usr\bin\mintty.exe /bin/env MSYSTEM=MINGW64 /bin/bash -l """ toolsDirBash "/scripts/bash/python_launcher.sh"" " pythonScript " " task.jobId " " task.taskId
; When running the script in MinGW we need to lookup the cli window using a tag
exeLookup := "mintty.exe"
idSep := ":"
idTag := "[" . job.jobShortId . idSep . task.taskShortId . "]"
WinWait, %idTag% ahk_exe %exeLookup%,, 10
encodingStarted := A_TickCount
WinGet, scriptPid, PID, %idTag% ahk_exe %exeLookup%
WinGet, scriptWin, ID, ahk_pid %scriptPid%
}
timeBeforeCheckHung := 15 * 60 * 1000 ; 15 minutes in millis
periodOfGrace := 5 * 60 * 1000 ; 5 minutes
hungStart := -1
; Wait for the script to finish
oldStatus := task.taskStatus
while (oldStatus == task.taskStatus) {
encodingEllapsed := A_TickCount - encodingStarted
if (encodingEllapsed > timeBeforeCheckHung && scriptWin) {
; After 15 minutes start checking if the process froze
isHung := IsHungWindow(scriptWin)
if(IsHung == 0) {
; It has recovered within the period of grace. Keep it going
hungStart := -1
}
if(hungStart != -1) {
hungEllapsed := hungStart - A_TickCount
if(hungEllapsed > periodOfGrace) {
Process, Close, %scriptPid%
MsgBox, 0x10, % "Error", % "The encoding script froze and had to be killed"
ExitApp, 1
}
} else {
if(IsHung == 1) {
hungStart := A_TickCount
}
}
}
PullTaskStatus(task)
Sleep, 100
}
if(task.taskStatus == TaskData.STATUS_ERROR) {
success := false
TrayTip % "Error", % "Encoding task finished with errors", 2, 3
}
} catch {
success := false
TrayTip % "Error", % "Unknown error during encoding", 2, 3
}
Return success
}
StartInjectMetadataTask(ByRef job, ByRef task, videoFile) {
success := true
try {
scriptPid := 0
scriptWin := 0
taskStarted := -1
if (A_IsCompiled) {
; For the compiled exe we can get the PID directly from the Run command
Run % A_WorkingDir . "\scripts\inject_metadata.exe " task.jobId " " task.taskId " """ videoFile """",,, scriptPid
WinWait, ahk_pid %scriptPid%,, 10
taskStarted := A_TickCount
WinGet, scriptWin, ID, ahk_pid %scriptPid%
} else {
toolsDir := A_WorkingDir
toolsDirClean := StrReplace(toolsDir, ":")
toolsDirBash := "/" . StrReplace(toolsDirClean, "\", "/")
pythonScript := toolsDirBash . "/scripts/python/inject_metadata.py"
Run % "C:\msys64\usr\bin\mintty.exe /bin/env MSYSTEM=MINGW64 /bin/bash -l """ toolsDirBash "/scripts/bash/python_launcher.sh"" " pythonScript " " task.jobId " " task.taskId " '" videoFile "'"
; When running the script in MinGW we need to lookup the cli window using a tag
exeLookup := "mintty.exe"
idSep := ":"
idTag := "[" . job.jobShortId . idSep . task.taskShortId . "]"
WinWait, %idTag% ahk_exe %exeLookup%,, 10
taskStarted := A_TickCount
WinGet, scriptPid, PID, %idTag% ahk_exe %exeLookup%
WinGet, scriptWin, ID, ahk_pid %scriptPid%
}
timeBeforeCheckHung := 10 * 60 * 1000 ; 10 minutes in millis
periodOfGrace := 5 * 60 * 1000 ; 5 minute
hungStart := -1
; Wait for the script to finish
oldStatus := task.taskStatus
while (oldStatus == task.taskStatus) {
taskEllapsed := A_TickCount - taskStarted
if (taskEllapsed > timeBeforeCheckHung && scriptWin) {
; After 15 minutes start checking if the process froze
isHung := IsHungWindow(scriptWin)
if(IsHung == 0) {
; It has recovered within the period of grace. Keep it going
hungStart := -1
}
if(hungStart != -1) {
hungEllapsed := hungStart - A_TickCount
if(hungEllapsed > periodOfGrace) {
Process, Close, %scriptPid%
MsgBox, 0x10, % "Error", % "The encoding script froze and had to be killed"
ExitApp, 1
}
} else {
if(IsHung == 1) {
hungStart := A_TickCount
}
}
}
PullTaskStatus(task)
Sleep, 100
}
if(task.taskStatus == TaskData.STATUS_ERROR) {
success := false
TrayTip % "Error", % "Encoding task finished with errors", 2, 3
}
} catch {
success := false
TrayTip % "Error", % "Unknown error while injecting the metadata", 2, 3
}
Return success
}
StartUploadingTask(ByRef job, ByRef task, videoFile) {
success := true
try {
scriptPid := 0
scriptWin := 0
taskStarted := -1
if (A_IsCompiled) {