mirror of
https://github.com/Akascape/Datamosher-Pro.git
synced 2025-12-05 15:59:59 +01:00
added new UI for python version
Now python users can also enjoy the easy UI
This commit is contained in:
BIN
Python Version/Assets/Icons/Logo.png
Normal file
BIN
Python Version/Assets/Icons/Logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 95 KiB |
BIN
Python Version/Assets/Icons/Program_icon.png
Normal file
BIN
Python Version/Assets/Icons/Program_icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 372 KiB |
BIN
Python Version/Assets/Icons/right_icon.png
Normal file
BIN
Python Version/Assets/Icons/right_icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.8 KiB |
BIN
Python Version/Assets/Icons/settings.png
Normal file
BIN
Python Version/Assets/Icons/settings.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 9.8 KiB |
BIN
Python Version/Assets/Icons/video_icon.png
Normal file
BIN
Python Version/Assets/Icons/video_icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.4 KiB |
BIN
Python Version/Assets/thumbnail_cache/offline_image.png
Normal file
BIN
Python Version/Assets/thumbnail_cache/offline_image.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 178 KiB |
1
Python Version/Assets/version/VERSIONPY.txt
Normal file
1
Python Version/Assets/version/VERSIONPY.txt
Normal file
@@ -0,0 +1 @@
|
||||
1.8
|
||||
154
Python Version/DatamoshLib/FFG_effects/basic_modes.py
Normal file
154
Python Version/DatamoshLib/FFG_effects/basic_modes.py
Normal file
@@ -0,0 +1,154 @@
|
||||
#Author: Akash Bora
|
||||
import os, shutil, subprocess, random, json
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
DIRPATH = Path(os.path.dirname(os.path.realpath(__file__)))
|
||||
ffgac=str(DIRPATH.parent.parent).replace(os.sep, '/')+"/FFglitch/ffgac"
|
||||
ffedit=str(DIRPATH.parent.parent).replace(os.sep, '/')+"/FFglitch/ffedit"
|
||||
|
||||
def library(input_video, output, mode, extract_from="", fluidity=0, size=0, s=0, e=0, vh=0, gop=1000):
|
||||
def get_vectors(input_video):
|
||||
subprocess.call(f'"{ffgac}" -i "{input_video}" -an -mpv_flags +nopimb+forcemv -qscale:v 0 -g "{gop}"' +
|
||||
' -vcodec mpeg2video -f rawvideo -y tmp.mpg', shell=True)
|
||||
subprocess.call(f'"{ffedit}" -i tmp.mpg -f mv:0 -e tmp.json', shell=True)
|
||||
os.remove('tmp.mpg')
|
||||
f = open('tmp.json', 'r')
|
||||
raw_data = json.load(f)
|
||||
f.close()
|
||||
os.remove('tmp.json')
|
||||
frames = raw_data['streams'][0]['frames']
|
||||
vectors = []
|
||||
for frame in frames:
|
||||
try:
|
||||
vectors.append(frame['mv']['forward'])
|
||||
except:
|
||||
vectors.append([])
|
||||
return vectors
|
||||
def apply_vectors(vectors, input_video, output_video, method='add'):
|
||||
subprocess.call(f'"{ffgac}" -i "{input_video}" -an -mpv_flags +nopimb+forcemv -qscale:v 0 -g "{gop}"' +
|
||||
' -vcodec mpeg2video -f rawvideo -y tmp.mpg', shell=True)
|
||||
to_add = '+' if method == 'add' else ''
|
||||
script_path = 'apply_vectors.js'
|
||||
script_contents = '''
|
||||
var vectors = [];
|
||||
var n_frames = 0;
|
||||
function glitch_frame(frame) {
|
||||
let fwd_mvs = frame["mv"]["forward"];
|
||||
if (!fwd_mvs || !vectors[n_frames]) {
|
||||
n_frames++;
|
||||
return;
|
||||
}
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ ) {
|
||||
let row = fwd_mvs[i];
|
||||
for ( let j = 0; j < row.length; j++ ) {
|
||||
let mv = row[j];
|
||||
try {
|
||||
mv[0] ''' + to_add + '''= vectors[n_frames][i][j][0];
|
||||
mv[1] ''' + to_add + '''= vectors[n_frames][i][j][1];
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
n_frames++;
|
||||
}
|
||||
'''
|
||||
with open(script_path, 'w') as f:
|
||||
f.write(script_contents.replace('var vectors = [];', f'var vectors = {json.dumps(vectors)};'))
|
||||
subprocess.call(f'"{ffedit}" -i tmp.mpg -f mv -s "{script_path}" -o "{output_video}"', shell=True)
|
||||
os.remove('apply_vectors.js')
|
||||
os.remove('tmp.mpg')
|
||||
def shuffle(output):
|
||||
if os.path.isdir("cache"):
|
||||
shutil.rmtree("cache")
|
||||
os.mkdir("cache")
|
||||
base=os.path.basename(input_video)
|
||||
fin="cache/"+base[:-4]+".mpg"
|
||||
subprocess.call(f'"{ffgac}" -i "{input_video}" -an -vcodec mpeg2video -f rawvideo -mpv_flags +nopimb -qscale:v 6 -r 30 -g "{gop}" -y "{fin}"')
|
||||
os.mkdir("cache/raws")
|
||||
framelist=[]
|
||||
subprocess.call(f'"{ffgac}" -i "{fin}" -vcodec copy cache/raws/frames_%04d.raw')
|
||||
frames=os.listdir("cache/raws")
|
||||
siz=size
|
||||
framelist.extend(frames)
|
||||
chunked_list=[]
|
||||
chunk_size=siz
|
||||
for i in range(0, len(framelist), chunk_size):
|
||||
chunked_list.append(framelist[i:i+chunk_size])
|
||||
random.shuffle(chunked_list)
|
||||
framelist.clear()
|
||||
for k in frames[0:siz]:
|
||||
framelist.append(k)
|
||||
for i in chunked_list:
|
||||
for j in i:
|
||||
if not j in framelist:
|
||||
framelist.append(j)
|
||||
out_data = b''
|
||||
for fn in framelist:
|
||||
with open("cache/raws/"+fn, 'rb') as fp:
|
||||
out_data += fp.read()
|
||||
with open(output, 'wb+') as fp:
|
||||
fp.write(out_data)
|
||||
fp.close()
|
||||
shutil.rmtree("cache")
|
||||
def rise(output):
|
||||
if os.path.isdir("cache"):
|
||||
shutil.rmtree("cache")
|
||||
os.mkdir("cache")
|
||||
base=os.path.basename(input_video)
|
||||
fin="cache/"+base[:-4]+".mpg"
|
||||
qua=''
|
||||
subprocess.call(f'"{ffgac}" -i "{input_video}" -an -vcodec mpeg2video -f rawvideo -mpv_flags +nopimb -qscale:v 6 -r 30 -g "{gop}" -y "{fin}"')
|
||||
os.mkdir("cache/raws")
|
||||
framelist=[]
|
||||
subprocess.call(f'"{ffgac}" -i "{fin}" -vcodec copy cache/raws/frames_%04d.raw')
|
||||
kil=e
|
||||
po=s
|
||||
if po==0:
|
||||
po=1
|
||||
frames=os.listdir("cache/raws")
|
||||
for i in frames[po:(po+kil)]:
|
||||
os.remove("cache/raws/"+i)
|
||||
frames.clear()
|
||||
frames=os.listdir("cache/raws")
|
||||
framelist.extend(frames)
|
||||
out_data = b''
|
||||
for fn in framelist:
|
||||
with open("cache/raws/"+fn, 'rb') as fp:
|
||||
out_data += fp.read()
|
||||
with open(output, 'wb') as fp:
|
||||
fp.write(out_data)
|
||||
fp.close()
|
||||
shutil.rmtree("cache")
|
||||
def average(frames):
|
||||
if not frames:
|
||||
return []
|
||||
return np.mean(np.array([x for x in frames if x != []]), axis=0).tolist()
|
||||
def fluid(frames):
|
||||
average_length = fluidity
|
||||
if average_length==1:
|
||||
average_length=2
|
||||
return [average(frames[i + 1 - average_length: i + 1]) for i in range(len(frames))]
|
||||
def movement(frames):
|
||||
for frame in frames:
|
||||
if not frame:
|
||||
continue
|
||||
for row in frame:
|
||||
for col in row:
|
||||
col[vh] = 0
|
||||
return frames
|
||||
if(mode==1):
|
||||
transfer_to=input_video
|
||||
vectors = []
|
||||
if extract_from:
|
||||
vectors = get_vectors(extract_from)
|
||||
if transfer_to == '':
|
||||
with open(output, 'w') as f:
|
||||
json.dump(vectors, f)
|
||||
apply_vectors(vectors, transfer_to, output)
|
||||
elif(mode==2):
|
||||
apply_vectors(movement(get_vectors(input_video)), input_video, output, method='')
|
||||
elif(mode==3):
|
||||
apply_vectors(fluid(get_vectors(input_video)), input_video, output, method='')
|
||||
elif(mode==4):
|
||||
shuffle(output)
|
||||
elif(mode==5):
|
||||
rise(output)
|
||||
15
Python Version/DatamoshLib/FFG_effects/external_script.py
Normal file
15
Python Version/DatamoshLib/FFG_effects/external_script.py
Normal file
@@ -0,0 +1,15 @@
|
||||
#Author: Akash Bora
|
||||
import os, subprocess
|
||||
from pathlib import Path
|
||||
DIRPATH = Path(os.path.dirname(os.path.realpath(__file__)))
|
||||
ffgac=str(DIRPATH.parent.parent).replace(os.sep, '/')+"/FFglitch/ffgac"
|
||||
ffedit=str(DIRPATH.parent.parent).replace(os.sep, '/')+"/FFglitch/ffedit"
|
||||
def mosh(input_video, output_video, mode, effect='', scriptfile='', gop=1000):
|
||||
if mode==1:
|
||||
script_path=scriptfile
|
||||
elif mode==2:
|
||||
script_path=str(DIRPATH).replace(os.sep, '/')+"/jscripts/"+effect+".js"
|
||||
subprocess.call(f'"{ffgac}" -i "{input_video}" -an -mpv_flags +nopimb+forcemv -qscale:v 0 -b:v 20M -minrate 20M -maxrate 20M -bufsize 2M -g "{gop}"' +
|
||||
' -vcodec mpeg2video -f rawvideo -y tmp.mpg', shell=True)
|
||||
subprocess.call(f'"{ffedit}" -i tmp.mpg -f mv -s "{script_path}" -o "{output_video}"', shell=True)
|
||||
os.remove('tmp.mpg')
|
||||
75
Python Version/DatamoshLib/FFG_effects/jscripts/Buffer.js
Normal file
75
Python Version/DatamoshLib/FFG_effects/jscripts/Buffer.js
Normal file
@@ -0,0 +1,75 @@
|
||||
// dd_ring_buffer.js
|
||||
// works kinda like an audio delay
|
||||
// stacks the previous n frames into a buffer
|
||||
|
||||
// global variable holding forward motion vectors from previous frames
|
||||
var prev_fwd_mvs = [ ];
|
||||
|
||||
// change these values to use a smaller or greater number of frames to
|
||||
// perform the average of motion vectors
|
||||
|
||||
// try making the delay long enough to overlap an edit in the content ...
|
||||
var delay = 10;
|
||||
// divisor controls "feedback" ... or "feedforward" which ever is a better description ...
|
||||
var feedback = 0.5; // a number between 0.000001 and .... yeah - controls how much of the buffered mv gets into the next pass
|
||||
|
||||
var divisor = 1.0/feedback;
|
||||
|
||||
function glitch_frame(frame)
|
||||
{
|
||||
// bail out if we have no motion vectors
|
||||
let mvs = frame["mv"];
|
||||
if ( !mvs )
|
||||
return;
|
||||
// bail out if we have no forward motion vectors
|
||||
let fwd_mvs = mvs["forward"];
|
||||
if ( !fwd_mvs )
|
||||
return;
|
||||
|
||||
// update variable holding forward motion vectors from previous
|
||||
// frames. note that we perform a deep copy of the clean motion
|
||||
// vector values before modifying them.
|
||||
let json_str = JSON.stringify(fwd_mvs);
|
||||
let deep_copy = JSON.parse(json_str);
|
||||
// push to the end of array
|
||||
prev_fwd_mvs.push(deep_copy);
|
||||
// drop values from earliest frames to always keep the same tail
|
||||
// length
|
||||
if ( prev_fwd_mvs.length > delay )
|
||||
prev_fwd_mvs = prev_fwd_mvs.slice(1);
|
||||
|
||||
// bail out if we still don't have enough frames
|
||||
if ( prev_fwd_mvs.length != delay )
|
||||
return;
|
||||
|
||||
// replace all motion vectors of current frame with an average
|
||||
// of the motion vectors from the previous 10 frames
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ )
|
||||
{
|
||||
// loop through all rows
|
||||
let row = fwd_mvs[i];
|
||||
let delay_row = prev_fwd_mvs[0][i];
|
||||
let insert_row = prev_fwd_mvs[delay-1][i];
|
||||
|
||||
for ( let j = 0; j < row.length; j++ )
|
||||
{
|
||||
// loop through all macroblocks
|
||||
let mv = row[j];
|
||||
let dmv = delay_row[j];
|
||||
let imv = insert_row[j];
|
||||
// THIS IS WHERE THE MAGIC HAPPENS
|
||||
|
||||
// temp copy of the incoming vectors
|
||||
let x = mv[0];
|
||||
let y = mv[1];
|
||||
// pull their replacements out of the buffer
|
||||
mv[0] = dmv[0];
|
||||
mv[1] = dmv[1];
|
||||
// feedback the 'old' with the 'new' for next time
|
||||
imv[0] = (dmv[0] / divisor) + x;
|
||||
imv[1] = (dmv[1] / divisor) + y;
|
||||
// rinse and repeat
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
71
Python Version/DatamoshLib/FFG_effects/jscripts/Delay.js
Normal file
71
Python Version/DatamoshLib/FFG_effects/jscripts/Delay.js
Normal file
@@ -0,0 +1,71 @@
|
||||
// dd_delay.js
|
||||
// works kinda like an audio delay
|
||||
// stacks the previous n frames into a buffer
|
||||
|
||||
// global variable holding forward motion vectors from previous frames
|
||||
var prev_fwd_mvs = [ ];
|
||||
|
||||
// change these values to use a smaller or greater number of frames to
|
||||
// perform the average of motion vectors
|
||||
|
||||
// try making the delay long enough to overlap an edit in the content ...
|
||||
var delay = 20;
|
||||
|
||||
function glitch_frame(frame)
|
||||
{
|
||||
// bail out if we have no motion vectors
|
||||
let mvs = frame["mv"];
|
||||
if ( !mvs )
|
||||
return;
|
||||
// bail out if we have no forward motion vectors
|
||||
let fwd_mvs = mvs["forward"];
|
||||
if ( !fwd_mvs )
|
||||
return;
|
||||
|
||||
// update variable holding forward motion vectors from previous
|
||||
// frames. note that we perform a deep copy of the clean motion
|
||||
// vector values before modifying them.
|
||||
let json_str = JSON.stringify(fwd_mvs);
|
||||
let deep_copy = JSON.parse(json_str);
|
||||
// push to the end of array
|
||||
prev_fwd_mvs.push(deep_copy);
|
||||
// drop values from earliest frames to always keep the same tail
|
||||
// length
|
||||
if ( prev_fwd_mvs.length > delay )
|
||||
prev_fwd_mvs = prev_fwd_mvs.slice(1);
|
||||
|
||||
// bail out if we still don't have enough frames
|
||||
if ( prev_fwd_mvs.length != delay )
|
||||
return;
|
||||
|
||||
// replace all motion vectors of current frame with an average
|
||||
// of the motion vectors from the previous 10 frames
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ )
|
||||
{
|
||||
// loop through all rows
|
||||
let row = fwd_mvs[i];
|
||||
let delay_row = prev_fwd_mvs[0][i];
|
||||
let insert_row = prev_fwd_mvs[delay-1][i];
|
||||
|
||||
for ( let j = 0; j < row.length; j++ )
|
||||
{
|
||||
// loop through all macroblocks
|
||||
let mv = row[j];
|
||||
let dmv = delay_row[j];
|
||||
let imv = insert_row[j];
|
||||
// THIS IS WHERE THE MAGIC HAPPENS
|
||||
|
||||
// temp copy of the incoming vectors
|
||||
let x = mv[0];
|
||||
let y = mv[1];
|
||||
// pull their replacements out of the buffer
|
||||
mv[0] = dmv[0];
|
||||
mv[1] = dmv[1];
|
||||
// feedback the 'old' with the 'new' for next time
|
||||
imv[0] = x;
|
||||
imv[1] = y;
|
||||
// rinse and repeat
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// dd_RandomDamage(invertRandomN).js
|
||||
// invert x and y component of mv for random number of frames if threshold met for frame
|
||||
|
||||
let threshold = 95;
|
||||
var TRIGGERED = 0;
|
||||
var nFrames = 10;
|
||||
var frameCount = 0;
|
||||
var MAGNITUDE = 20;
|
||||
|
||||
function glitch_frame(frame)
|
||||
{
|
||||
|
||||
var do_or_not = Math.random() * 100;
|
||||
if(do_or_not > threshold){
|
||||
if(TRIGGERED > 0){
|
||||
|
||||
}else{
|
||||
TRIGGERED = 1;
|
||||
frameCount = 0;
|
||||
nFrames = Math.random() * MAGNITUDE;
|
||||
}
|
||||
}
|
||||
// only do the glitch if our random number crosses the threshold
|
||||
if(TRIGGERED > 0 & frameCount <= nFrames){
|
||||
frameCount++;
|
||||
|
||||
// bail out if we have no motion vectors
|
||||
let mvs = frame["mv"];
|
||||
if ( !mvs )
|
||||
return;
|
||||
// bail out if we have no forward motion vectors
|
||||
let fwd_mvs = mvs["forward"];
|
||||
if ( !fwd_mvs )
|
||||
return;
|
||||
|
||||
var M_H = fwd_mvs.length/2;
|
||||
// clear horizontal element of all motion vectors
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ )
|
||||
{
|
||||
// loop through all rows
|
||||
let row = fwd_mvs[i];
|
||||
var M_W = row.length/2;
|
||||
|
||||
for ( let j = 0; j < row.length; j++ )
|
||||
{
|
||||
// loop through all macroblocks
|
||||
let mv = row[j];
|
||||
|
||||
// THIS IS WHERE THE MAGIC HAPPENS
|
||||
// STOP XY
|
||||
mv[0] = 0 - mv[0];
|
||||
mv[1] = 0 - mv[1];
|
||||
}
|
||||
}
|
||||
}else{
|
||||
TRIGGERED = 0;
|
||||
}
|
||||
}
|
||||
52
Python Version/DatamoshLib/FFG_effects/jscripts/Mirror.js
Normal file
52
Python Version/DatamoshLib/FFG_effects/jscripts/Mirror.js
Normal file
@@ -0,0 +1,52 @@
|
||||
// dd_mirror_X.js
|
||||
|
||||
// clean buffer :
|
||||
var buffer = [ ];
|
||||
|
||||
var ZOOM = -20;
|
||||
|
||||
function glitch_frame(frame)
|
||||
{
|
||||
// bail out if we have no motion vectors
|
||||
let mvs = frame["mv"];
|
||||
if ( !mvs )
|
||||
return;
|
||||
// bail out if we have no forward motion vectors
|
||||
let fwd_mvs = mvs["forward"];
|
||||
if ( !fwd_mvs )
|
||||
return;
|
||||
|
||||
// note that we perform a deep copy of the clean motion
|
||||
// vector values before modifying them.
|
||||
let json_str = JSON.stringify(fwd_mvs);
|
||||
let deep_copy = JSON.parse(json_str);
|
||||
// stick em in the buffer
|
||||
buffer = deep_copy;
|
||||
|
||||
var M_H = fwd_mvs.length/2;
|
||||
// VERTICALLY
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ )
|
||||
{
|
||||
|
||||
// loop through all rows
|
||||
|
||||
let row = fwd_mvs[i];
|
||||
var row2 = buffer[i];
|
||||
//var row2 = fwd_mvs[(fwd_mvs.length-1)-i];
|
||||
|
||||
var M_W = row.length/2;
|
||||
|
||||
// HORIZONTALLY
|
||||
for ( let j = 0; j < row.length; j++ )
|
||||
{
|
||||
// loop through all macroblocks
|
||||
let mv = row[j];
|
||||
var mv2 = row2[(row.length - 1) - j];
|
||||
// THIS IS WHERE THE MAGIC HAPPENS
|
||||
//if(i>M_W){
|
||||
mv[0] = 0-mv2[0];
|
||||
mv[1] = mv2[1];
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
67
Python Version/DatamoshLib/FFG_effects/jscripts/Noise.js
Normal file
67
Python Version/DatamoshLib/FFG_effects/jscripts/Noise.js
Normal file
@@ -0,0 +1,67 @@
|
||||
// dd_MultiplySlowest_50.js
|
||||
// Multiply slowest moving mv's
|
||||
var LARGEST = 0;
|
||||
var SOME_PERCENTAGE = 0.5;
|
||||
var MULTIPLE = 10;
|
||||
|
||||
// global variable holding forward motion vectors from previous frames
|
||||
var prev_fwd_mvs = [ ];
|
||||
|
||||
// change this value to use a smaller or greater number of frmes to average
|
||||
var tail_length = 20;
|
||||
|
||||
function glitch_frame(frame)
|
||||
{
|
||||
LARGEST = 0;
|
||||
// bail out if we have no motion vectors
|
||||
let mvs = frame["mv"];
|
||||
if ( !mvs )
|
||||
return;
|
||||
// bail out if we have no forward motion vectors
|
||||
let fwd_mvs = mvs["forward"];
|
||||
if ( !fwd_mvs )
|
||||
return;
|
||||
|
||||
// 1st loop - find the fastest mv
|
||||
// this ends-up in LARGEST as the square of the hypotenuse (mv[0]*mv[0]) + (mv[1]*mv[1])
|
||||
let W = fwd_mvs.length;
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ )
|
||||
{
|
||||
let row = fwd_mvs[i];
|
||||
// rows
|
||||
let H = row.length;
|
||||
for ( let j = 0; j < row.length; j++ )
|
||||
{
|
||||
// loop through all macroblocks
|
||||
let mv = row[j];
|
||||
|
||||
// THIS IS WHERE THE MEASUREMENT HAPPENS
|
||||
var this_mv = (mv[0] * mv[0])+(mv[1] * mv[1]);
|
||||
if ( this_mv > LARGEST){
|
||||
LARGEST = this_mv;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// then find those mv's which are bigger than SOME_PERCENTAGE of LARGEST
|
||||
// and then replace them with the average mv from the last n frames
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ )
|
||||
{
|
||||
let row = fwd_mvs[i];
|
||||
// rows
|
||||
let H = row.length;
|
||||
for ( let j = 0; j < row.length; j++ )
|
||||
{
|
||||
// loop through all macroblocks
|
||||
let mv = row[j];
|
||||
|
||||
// THIS IS WHERE THE MAGIC HAPPENS
|
||||
var this_mv = (mv[0] * mv[0])+(mv[1] * mv[1]);
|
||||
if (this_mv < (LARGEST * SOME_PERCENTAGE)){
|
||||
|
||||
mv[0] = mv[0] * MULTIPLE;
|
||||
mv[1] = mv[1] * MULTIPLE;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
37
Python Version/DatamoshLib/FFG_effects/jscripts/Shear.js
Normal file
37
Python Version/DatamoshLib/FFG_effects/jscripts/Shear.js
Normal file
@@ -0,0 +1,37 @@
|
||||
// dd_sheer.js
|
||||
|
||||
var ZOOM = -20;
|
||||
|
||||
function glitch_frame(frame)
|
||||
{
|
||||
// bail out if we have no motion vectors
|
||||
let mvs = frame["mv"];
|
||||
if ( !mvs )
|
||||
return;
|
||||
// bail out if we have no forward motion vectors
|
||||
let fwd_mvs = mvs["forward"];
|
||||
if ( !fwd_mvs )
|
||||
return;
|
||||
|
||||
var M_H = fwd_mvs.length/2;
|
||||
// clear horizontal element of all motion vectors
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ )
|
||||
{
|
||||
|
||||
// loop through all rows
|
||||
|
||||
let row = fwd_mvs[i];
|
||||
var M_W = row.length/2;
|
||||
for ( let j = 0; j < row.length; j++ )
|
||||
{
|
||||
// loop through all macroblocks
|
||||
let mv = row[j];
|
||||
|
||||
// THIS IS WHERE THE MAGIC HAPPENS
|
||||
//if(i>M_W){
|
||||
mv[0] = mv[0] + ((i - M_W) / 100)*ZOOM;
|
||||
mv[1] = mv[1] + ((j - M_H) / 100)*ZOOM;
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
74
Python Version/DatamoshLib/FFG_effects/jscripts/Shift.js
Normal file
74
Python Version/DatamoshLib/FFG_effects/jscripts/Shift.js
Normal file
@@ -0,0 +1,74 @@
|
||||
// dd_RandomDamage(antiGrav).js
|
||||
// anitgravityify if threshold met for frame
|
||||
|
||||
let threshold = 98;
|
||||
// global variable holding forward motion vectors from previous frames
|
||||
var old_mvs = [ ];
|
||||
// a variable for gravity
|
||||
var rt = 0;
|
||||
var gravity = 0
|
||||
var orig_gravity = 5;
|
||||
var TRIGGERED = 0;
|
||||
var frameCount = 10;
|
||||
var count = 0;
|
||||
|
||||
function glitch_frame(frame)
|
||||
{
|
||||
var do_or_not = Math.random() * 100;
|
||||
// only do the glitch if our random number crosses the threshold
|
||||
if(do_or_not > threshold | TRIGGERED == 1){
|
||||
if(TRIGGERED == 0){
|
||||
gravity = orig_gravity;
|
||||
TRIGGERED = 1;
|
||||
rt = 0;
|
||||
}
|
||||
// bail out if we have no motion vectors
|
||||
let mvs = frame["mv"];
|
||||
if ( !mvs )
|
||||
return;
|
||||
// bail out if we have no forward motion vectors
|
||||
let fwd_mvs = mvs["forward"];
|
||||
if ( !fwd_mvs )
|
||||
return;
|
||||
|
||||
// buffer first set of vectors. . .
|
||||
if(rt == 0){
|
||||
let json_str = JSON.stringify(fwd_mvs);
|
||||
let deep_copy = JSON.parse(json_str);
|
||||
// push to the end of array
|
||||
old_mvs[0] = (deep_copy);
|
||||
rt = 1;
|
||||
}
|
||||
|
||||
// clear horizontal element of all motion vectors
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ )
|
||||
{
|
||||
// loop through all rows
|
||||
let row = fwd_mvs[i];
|
||||
let old_row = old_mvs[0][i];
|
||||
for ( let j = 0; j < row.length; j++ )
|
||||
{
|
||||
// loop through all macroblocks
|
||||
let mv = row[j];
|
||||
let omv = old_row[j];
|
||||
// THIS IS WHERE THE MAGIC HAPPENS
|
||||
|
||||
mv[0] = mv[0];
|
||||
//if(mv[1] < 0){
|
||||
var nmv = mv[1];
|
||||
mv[1] = omv[1];
|
||||
omv[1] = nmv + omv[1] + gravity;
|
||||
//gravity++;
|
||||
//}else{
|
||||
// mv[1] = mv[1];
|
||||
//}
|
||||
|
||||
}
|
||||
}
|
||||
count++;
|
||||
if(count >= frameCount){
|
||||
TRIGGERED = 0;
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
38
Python Version/DatamoshLib/FFG_effects/jscripts/Sink.js
Normal file
38
Python Version/DatamoshLib/FFG_effects/jscripts/Sink.js
Normal file
@@ -0,0 +1,38 @@
|
||||
// dd_zero.js
|
||||
// only fuck things up if mv > movement_threshold
|
||||
var movement_threshold = 3;
|
||||
function glitch_frame(frame)
|
||||
{
|
||||
// bail out if we have no motion vectors
|
||||
let mvs = frame["mv"];
|
||||
if ( !mvs )
|
||||
return;
|
||||
// bail out if we have no forward motion vectors
|
||||
let fwd_mvs = mvs["forward"];
|
||||
if ( !fwd_mvs )
|
||||
return;
|
||||
|
||||
// columns
|
||||
let W = fwd_mvs.length;
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ )
|
||||
{
|
||||
|
||||
let row = fwd_mvs[i];
|
||||
|
||||
// rows
|
||||
let H = row.length;
|
||||
for ( let j = 0; j < row.length; j++ )
|
||||
{
|
||||
// loop through all macroblocks
|
||||
let mv = row[j];
|
||||
|
||||
// THIS IS WHERE THE MAGIC HAPPENS
|
||||
if ( (mv[0] * mv[0])+(mv[1] * mv[1]) > movement_threshold*movement_threshold){
|
||||
//mv[0] = Math.sin(i/W*Math.PI*2)*mv[0];
|
||||
//mv[1] = Math.cos(j/H*Math.PI*2)*mv[1];
|
||||
mv[0] = 0;//mv[0] * 10;
|
||||
mv[1] = 0;//mv[1] * 10;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
37
Python Version/DatamoshLib/FFG_effects/jscripts/Slam Zoom.js
Normal file
37
Python Version/DatamoshLib/FFG_effects/jscripts/Slam Zoom.js
Normal file
@@ -0,0 +1,37 @@
|
||||
// dd_slam_zoom_in.js
|
||||
|
||||
var ZOOM = 20;
|
||||
|
||||
function glitch_frame(frame)
|
||||
{
|
||||
// bail out if we have no motion vectors
|
||||
let mvs = frame["mv"];
|
||||
if ( !mvs )
|
||||
return;
|
||||
// bail out if we have no forward motion vectors
|
||||
let fwd_mvs = mvs["forward"];
|
||||
if ( !fwd_mvs )
|
||||
return;
|
||||
|
||||
var M_H = fwd_mvs.length/2;
|
||||
// clear horizontal element of all motion vectors
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ )
|
||||
{
|
||||
|
||||
// loop through all rows
|
||||
|
||||
let row = fwd_mvs[i];
|
||||
var M_W = row.length/2;
|
||||
for ( let j = 0; j < row.length; j++ )
|
||||
{
|
||||
// loop through all macroblocks
|
||||
let mv = row[j];
|
||||
|
||||
// THIS IS WHERE THE MAGIC HAPPENS
|
||||
//if(i>M_W){
|
||||
mv[0] = ((M_W - j) / 100)*ZOOM;
|
||||
mv[1] = ((M_H - i) / 100)*ZOOM;
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
68
Python Version/DatamoshLib/FFG_effects/jscripts/Slice.js
Normal file
68
Python Version/DatamoshLib/FFG_effects/jscripts/Slice.js
Normal file
@@ -0,0 +1,68 @@
|
||||
// dd_RandomDamage(progZoom).js
|
||||
// progressive Zoom x and y components of mv if threshold met for frame
|
||||
|
||||
let threshold = 95;
|
||||
|
||||
var ZOOM = 0;
|
||||
var doZOOM = 0;
|
||||
var TRIGGERED = 0;
|
||||
var nFrames = 5;
|
||||
var frameCount = 0;
|
||||
|
||||
function glitch_frame(frame)
|
||||
{
|
||||
|
||||
var do_or_not = Math.random() * 100;
|
||||
if(do_or_not > threshold){
|
||||
if(TRIGGERED > 0){
|
||||
|
||||
}else{
|
||||
TRIGGERED = 1;
|
||||
frameCount = 0;
|
||||
ZOOM = 0;
|
||||
}
|
||||
}
|
||||
// only do the glitch if our random number crosses the threshold
|
||||
if(TRIGGERED > 0 & frameCount <= nFrames){
|
||||
frameCount++;
|
||||
ZOOM+= 10
|
||||
|
||||
var do_dir = Math.random() * 100;
|
||||
if(do_dir > 50){
|
||||
doZOOM = 0 - ZOOM;
|
||||
}else{
|
||||
doZOOM = ZOOM
|
||||
}
|
||||
// bail out if we have no motion vectors
|
||||
let mvs = frame["mv"];
|
||||
if ( !mvs )
|
||||
return;
|
||||
// bail out if we have no forward motion vectors
|
||||
let fwd_mvs = mvs["forward"];
|
||||
if ( !fwd_mvs )
|
||||
return;
|
||||
|
||||
var M_H = fwd_mvs.length/2;
|
||||
// clear horizontal element of all motion vectors
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ )
|
||||
{
|
||||
// loop through all rows
|
||||
let row = fwd_mvs[i];
|
||||
var M_W = row.length/2;
|
||||
|
||||
for ( let j = 0; j < row.length; j++ )
|
||||
{
|
||||
// loop through all macroblocks
|
||||
let mv = row[j];
|
||||
|
||||
// THIS IS WHERE THE MAGIC HAPPENS
|
||||
// ZOOM X & Y VECTORS
|
||||
mv[0] = mv[0] + ((M_W - j) / 10)*doZOOM;
|
||||
mv[1] = mv[1] + ((M_H - i) / 10)*doZOOM;
|
||||
|
||||
}
|
||||
}
|
||||
}else{
|
||||
TRIGGERED = 0;
|
||||
}
|
||||
}
|
||||
56
Python Version/DatamoshLib/FFG_effects/jscripts/Stop.js
Normal file
56
Python Version/DatamoshLib/FFG_effects/jscripts/Stop.js
Normal file
@@ -0,0 +1,56 @@
|
||||
// dd_RandomDamage(stopXY).js
|
||||
// stop x and y component of mv for n framesif threshold met for frame
|
||||
|
||||
let threshold = 95;
|
||||
var TRIGGERED = 0;
|
||||
var nFrames = 10;
|
||||
var frameCount = 0;
|
||||
|
||||
function glitch_frame(frame)
|
||||
{
|
||||
|
||||
var do_or_not = Math.random() * 100;
|
||||
if(do_or_not > threshold){
|
||||
if(TRIGGERED > 0){
|
||||
|
||||
}else{
|
||||
TRIGGERED = 1;
|
||||
frameCount = 0;
|
||||
}
|
||||
}
|
||||
// only do the glitch if our random number crosses the threshold
|
||||
if(TRIGGERED > 0 & frameCount <= nFrames){
|
||||
frameCount++;
|
||||
|
||||
// bail out if we have no motion vectors
|
||||
let mvs = frame["mv"];
|
||||
if ( !mvs )
|
||||
return;
|
||||
// bail out if we have no forward motion vectors
|
||||
let fwd_mvs = mvs["forward"];
|
||||
if ( !fwd_mvs )
|
||||
return;
|
||||
|
||||
var M_H = fwd_mvs.length/2;
|
||||
// clear horizontal element of all motion vectors
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ )
|
||||
{
|
||||
// loop through all rows
|
||||
let row = fwd_mvs[i];
|
||||
var M_W = row.length/2;
|
||||
|
||||
for ( let j = 0; j < row.length; j++ )
|
||||
{
|
||||
// loop through all macroblocks
|
||||
let mv = row[j];
|
||||
|
||||
// THIS IS WHERE THE MAGIC HAPPENS
|
||||
// STOP XY
|
||||
mv[0] = 0;
|
||||
mv[1] = 0;
|
||||
}
|
||||
}
|
||||
}else{
|
||||
TRIGGERED = 0;
|
||||
}
|
||||
}
|
||||
29
Python Version/DatamoshLib/FFG_effects/jscripts/Vibrate.js
Normal file
29
Python Version/DatamoshLib/FFG_effects/jscripts/Vibrate.js
Normal file
@@ -0,0 +1,29 @@
|
||||
var randomness = 10;
|
||||
var bias = (randomness/2);
|
||||
function glitch_frame(frame)
|
||||
{
|
||||
// bail out if we have no motion vectors
|
||||
let mvs = frame["mv"];
|
||||
if ( !mvs )
|
||||
return;
|
||||
// bail out if we have no forward motion vectors
|
||||
let fwd_mvs = mvs["forward"];
|
||||
if ( !fwd_mvs )
|
||||
return;
|
||||
|
||||
// clear horizontal element of all motion vectors
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ )
|
||||
{
|
||||
// loop through all rows
|
||||
let row = fwd_mvs[i];
|
||||
for ( let j = 0; j < row.length; j++ )
|
||||
{
|
||||
// loop through all macroblocks
|
||||
let mv = row[j];
|
||||
|
||||
// THIS IS WHERE THE MAGIC HAPPENS
|
||||
mv[0] = mv[0] + (Math.floor((Math.random() * randomness) -bias));
|
||||
mv[1] = mv[1] + (Math.floor((Math.random() * randomness) -bias));
|
||||
}
|
||||
}
|
||||
}
|
||||
38
Python Version/DatamoshLib/FFG_effects/jscripts/Zoom.js
Normal file
38
Python Version/DatamoshLib/FFG_effects/jscripts/Zoom.js
Normal file
@@ -0,0 +1,38 @@
|
||||
// dd_zoom_in.js
|
||||
|
||||
var ZOOM = 20;
|
||||
|
||||
function glitch_frame(frame)
|
||||
{
|
||||
// bail out if we have no motion vectors
|
||||
let mvs = frame["mv"];
|
||||
if ( !mvs )
|
||||
return;
|
||||
// bail out if we have no forward motion vectors
|
||||
let fwd_mvs = mvs["forward"];
|
||||
if ( !fwd_mvs )
|
||||
return;
|
||||
|
||||
var M_H = fwd_mvs.length/2;
|
||||
// clear horizontal element of all motion vectors
|
||||
for ( let i = 0; i < fwd_mvs.length; i++ )
|
||||
{
|
||||
|
||||
// loop through all rows
|
||||
|
||||
let row = fwd_mvs[i];
|
||||
var M_W = row.length/2;
|
||||
|
||||
for ( let j = 0; j < row.length; j++ )
|
||||
{
|
||||
// loop through all macroblocks
|
||||
let mv = row[j];
|
||||
|
||||
// THIS IS WHERE THE MAGIC HAPPENS
|
||||
//if(i>M_W){
|
||||
mv[0] = mv[0] + ((M_W - j) / 100)*ZOOM;
|
||||
mv[1] = mv[1] + ((M_H - i) / 100)*ZOOM;
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
35
Python Version/DatamoshLib/Original/classic.py
Normal file
35
Python Version/DatamoshLib/Original/classic.py
Normal file
@@ -0,0 +1,35 @@
|
||||
#Author: Akash Bora
|
||||
import subprocess
|
||||
def Datamosh(filename, outf, s, e, p, fps=30):
|
||||
END_FRAME_HEX = b'00dc'
|
||||
I_FRAME_HEX = b'\x00\x01\xb0'
|
||||
def main(filename, effect_sec_list, p_frames_mult):
|
||||
mosh(effect_sec_list, p_frames_mult)
|
||||
def mosh(effect_sec_list, p_frames_mult):
|
||||
with open(filename, 'rb') as in_file, open(outf, 'wb') as out_file:
|
||||
frames = split_file(in_file, END_FRAME_HEX)
|
||||
for index, frame in enumerate(frames):
|
||||
if not is_need_effect_here(index / fps, effect_sec_list):
|
||||
out_file.write(frame + END_FRAME_HEX)
|
||||
continue
|
||||
if not is_iframe(frame):
|
||||
out_file.write((frame + END_FRAME_HEX) * p_frames_mult)
|
||||
def split_file(fp, marker, blocksize=4096):
|
||||
buffer = b''
|
||||
for block in iter(lambda: fp.read(blocksize), b''):
|
||||
buffer += block
|
||||
while True:
|
||||
markerpos = buffer.find(marker)
|
||||
if markerpos == -1:
|
||||
break
|
||||
yield buffer[:markerpos]
|
||||
buffer = buffer[markerpos + len(marker):]
|
||||
yield buffer
|
||||
def is_need_effect_here(curr_sec, effect_sec_list):
|
||||
return any(start < curr_sec < end for start, end in effect_sec_list)
|
||||
def is_iframe(frame):
|
||||
return frame[5:8] == I_FRAME_HEX
|
||||
start=s
|
||||
end=e
|
||||
pf=p
|
||||
main(filename,[(start,end)],pf)
|
||||
64
Python Version/DatamoshLib/Original/pymodes.py
Normal file
64
Python Version/DatamoshLib/Original/pymodes.py
Normal file
@@ -0,0 +1,64 @@
|
||||
#Author: Akash Bora
|
||||
from pymosh import Index
|
||||
from pymosh.codec.mpeg4 import is_iframe
|
||||
from itertools import islice
|
||||
class library():
|
||||
def glide(interval, filename, outfile):
|
||||
f = Index.from_file(filename)
|
||||
buf = [None]
|
||||
def process_frame(frame):
|
||||
if buf[0] == None or not is_iframe(frame):
|
||||
buf[0] = frame
|
||||
else:
|
||||
frame = buf[0]
|
||||
return frame
|
||||
for stream in f.video:
|
||||
newstream = []
|
||||
newstream.append(stream[0])
|
||||
ix = 0
|
||||
jx = 0
|
||||
for i in stream[1:]:
|
||||
ix += 1
|
||||
jx += 1
|
||||
if ix < interval:
|
||||
newstream.append(process_frame(stream[jx]))
|
||||
else:
|
||||
newstream.append(newstream[-1])
|
||||
if ix > interval * 2:
|
||||
ix = 0
|
||||
stream.replace(newstream)
|
||||
f.rebuild()
|
||||
with open(outfile, 'wb') as out:
|
||||
f.write(out)
|
||||
|
||||
def avi_sort(filename, outfile, mode, rev):
|
||||
f = Index.from_file(filename)
|
||||
for stream in f.video:
|
||||
if mode==0:
|
||||
sorted_stream = sorted(stream, key=len, reverse=rev)
|
||||
else:
|
||||
sorted_stream = sorted(stream, key=lambda s: s[len(s)-6], reverse=rev)
|
||||
stream.replace(sorted_stream)
|
||||
f.rebuild()
|
||||
with open(outfile, 'wb') as out:
|
||||
f.write(out)
|
||||
|
||||
def process_streams(in_filename, out_filename, mid=''):
|
||||
def echo(stream, midpoint):
|
||||
all_frames = list(stream)
|
||||
pframes = [f for f in all_frames if not is_iframe(f)]
|
||||
midpoint_idx = int(len(all_frames)*midpoint)
|
||||
frames = all_frames[:midpoint_idx]
|
||||
while len(frames) < len(all_frames):
|
||||
frames += pframes[:(len(all_frames) - len(frames))]
|
||||
return frames
|
||||
mode=echo
|
||||
f = Index.from_file(in_filename)
|
||||
for stream in f.video:
|
||||
midpoint=mid
|
||||
drifted = list(mode(stream, midpoint))
|
||||
stream.replace(drifted)
|
||||
f.rebuild()
|
||||
with open(out_filename, 'wb') as out:
|
||||
f.write(out)
|
||||
|
||||
43
Python Version/DatamoshLib/Original/repeat.py
Normal file
43
Python Version/DatamoshLib/Original/repeat.py
Normal file
@@ -0,0 +1,43 @@
|
||||
#Author: Akash Bora
|
||||
def Datamosh(filename,outfile,s,e,p,fps):
|
||||
def write_frame(frame):
|
||||
out_file.write(frame_start + frame)
|
||||
def mosh_delta_repeat(n_repeat):
|
||||
if n_repeat=="1":
|
||||
n_repeat=2
|
||||
repeat_frames = []
|
||||
repeat_index = 0
|
||||
for index, frame in enumerate(frames):
|
||||
if (frame[5:8] != iframe and frame[5:8] != pframe) or not start_frame <= index < end_frame:
|
||||
write_frame(frame)
|
||||
continue
|
||||
if len(repeat_frames) < n_repeat and frame[5:8] != iframe:
|
||||
repeat_frames.append(frame)
|
||||
write_frame(frame)
|
||||
elif len(repeat_frames) == n_repeat:
|
||||
write_frame(repeat_frames[repeat_index])
|
||||
repeat_index = (repeat_index + 1) % n_repeat
|
||||
else:
|
||||
write_frame(frame)
|
||||
start_frame = s
|
||||
end_frame = e
|
||||
if end_frame==1:
|
||||
end_frame=1000
|
||||
input_avi = filename
|
||||
delta = p
|
||||
in_file = open(input_avi, 'rb')
|
||||
output_avi= outfile
|
||||
in_file_bytes = in_file.read()
|
||||
out_file = open(output_avi, 'wb')
|
||||
frame_start = bytes.fromhex('30306463')
|
||||
frames = in_file_bytes.split(frame_start)
|
||||
out_file.write(frames[0])
|
||||
frames = frames[1:]
|
||||
iframe = bytes.fromhex('0001B0')
|
||||
pframe = bytes.fromhex('0001B6')
|
||||
n_video_frames = len([frame for frame in frames if frame[5:8] == iframe or frame[5:8] == pframe])
|
||||
if end_frame < 0:
|
||||
end_frame = n_video_frames
|
||||
mosh_delta_repeat(delta)
|
||||
in_file.close()
|
||||
out_file.close()
|
||||
21
Python Version/DatamoshLib/Tomato/LICENSE.txt
Normal file
21
Python Version/DatamoshLib/Tomato/LICENSE.txt
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 Kaspar RAVEL
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
234
Python Version/DatamoshLib/Tomato/tomato.py
Normal file
234
Python Version/DatamoshLib/Tomato/tomato.py
Normal file
@@ -0,0 +1,234 @@
|
||||
#Original Author: Kasper Ravel
|
||||
#Modified by: Akash Bora
|
||||
import os, re, random, struct
|
||||
from itertools import chain
|
||||
from itertools import repeat
|
||||
def mosh(infile, outfile, m, c, n, a, f, k):
|
||||
print (" _ _ ")
|
||||
print ("| | | | ")
|
||||
print ("| |_ ___ _ __ ___ __ _| |_ ___ ")
|
||||
print ("| __/ _ \| '_ ` _ \ / _` | __/ _ \ ")
|
||||
print ("| || (_) | | | | | | (_| | || (_) |")
|
||||
print (" \__\___/|_| |_| |_|\__,_|\__\___/ ")
|
||||
print ("Tomato Automosh v2.0")
|
||||
print ("\\\\ Audio Video Interleave breaker")
|
||||
print (" ")
|
||||
print ("glitch tool made with love for the glitch art community <3")
|
||||
print ("___________________________________")
|
||||
|
||||
filein = infile
|
||||
mode = m
|
||||
countframes = c
|
||||
positframes = n
|
||||
audio = a
|
||||
firstframe = f
|
||||
kill = k
|
||||
if filein is None or os.path.exists(filein) == False:
|
||||
print("> step 0/5: valid input file required!")
|
||||
print("use -h to see help")
|
||||
exit()
|
||||
|
||||
|
||||
#define temp directory and files
|
||||
temp_nb = random.randint(10000, 99999)
|
||||
temp_dir = "temp-" + str(temp_nb)
|
||||
temp_hdrl = temp_dir +"\\hdrl.bin"
|
||||
temp_movi = temp_dir +"\\movi.bin"
|
||||
temp_idx1 = temp_dir +"\\idx1.bin"
|
||||
|
||||
os.mkdir(temp_dir)
|
||||
|
||||
#Define constrain function for jiggle :3
|
||||
def constrain(val, min_val, max_val):
|
||||
return min(max_val, max(min_val, val))
|
||||
|
||||
######################################
|
||||
### STREAM FILE INTO WORK DIR BINS ###
|
||||
######################################
|
||||
|
||||
print("> step 1/5 : streaming into binary files")
|
||||
|
||||
def bstream_until_marker(bfilein, bfileout, marker=0, startpos=0):
|
||||
chunk = 1024
|
||||
filesize = os.path.getsize(bfilein)
|
||||
if marker :
|
||||
marker = str.encode(marker)
|
||||
|
||||
with open(bfilein,'rb') as rd:
|
||||
with open(bfileout,'ab') as wr:
|
||||
for pos in range(startpos, filesize, chunk):
|
||||
rd.seek(pos)
|
||||
buffer = rd.read(chunk)
|
||||
|
||||
if marker:
|
||||
if buffer.find(marker) > 0 :
|
||||
marker_pos = re.search(marker, buffer).start() # position is relative to buffer glitchedframes
|
||||
marker_pos = marker_pos + pos # position should be absolute now
|
||||
split = buffer.split(marker, 1)
|
||||
wr.write(split[0])
|
||||
return marker_pos
|
||||
else:
|
||||
wr.write(buffer)
|
||||
else:
|
||||
wr.write(buffer)
|
||||
|
||||
#make 3 files, 1 for each chunk
|
||||
movi_marker_pos = bstream_until_marker(filein, temp_hdrl, "movi")
|
||||
idx1_marker_pos = bstream_until_marker(filein, temp_movi, "idx1", movi_marker_pos)
|
||||
bstream_until_marker(filein, temp_idx1, 0, idx1_marker_pos)
|
||||
|
||||
####################################
|
||||
### FUN STUFF WITH VIDEO CONTENT ###
|
||||
####################################
|
||||
|
||||
print("> step 2/5 : constructing frame index")
|
||||
|
||||
with open(temp_movi,'rb') as rd:
|
||||
chunk = 1024
|
||||
filesize = os.path.getsize(temp_movi)
|
||||
frame_table = []
|
||||
|
||||
for pos in range(0, filesize, chunk):
|
||||
rd.seek(pos)
|
||||
buffer = rd.read(chunk)
|
||||
|
||||
#build first list with all adresses
|
||||
for m in (re.finditer(b'\x30\x31\x77\x62', buffer)): # find iframes
|
||||
if audio : frame_table.append([m.start() + pos, 'sound'])
|
||||
for m in (re.finditer(b'\x30\x30\x64\x63', buffer)): # find b frames
|
||||
frame_table.append([m.start() + pos, 'video'])
|
||||
|
||||
#then remember to sort the list
|
||||
frame_table.sort(key=lambda tup: tup[0])
|
||||
|
||||
l = []
|
||||
l.append([0,0, 'void'])
|
||||
max_frame_size = 0
|
||||
|
||||
#build tuples for each frame index with frame sizes
|
||||
for n in range(len(frame_table)):
|
||||
if n + 1 < len(frame_table):
|
||||
frame_size = frame_table[n + 1][0] - frame_table[n][0]
|
||||
else:
|
||||
frame_size = filesize - frame_table[n][0]
|
||||
max_frame_size = max(max_frame_size, frame_size)
|
||||
l.append([frame_table[n][0],frame_size, frame_table[n][1]])
|
||||
|
||||
|
||||
########################
|
||||
### TIME FOR SOME FX ###
|
||||
########################
|
||||
|
||||
# variables that make shit work
|
||||
clean = []
|
||||
final = []
|
||||
|
||||
# keep first video frame or not
|
||||
if firstframe:
|
||||
for x in l:
|
||||
if x[2] == 'video':
|
||||
clean.append(x)
|
||||
break
|
||||
|
||||
# clean the list by killing "big" frames
|
||||
for x in l:
|
||||
if x[1] <= (max_frame_size * kill) :
|
||||
clean.append(x)
|
||||
# FX modes
|
||||
if mode == "void":
|
||||
print('> step 3/5 : mode void')
|
||||
final = clean
|
||||
|
||||
if mode == "random":
|
||||
print('> step 3/5 : mode random')
|
||||
final = random.sample(clean,len(clean))
|
||||
|
||||
if mode == "reverse":
|
||||
print('> step 3/5 : mode reverse')
|
||||
final = sum(zip(clean[::-1], clean[:-1]), ())
|
||||
|
||||
if mode == "invert":
|
||||
print('> step 3/5 : mode invert')
|
||||
final = sum(zip(clean[1::2], clean[::2]), ())
|
||||
|
||||
if mode == 'bloom':
|
||||
print('> step 3/5 : mode bloom')
|
||||
repeat = int(countframes)
|
||||
frame = int(positframes)
|
||||
## split list
|
||||
lista = clean[:frame]
|
||||
listb = clean[frame:]
|
||||
## rejoin list with bloom
|
||||
final = lista + ([clean[frame]]*repeat) + listb
|
||||
|
||||
if mode == 'pulse':
|
||||
print('> step 3/5 : mode pulse')
|
||||
pulselen = int(countframes)
|
||||
pulseryt = int(positframes)
|
||||
j = 0
|
||||
for x in clean:
|
||||
i = 0
|
||||
if(j % pulselen == 0):
|
||||
while i < pulselen :
|
||||
final.append(x)
|
||||
i = i + 1
|
||||
else:
|
||||
final.append(x)
|
||||
j = j + 1
|
||||
|
||||
if mode == "jiggle":
|
||||
print('> step 3/5 : mode jiggle')
|
||||
#print('*needs debugging lol help thx*') # didn't pandy's branch fix this?
|
||||
amount = int(positframes)
|
||||
final = [clean[constrain(x+int(random.gauss(0,amount)),0,len(clean)-1)] for x in range(0,len(clean))]
|
||||
|
||||
if mode == "overlap":
|
||||
print('> step 3/5 : mode overlap')
|
||||
pulselen = int(countframes)
|
||||
pulseryt = int(positframes)
|
||||
|
||||
clean = [clean[i:i+pulselen] for i in range(0,len(clean),pulseryt)]
|
||||
final = [item for sublist in clean for item in sublist]
|
||||
|
||||
if mode == 'exponential':#Ask Kasper to add these modes (Note by Akash)
|
||||
print('> step 3/5 : mode exponential')
|
||||
print('sorry, currently not implemented. using void..')
|
||||
|
||||
if mode == 'swap':
|
||||
print('> step 3/5 : mode swap')
|
||||
print('sorry, currently not implemented. using void..')
|
||||
|
||||
|
||||
####################################
|
||||
### PUT VIDEO FILE BACK TOGETHER ###
|
||||
####################################
|
||||
|
||||
print("> step 4/5 : putting things back together")
|
||||
|
||||
#name new file
|
||||
fileout = outfile
|
||||
|
||||
#delete old file
|
||||
if os.path.exists(fileout):
|
||||
os.remove(fileout)
|
||||
|
||||
bstream_until_marker(temp_hdrl, fileout)
|
||||
|
||||
with open(temp_movi,'rb') as rd:
|
||||
filesize = os.path.getsize(temp_movi)
|
||||
with open(fileout,'ab') as wr:
|
||||
wr.write(struct.pack('<4s', b'movi'))
|
||||
for x in final:
|
||||
if x[0] != 0 and x[1] != 0:
|
||||
rd.seek(x[0])
|
||||
wr.write(rd.read(x[1]))
|
||||
|
||||
bstream_until_marker(temp_idx1, fileout)
|
||||
|
||||
#remove unnecessary temporary files and folders
|
||||
os.remove(temp_hdrl)
|
||||
os.remove(temp_movi)
|
||||
os.remove(temp_idx1)
|
||||
os.rmdir(temp_dir)
|
||||
|
||||
print("> step 5/5 : done - final idx size : " + str(len(final)))
|
||||
725
Python Version/Datamosher Pro.py
Normal file
725
Python Version/Datamosher Pro.py
Normal file
@@ -0,0 +1,725 @@
|
||||
#Author: Akash Bora
|
||||
#License: MIT | Copyright (c) 2022 Akash Bora
|
||||
currentversion=1.8
|
||||
|
||||
#Import required modules
|
||||
import tkinter
|
||||
import tkinter.messagebox
|
||||
import customtkinter
|
||||
from tkinter import ttk, messagebox, filedialog
|
||||
import sys
|
||||
import os
|
||||
import imageio_ffmpeg
|
||||
import subprocess
|
||||
import imageio
|
||||
from PIL import Image, ImageTk #Upgrade pillow if you are facing any import error with PIL (pip install pillow --upgrade)
|
||||
from RangeSlider.RangeSlider import RangeSliderH, RangeSliderV
|
||||
import threading
|
||||
import ctypes
|
||||
import webbrowser
|
||||
import requests
|
||||
import time
|
||||
|
||||
#Import the local datamosh library
|
||||
from DatamoshLib.Tomato import tomato
|
||||
from DatamoshLib.Original import classic, repeat, pymodes
|
||||
from DatamoshLib.FFG_effects import basic_modes, external_script
|
||||
|
||||
#Resource Finder
|
||||
def resource(relative_path):
|
||||
base_path = getattr(
|
||||
sys,
|
||||
'_MEIPASS',
|
||||
os.path.dirname(os.path.abspath(__file__)))
|
||||
return os.path.join(base_path, relative_path)
|
||||
|
||||
#Main Window
|
||||
WIDTH = 780
|
||||
HEIGHT = 520
|
||||
try:
|
||||
ctypes.windll.shcore.SetProcessDpiAwareness(0)
|
||||
except:
|
||||
pass
|
||||
customtkinter.set_appearance_mode("Dark")
|
||||
customtkinter.set_default_color_theme("blue")
|
||||
self=customtkinter.CTk()
|
||||
self.title("Datamosher Pro (python version)")
|
||||
self.geometry(f"{WIDTH}x{HEIGHT}")
|
||||
self.bind("<1>", lambda event: event.widget.focus_set())
|
||||
self.grid_columnconfigure(1, weight=1)
|
||||
self.grid_rowconfigure(0, weight=1)
|
||||
self.resizable(width=False, height=False)
|
||||
frame_left = customtkinter.CTkFrame(master=self,width=180,corner_radius=0)
|
||||
frame_left.grid(row=0, column=0, sticky="nswe")
|
||||
frame_right = customtkinter.CTkFrame(master=self)
|
||||
frame_right.grid(row=0, column=1, sticky="nswe", padx=20, pady=20)
|
||||
icopath=ImageTk.PhotoImage(file=resource("Assets/Icons/Program_icon.png"))
|
||||
self.iconphoto(False, icopath)
|
||||
|
||||
#FFMPEG path (using the imageio ffmpeg plugin)
|
||||
ffdir=os.path.dirname(imageio_ffmpeg.__file__).replace(os.sep, '/')+"/binaries/"
|
||||
fileff=''.join([idx for idx in os.listdir(ffdir) if idx[0].lower()=='f'.lower()])
|
||||
ffmpeg=resource(ffdir+fileff)
|
||||
|
||||
#Effect List
|
||||
modelist=sorted(["Bloom", "Invert", "Jiggle", "Overlap", "Pulse", "Reverse",
|
||||
"Random", "Classic", "Glide", "Sort", "Echo", "Void",
|
||||
"Fluid", "Stretch", "Motion Transfer", "Repeat", "Shear", "Delay", "Sink",
|
||||
"Mirror", "Vibrate", "Slam Zoom", "Zoom","Invert-Reverse", "Shift",
|
||||
"Noise", "Stop", "Buffer", "Slice", "Shuffle", "Rise", "Custom Script"])
|
||||
current=modelist[0]
|
||||
|
||||
#Making the top widgets for changing the modes dynamically
|
||||
def ChangeModeRight():
|
||||
global current
|
||||
modelist.append(modelist.pop(0))
|
||||
current=modelist[0]
|
||||
mode_info.configure(text=current)
|
||||
dynamic()
|
||||
def ChangeModeLeft():
|
||||
global current
|
||||
modelist.insert(0, modelist.pop())
|
||||
current=modelist[0]
|
||||
mode_info.configure(text=current)
|
||||
dynamic()
|
||||
frame_info = customtkinter.CTkFrame(master=frame_right, width=520, height=100)
|
||||
frame_info.place(x=20,y=20)
|
||||
mode_info = customtkinter.CTkLabel(master=frame_info,text=current, corner_radius=10, width=320,
|
||||
height=50,
|
||||
fg_color=("white", "gray38"))
|
||||
mode_info.place(x=100,y=25)
|
||||
play_icon =Image.open(resource("Assets/Icons/right_icon.png")).resize((20, 20), Image.Resampling.LANCZOS)
|
||||
|
||||
left_but = customtkinter.CTkButton(master=frame_info, image=ImageTk.PhotoImage(play_icon.transpose(Image.Transpose.FLIP_LEFT_RIGHT)), text="", width=50, height=50,
|
||||
corner_radius=10, fg_color="gray40", hover_color="gray25", command=ChangeModeLeft)
|
||||
left_but.place(x=20,y=25)
|
||||
|
||||
right_but = customtkinter.CTkButton(master=frame_info, image=ImageTk.PhotoImage(play_icon), text="", width=50, height=50,
|
||||
corner_radius=10, fg_color="gray40", hover_color="gray25", command=ChangeModeRight)
|
||||
right_but.place(x=450,y=25)
|
||||
|
||||
#Open video function
|
||||
previous=""
|
||||
def open_function():
|
||||
global ofile, vid_image2, previous, duration, vid
|
||||
ofile=tkinter.filedialog.askopenfilename(filetypes =[('Video', ['*.mp4','*.avi','*.mov','*.mkv','*gif']),('All Files', '*.*')])
|
||||
#Check the video type
|
||||
supported=["mp4","avi","mov","gif","mkv","wmv","m4v"]
|
||||
if ofile:
|
||||
previous=ofile
|
||||
pass
|
||||
else:
|
||||
ofile=previous
|
||||
return
|
||||
if ofile[-3:].lower() in supported:
|
||||
pass
|
||||
else:
|
||||
print("This file type is not supported!")
|
||||
return
|
||||
if len(os.path.basename(ofile))>=20:
|
||||
showinput=os.path.basename(ofile)[:10]+"..."+os.path.basename(ofile)[-3:]
|
||||
else:
|
||||
showinput=os.path.basename(ofile)[:20]
|
||||
#Change the thumbnail
|
||||
button_open.configure(fg_color='grey', text=showinput)
|
||||
outpng="Assets/thumbnail_cache/vid_thumbnail.jpg"
|
||||
button_thumbnail.configure(image=vid_image)
|
||||
if os.path.exists("Assets/thumbnail_cache/vid_thumbnail.jpg"):
|
||||
os.remove("Assets/thumbnail_cache/vid_thumbnail.jpg")
|
||||
subprocess.call(f'"{ffmpeg}" -loglevel quiet -ss 00:00:01 -t 00:00:01 -i "{ofile}" -qscale:v 2 -r 10.0 "{outpng}"', shell=True)
|
||||
vid_image2 = ImageTk.PhotoImage(Image.open(outpng).resize((167, 100), Image.Resampling.LANCZOS))
|
||||
button_thumbnail.configure(image=vid_image2)
|
||||
vid=imageio.get_reader(ofile, 'ffmpeg')
|
||||
#Update the widget parameters
|
||||
position_frame.configure(to=vid.count_frames(), number_of_steps=vid.count_frames())
|
||||
duration= vid.get_meta_data()['duration']
|
||||
rangebar.max_val=duration
|
||||
label_seconds2.configure(text="End: "+str(int(duration))+"s")
|
||||
rangebar2.max_val=vid.count_frames()
|
||||
label_showframe2.configure(text="End: "+str(vid.count_frames()))
|
||||
shuf_slider.configure(to=vid.count_frames(), number_of_steps=vid.count_frames())
|
||||
end_mosh.set(duration)
|
||||
end_frame_mosh.set(vid.count_frames())
|
||||
|
||||
#Left Frame Widgets
|
||||
label_appname = customtkinter.CTkLabel(master=frame_left,text="DATAMOSHER PRO")
|
||||
label_appname.place(x=20,y=10)
|
||||
|
||||
vid_image = ImageTk.PhotoImage(Image.open("Assets/thumbnail_cache/offline_image.png").resize((167, 100), Image.Resampling.LANCZOS))
|
||||
|
||||
button_thumbnail = tkinter.Label(master=frame_left, image=vid_image, width=167, height=100, text="", bg="grey")
|
||||
button_thumbnail.place(x=5,y=40)
|
||||
|
||||
add_video_image = ImageTk.PhotoImage(Image.open(resource("Assets/Icons/video_icon.png")).resize((20, 15), Image.Resampling.LANCZOS))
|
||||
button_open = customtkinter.CTkButton(master=frame_left, image=add_video_image, text="IMPORT VIDEO", width=160, height=35,
|
||||
compound="right", command=open_function)
|
||||
button_open.place(x=10,y=170)
|
||||
|
||||
label_export = customtkinter.CTkLabel(master=frame_left,anchor="w",text="Export Format")
|
||||
label_export.place(x=12,y=215)
|
||||
|
||||
optionmenu_1 = customtkinter.CTkOptionMenu(master=frame_left, fg_color="#4d4d4d",width=160, height=35, values=["mp4","avi","mov","mkv"])
|
||||
optionmenu_1.set("mp4")
|
||||
optionmenu_1.place(x=10,y=250)
|
||||
|
||||
settingpng = ImageTk.PhotoImage(Image.open(resource("Assets/Icons/settings.png")).resize((20, 20), Image.Resampling.LANCZOS))
|
||||
|
||||
#Setting Window
|
||||
def close_top3():
|
||||
window_UI.destroy()
|
||||
uisetting.configure(state=tkinter.NORMAL)
|
||||
def changeUI():
|
||||
global window_UI
|
||||
window_UI = customtkinter.CTkToplevel(self)
|
||||
window_UI.geometry("410x200")
|
||||
window_UI.resizable(width=False, height=False)
|
||||
window_UI.title("App Preferences")
|
||||
window_UI.iconphoto(False, icopath)
|
||||
uisetting.configure(state=tkinter.DISABLED)
|
||||
window_UI.wm_transient(self)
|
||||
def check():
|
||||
URL = "https://raw.githubusercontent.com/Akascape/Datamosher-Pro/Miscellaneous/VERSIONPY.txt"
|
||||
try:
|
||||
response = requests.get(URL)
|
||||
open("Assets\\version\\VERSIONPY.txt", "wb").write(response.content)
|
||||
except:
|
||||
tkinter.messagebox.showinfo("Unable to connect!", "Unable to get information, please check your internet connection or visit the github repository.")
|
||||
return
|
||||
time.sleep(2)
|
||||
with open("Assets\\version\\VERSIONPY.txt", 'r') as uf:
|
||||
nver=float(uf.read())
|
||||
if nver>currentversion:
|
||||
tkinter.messagebox.showinfo("New Version available!","A new version "+ str(nver) +
|
||||
" is available, \nPlease visit the github repository or the original download page!")
|
||||
else:
|
||||
tkinter.messagebox.showinfo("No Updates!", "You are on the latest version!")
|
||||
def docs():
|
||||
webbrowser.open_new_tab("https://github.com/Akascape/Datamosher-Pro/wiki")
|
||||
def repo():
|
||||
webbrowser.open_new_tab("https://github.com/Akascape/Datamosher-Pro")
|
||||
logo_image = ImageTk.PhotoImage(Image.open(resource("Assets/Icons/Logo.png")).resize((210, 200), Image.Resampling.LANCZOS))
|
||||
logo=customtkinter.CTkButton(master=window_UI, image=logo_image, width=205, height=105, border_width=0,
|
||||
corner_radius=1, border_color="grey20", text="",fg_color=customtkinter.ThemeManager.theme["color"]["frame_low"][1],
|
||||
hover_color=customtkinter.ThemeManager.theme["color"]["frame_low"][1])
|
||||
logo.place(x=200,y=0)
|
||||
visit=customtkinter.CTkButton(window_UI, text="Visit Repo", width=150, height=35,
|
||||
corner_radius=10, fg_color=customtkinter.ThemeManager.theme["color"]["button"][1], hover_color="gray25",command=repo)
|
||||
visit.place(x=20,y=30)
|
||||
checkupdate=customtkinter.CTkButton(window_UI, text="Check For Updates", width=150, height=35,
|
||||
corner_radius=10, fg_color=customtkinter.ThemeManager.theme["color"]["button"][1], hover_color="gray25",command=check)
|
||||
checkupdate.place(x=20,y=80)
|
||||
helpbutton=customtkinter.CTkButton(window_UI, text="Help", width=150, height=35,
|
||||
corner_radius=10, fg_color=customtkinter.ThemeManager.theme["color"]["button"][1], hover_color="gray25",command=docs)
|
||||
helpbutton.place(x=20,y=130)
|
||||
version_label=customtkinter.CTkLabel(window_UI,anchor="w",width=1,fg_color=customtkinter.ThemeManager.theme["color"]["frame_low"][1],
|
||||
text="v"+str(currentversion), bg_color=customtkinter.ThemeManager.theme["color"]["frame_low"][1])
|
||||
version_label.place(x=365, y=2)
|
||||
dvname=customtkinter.CTkLabel(window_UI,anchor="w",width=1,fg_color=customtkinter.ThemeManager.theme["color"]["frame_low"][1],
|
||||
text="Developer: Akash Bora", bg_color=customtkinter.ThemeManager.theme["color"]["frame_low"][1])
|
||||
dvname.place(x=30,y=170)
|
||||
window_UI.protocol("WM_DELETE_WINDOW", close_top3)
|
||||
uisetting = customtkinter.CTkButton(master=frame_left, image=settingpng, text="", width=40, height=40,
|
||||
corner_radius=10, fg_color=customtkinter.ThemeManager.theme["color"]["text_disabled"][1],
|
||||
hover_color="gray25", command=changeUI)
|
||||
uisetting.place(x=10,y=470)
|
||||
|
||||
#Validation for entries
|
||||
def only_numbers(char):
|
||||
if ((char.isdigit()) or (char=="")) and (len(char)<=6):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
validation = self.register(only_numbers)
|
||||
|
||||
### Dynamimc widgets that change with modes ###
|
||||
|
||||
#Kill Frame Widget
|
||||
def changekill(value):
|
||||
label_kill.configure(text="Kill Frame Size: "+str(round(value,4)))
|
||||
label_kill = customtkinter.CTkLabel(master=frame_right,anchor="w",text="Kill Frame Size: 0.6")
|
||||
slider_kill= customtkinter.CTkSlider(master=frame_right, width=500,
|
||||
from_=1,
|
||||
to=0,
|
||||
number_of_steps=100, command=changekill)
|
||||
slider_kill.set(0.6)
|
||||
|
||||
#N-frameWidget
|
||||
varn=tkinter.IntVar()
|
||||
label_ctime = customtkinter.CTkLabel(master=frame_right,anchor='w',text="Frame Count:",width=1)
|
||||
ctime=customtkinter.CTkEntry(frame_right,textvariable=varn, validate='key', validatecommand=(validation, '%P'),
|
||||
placeholder_text="1",
|
||||
width=100,
|
||||
placeholder_text_color="grey70",
|
||||
height=30,
|
||||
border_width=2,
|
||||
corner_radius=10)
|
||||
varn.set(1)
|
||||
|
||||
#Keep frame & Keep audio widgets
|
||||
keepaudio = customtkinter.CTkCheckBox(master=frame_right, text="Keep Audio", onvalue=1, offvalue=0)
|
||||
keepframe = customtkinter.CTkCheckBox(master=frame_right, text="Keep First Frame", onvalue=1, offvalue=0)
|
||||
|
||||
#Count Frame widget
|
||||
label_frame1 = customtkinter.CTkLabel(master=frame_right,anchor='w',text="Position Frame: 1",width=1)
|
||||
def framework(value):
|
||||
try:
|
||||
if ofile:
|
||||
pass
|
||||
except:
|
||||
return
|
||||
label_frame1.configure(text="Position Frame: "+str(int(value)))
|
||||
position_frame=customtkinter.CTkSlider(master=frame_right, width=500,progress_color="black", fg_color="black",
|
||||
from_=1,
|
||||
to=0,
|
||||
number_of_steps=1, command=framework)
|
||||
|
||||
position_frame.set(1)
|
||||
|
||||
#Classic Rangebar
|
||||
start_mosh = tkinter.DoubleVar()
|
||||
end_mosh = tkinter.DoubleVar()
|
||||
rangebar = RangeSliderH(frame_right, [start_mosh, end_mosh], Width=510, Height=63,
|
||||
bgColor=customtkinter.ThemeManager.theme["color"]["frame_low"][1],line_color="black",
|
||||
bar_color_outer=customtkinter.ThemeManager.theme["color"]["button"][0],
|
||||
bar_color_inner=customtkinter.ThemeManager.theme["color"]["checkmark"][1],min_val=0, max_val=1, show_value= False,
|
||||
line_s_color=customtkinter.ThemeManager.theme["color"]["button"][0])
|
||||
label_seconds1 = customtkinter.CTkLabel(master=frame_right,anchor='w',text="Start: 0s",width=1)
|
||||
label_seconds2 = customtkinter.CTkLabel(master=frame_right,anchor='w',text="End: 0s",width=1)
|
||||
label_segment= customtkinter.CTkLabel(master=frame_right,anchor='w',text="Choose Segment:",width=1)
|
||||
def show2(*args):
|
||||
try:
|
||||
if ofile:
|
||||
pass
|
||||
except:
|
||||
return
|
||||
label_seconds2.configure(text="End: "+str(int(end_mosh.get()))+"s")
|
||||
def show(*args):
|
||||
try:
|
||||
if ofile:
|
||||
pass
|
||||
except:
|
||||
return
|
||||
label_seconds1.configure(text="Start: "+str(int(start_mosh.get()))+"s")
|
||||
start_mosh.trace_add('write', show)
|
||||
end_mosh.trace_add('write', show2)
|
||||
|
||||
#Delta entry widget
|
||||
label_p = customtkinter.CTkLabel(master=frame_right,anchor='w',text="P-frames (Delta):",width=1)
|
||||
label_segment= customtkinter.CTkLabel(master=frame_right,anchor='w',text="Choose Segment:",width=1)
|
||||
|
||||
varp=tkinter.IntVar()
|
||||
delta=customtkinter.CTkEntry(frame_right,
|
||||
placeholder_text="1",validate='key', validatecommand=(validation, '%P'),
|
||||
width=100, textvariable=varp,
|
||||
placeholder_text_color="grey70",
|
||||
height=30,
|
||||
border_width=2,
|
||||
corner_radius=10)
|
||||
varp.set(1)
|
||||
|
||||
#Frame Rangebar for repeat and rise modes
|
||||
start_frame_mosh = tkinter.DoubleVar()
|
||||
end_frame_mosh = tkinter.DoubleVar()
|
||||
rangebar2 = RangeSliderH(frame_right, [start_frame_mosh, end_frame_mosh], Width=510, Height=63,
|
||||
bgColor=customtkinter.ThemeManager.theme["color"]["frame_low"][1],line_color="black",
|
||||
bar_color_outer=customtkinter.ThemeManager.theme["color"]["button"][0],
|
||||
bar_color_inner=customtkinter.ThemeManager.theme["color"]["checkmark"][1],min_val=0, max_val=1, show_value= False,
|
||||
line_s_color=customtkinter.ThemeManager.theme["color"]["button"][0])
|
||||
label_showframe1 = customtkinter.CTkLabel(master=frame_right,anchor='w',text="Start Frame: 0",width=1)
|
||||
label_showframe2 = customtkinter.CTkLabel(master=frame_right,anchor='w',text="End: 0",width=1)
|
||||
label_segment2= customtkinter.CTkLabel(master=frame_right,anchor='w',text="Choose Frame Segment:",width=1)
|
||||
def show3(*args):
|
||||
try:
|
||||
if ofile:
|
||||
pass
|
||||
except:
|
||||
return
|
||||
label_showframe2.configure(text="End: "+str(int(end_frame_mosh.get())))
|
||||
def show4(*args):
|
||||
try:
|
||||
if ofile:
|
||||
pass
|
||||
except:
|
||||
return
|
||||
label_showframe1.configure(text="Start Frame: "+str(int(start_frame_mosh.get())))
|
||||
start_frame_mosh.trace_add('write', show4)
|
||||
end_frame_mosh.trace_add('write', show3)
|
||||
|
||||
#slider for echo mode
|
||||
def midwork(value):
|
||||
label_mid.configure(text="Start Point: "+str(round(value,1)))
|
||||
label_mid = customtkinter.CTkLabel(master=frame_right,anchor='w',text="Start Point: 0.5",width=1)
|
||||
mid_point=customtkinter.CTkSlider(master=frame_right, width=500,progress_color="black", fg_color="black",
|
||||
from_=0,
|
||||
to=1,
|
||||
number_of_steps=10,command=midwork)
|
||||
mid_point.set(0.5)
|
||||
|
||||
#Some options for sort mode
|
||||
keepsort = customtkinter.CTkCheckBox(master=frame_right, text="Keep First Frames", onvalue=0, offvalue=1)
|
||||
reversesort=customtkinter.CTkCheckBox(master=frame_right, text="Reverse", onvalue=False, offvalue=True)
|
||||
|
||||
#Options for ffglitch modes
|
||||
hw_auto=customtkinter.CTkSwitch(master=frame_right,text="HW Acceleration \n(Auto)",onvalue=1, offvalue=0)
|
||||
labelk=customtkinter.CTkLabel(master=frame_right,anchor='w',text="Keyframes:",width=1)
|
||||
kf=customtkinter.CTkComboBox(master=frame_right,height=30, width=150,
|
||||
values=["1000","100","10", "1"])
|
||||
#Widget for Shuffle mde
|
||||
def changeshuf(value):
|
||||
shuf_label.configure(text="Chunk Size: "+str(int(value)))
|
||||
shuf_label=customtkinter.CTkLabel(master=frame_right,anchor='w',text="Chunk Size: 1",width=1)
|
||||
shuf_slider=customtkinter.CTkSlider(master=frame_right, width=500,
|
||||
from_=1,
|
||||
to=0,
|
||||
number_of_steps=1, command=changeshuf)
|
||||
shuf_slider.set(1)
|
||||
|
||||
#Widget for Fluid mode
|
||||
def changefluid(value):
|
||||
fluid_label.configure(text="Amount: "+str(int(value)))
|
||||
fluid_label=customtkinter.CTkLabel(master=frame_right,anchor='w',text="Amount: 5",width=1)
|
||||
slider_fluid=customtkinter.CTkSlider(master=frame_right, width=500,
|
||||
from_=1,
|
||||
to=20,
|
||||
number_of_steps=100, command=changefluid)
|
||||
slider_fluid.set(5)
|
||||
#Stretch mode widget
|
||||
v_h=customtkinter.CTkSwitch(frame_right,text="Horizontal Stretch", onvalue=1, offvalue=0)
|
||||
|
||||
#Button for motion transfer mode
|
||||
def open_MT():
|
||||
global vfile
|
||||
vfile=tkinter.filedialog.askopenfilename(filetypes =[('Vector File', ['*.mp4','*.avi','*.mov','*.mkv']),('All Files', '*.*')])
|
||||
if vfile:
|
||||
mt_button.configure(fg_color='grey', text=os.path.basename(vfile))
|
||||
else:
|
||||
return
|
||||
mt_button=customtkinter.CTkButton(master=frame_right, text="OPEN VIDEO", width=520, height=30,
|
||||
compound="right",command=open_MT)
|
||||
|
||||
#Button for custom script mode
|
||||
scriptfile=''
|
||||
def open_script():
|
||||
global scriptfile
|
||||
scriptfile=tkinter.filedialog.askopenfilename(filetypes =[('Script File', ['*.js','*.py']),('All Files', '*.*')])
|
||||
if scriptfile:
|
||||
scriptbutton.configure(fg_color='grey', text=os.path.basename(scriptfile))
|
||||
else:
|
||||
scriptbutton.configure(fg_color=customtkinter.ThemeManager.theme["color"]["button"], text='OPEN SCRIPT')
|
||||
scriptfile=''
|
||||
scriptbutton=customtkinter.CTkButton(master=frame_right, text="OPEN SCRIPT", width=520, height=30,
|
||||
compound="right",command=open_script)
|
||||
|
||||
#Dynamic UI functions for each widget
|
||||
def rangeslider(x):
|
||||
if x==1:
|
||||
rangebar.place(x=20,y=210)
|
||||
label_seconds1.place(x=25,y=200)
|
||||
label_seconds2.place(x=470,y=200)
|
||||
label_segment.place(x=25,y=170)
|
||||
else:
|
||||
rangebar.place_forget()
|
||||
label_segment.place_forget()
|
||||
label_seconds1.place_forget()
|
||||
label_seconds2.place_forget()
|
||||
def rangeslider2(x):
|
||||
if x==1:
|
||||
if (current=="Rise"):
|
||||
rangebar2.place(x=20,y=260)
|
||||
label_showframe1.place(x=25,y=250)
|
||||
label_showframe2.place(x=470,y=250)
|
||||
label_segment2.place(x=25,y=220)
|
||||
else:
|
||||
rangebar2.place(x=20,y=210)
|
||||
label_showframe1.place(x=25,y=200)
|
||||
label_showframe2.place(x=470,y=200)
|
||||
label_segment2.place(x=25,y=170)
|
||||
else:
|
||||
rangebar2.place_forget()
|
||||
label_showframe1.place_forget()
|
||||
label_showframe2.place_forget()
|
||||
label_segment2.place_forget()
|
||||
def mid(x):
|
||||
if x==1:
|
||||
mid_point.place(x=20,y=210)
|
||||
label_mid.place(x=25,y=170)
|
||||
else:
|
||||
mid_point.place_forget()
|
||||
label_mid.place_forget()
|
||||
def killoption(x):
|
||||
if x==1 or x==2 or x==3:
|
||||
label_kill.place(x=25,y=170)
|
||||
slider_kill.place(x=20,y=200)
|
||||
else:
|
||||
label_kill.place_forget()
|
||||
slider_kill.place_forget()
|
||||
def positionslider(x):
|
||||
if x==1:
|
||||
label_frame1.place(x=25,y=230)
|
||||
position_frame.place(x=20,y=260)
|
||||
else:
|
||||
label_frame1.place_forget()
|
||||
position_frame.place_forget()
|
||||
def framekeep(x):
|
||||
if x==1:
|
||||
keepframe.place(x=250,y=300)
|
||||
elif x==2:
|
||||
keepframe.place(x=250,y=240)
|
||||
else:
|
||||
keepframe.place_forget()
|
||||
def audiokeep(x):
|
||||
if x==1:
|
||||
keepaudio.place(x=400,y=300)
|
||||
elif x==2:
|
||||
keepaudio.place(x=400,y=240)
|
||||
else:
|
||||
keepaudio.place_forget()
|
||||
def ctimes(x):
|
||||
if x==1:
|
||||
ctime.place(x=110,y=300)
|
||||
label_ctime.place(x=25,y=300)
|
||||
else:
|
||||
ctime.place_forget()
|
||||
label_ctime.place_forget()
|
||||
def pdelta(x):
|
||||
if x==1:
|
||||
delta.place(x=135,y=275)
|
||||
label_p.place(x=25,y=275)
|
||||
if current=="Repeat":
|
||||
varp.set(5)
|
||||
elif x==2:
|
||||
delta.place(x=135,y=170)
|
||||
label_p.place(x=25,y=170)
|
||||
if current=="Glide":
|
||||
varp.set(5)
|
||||
else:
|
||||
delta.place_forget()
|
||||
label_p.place_forget()
|
||||
def sortoptions(x):
|
||||
if x==1:
|
||||
keepsort.place(x=30, y=170)
|
||||
reversesort.place(x=300, y=170)
|
||||
else:
|
||||
keepsort.place_forget()
|
||||
reversesort.place_forget()
|
||||
def ffgassist(x):
|
||||
if x==1:
|
||||
hw_auto.place(x=25, y=170)
|
||||
labelk.place(x=300,y=170)
|
||||
kf.place(x=380,y=170)
|
||||
else:
|
||||
hw_auto.place_forget()
|
||||
labelk.place_forget()
|
||||
kf.place_forget()
|
||||
def shuf(x):
|
||||
if x==1:
|
||||
shuf_label.place(x=25,y=220)
|
||||
shuf_slider.place(x=20,y=250)
|
||||
else:
|
||||
shuf_label.place_forget()
|
||||
shuf_slider.place_forget()
|
||||
def fluidwidget(x):
|
||||
if x==1:
|
||||
fluid_label.place(x=25,y=220)
|
||||
slider_fluid.place(x=20,y=250)
|
||||
else:
|
||||
fluid_label.place_forget()
|
||||
slider_fluid.place_forget()
|
||||
def h_v(x):
|
||||
if x==1:
|
||||
v_h.place(x=25,y=220)
|
||||
else:
|
||||
v_h.place_forget()
|
||||
def mtwid(x):
|
||||
if x==1:
|
||||
mt_button.place(x=20,y=230)
|
||||
else:
|
||||
mt_button.place_forget()
|
||||
def custom(x):
|
||||
if x==1:
|
||||
scriptbutton.place(x=20,y=230)
|
||||
else:
|
||||
scriptbutton.place_forget()
|
||||
|
||||
#Main Function to update the widgets
|
||||
def dynamic():
|
||||
global current, showwidgets
|
||||
allwidgets=[audiokeep, positionslider, killoption, framekeep,
|
||||
ctimes, pdelta, rangeslider, rangeslider2, mid, sortoptions, ffgassist, fluidwidget, h_v, custom, mtwid, shuf]
|
||||
for i in allwidgets:
|
||||
i(0)
|
||||
showwidgets=[]
|
||||
if (current=="Bloom") or (current=="Pulse") or (current=="Pulse") or(current=="Overlap"):
|
||||
showwidgets=[audiokeep, positionslider, killoption, framekeep, ctimes]
|
||||
u=1
|
||||
elif (current=="Jiggle"):
|
||||
showwidgets=[positionslider, audiokeep, killoption, framekeep]
|
||||
u=1
|
||||
elif (current=="Void") or (current=="Reverse") or (current=="Invert") or (current=="Random"):
|
||||
showwidgets=[killoption,audiokeep, framekeep]
|
||||
u=2
|
||||
elif (current=="Classic"):
|
||||
showwidgets=[rangeslider, pdelta]
|
||||
u=1
|
||||
elif (current=="Glide"):
|
||||
showwidgets=[pdelta]
|
||||
u=2
|
||||
elif (current=="Repeat") or (current=="Rise"):
|
||||
if (current=="Rise"):
|
||||
showwidgets=[rangeslider2, ffgassist]
|
||||
else:
|
||||
showwidgets=[rangeslider2, pdelta]
|
||||
u=1
|
||||
elif (current=="Echo"):
|
||||
showwidgets=[mid]
|
||||
u=1
|
||||
elif (current=="Sort"):
|
||||
showwidgets=[sortoptions]
|
||||
u=1
|
||||
elif ((current=="Buffer") or (current=="Sink") or (current=="Mirror") or (current=="Shear") or (current=="Noise")
|
||||
or (current=="Delay") or (current=="Slam Zoom") or (current=="Invert-Reverse") or (current=="Shift") or (current=="Zoom")
|
||||
or (current=="Slice")or (current=="Vibrate") or (current=="Stop")):
|
||||
showwidgets=[ffgassist]
|
||||
u=1
|
||||
elif (current=="Fluid"):
|
||||
showwidgets=[ffgassist, fluidwidget]
|
||||
u=1
|
||||
elif (current=="Stretch"):
|
||||
showwidgets=[ffgassist, h_v]
|
||||
u=1
|
||||
elif (current=="Motion Transfer"):
|
||||
showwidgets=[ffgassist, mtwid]
|
||||
u=1
|
||||
elif (current=="Custom Script"):
|
||||
showwidgets=[ffgassist, custom]
|
||||
u=1
|
||||
elif (current=="Shuffle"):
|
||||
showwidgets=[ffgassist, shuf]
|
||||
u=1
|
||||
for widgets in showwidgets:
|
||||
widgets(u)
|
||||
dynamic()
|
||||
keepframe.select()
|
||||
|
||||
#autosave video function
|
||||
def savename():
|
||||
global sfile
|
||||
if ofile:
|
||||
try:
|
||||
sfile=ofile[:-4]+"_datamoshed_"+current+'.'+optionmenu_1.get()
|
||||
nf=0
|
||||
while os.path.exists(sfile):
|
||||
nf=nf+1
|
||||
sfile=ofile[:-4]+"_datamoshed_"+current+'('+str(nf)+')'+'.'+optionmenu_1.get()
|
||||
except:
|
||||
sfile=""
|
||||
#A function that will thread the main mosh function to separate the processes
|
||||
def Threadthis():
|
||||
global varp, varn
|
||||
if delta.get()=='' or delta.get()<'1':
|
||||
varp.set(1)
|
||||
if ctime.get()=='' or ctime.get()<'1':
|
||||
varn.set(1)
|
||||
threading.Thread(target=Do_the_mosh).start()
|
||||
#Converter function
|
||||
def ffmpeg_convert(inputpath, parameters, outputpath, extra=''):
|
||||
subprocess.call(f'"{ffmpeg}" {extra} -i "{inputpath}" {parameters} -y "{outputpath}"', shell=True)
|
||||
|
||||
#Main Function of the whole program
|
||||
def Do_the_mosh():
|
||||
global ofile, sfile, param, param2
|
||||
button_mosh.configure(state=tkinter.DISABLED)
|
||||
if previous=="":
|
||||
tkinter.messagebox.showinfo("No Video imported!","Please import a video file!")
|
||||
button_mosh.configure(state=tkinter.NORMAL)
|
||||
return
|
||||
try:
|
||||
savename()
|
||||
ProcessLabel.configure(text='STEP 1/3 CONVERTING...')
|
||||
param="-c:v libx264 -preset medium -b:v 2M -minrate 2M -maxrate 2M -bufsize 2M" #Add other ffmpeg parameters in this line only
|
||||
if ((current=="Bloom") or (current=="Pulse") or (current=="Pulse") or(current=="Overlap")
|
||||
or (current=="Void") or (current=="Reverse") or (current=="Invert") or (current=="Random") or (current=="Jiggle")):
|
||||
ifile=sfile[:-4]+".avi"
|
||||
ffmpeg_convert(ofile,param,ifile)
|
||||
ProcessLabel.configure(text='STEP 2/3 MOSHING...')
|
||||
mfile=sfile[:-4]+"_corrupted.avi"
|
||||
tomato.mosh(infile=ifile, outfile=mfile, m=current.lower(), c=varn.get(), n=int(position_frame.get()), k=round(slider_kill.get(),4), a=keepaudio.get(), f=keepframe.get())
|
||||
time.sleep(1)
|
||||
os.remove(ifile)
|
||||
ProcessLabel.configure(text='STEP 3/3 FIXING THE CORRUPTED FILE...')
|
||||
ffmpeg_convert(mfile,param,sfile)
|
||||
os.remove(mfile)
|
||||
elif ((current=="Classic") or (current=="Repeat") or (current=="Glide") or (current=="Sort") or (current=="Echo")):
|
||||
param="-bf 0 -b 10000k" #Add other ffmpeg parameters in this line only for the above modes
|
||||
ifile=sfile[:-4]+".avi"
|
||||
ffmpeg_convert(ofile,param,ifile)
|
||||
ProcessLabel.configure(text='STEP 2/3 MOSHING...')
|
||||
mfile=sfile[:-4]+"_corrupted.avi"
|
||||
if current=="Classic":
|
||||
classic.Datamosh(ifile, mfile,s=int(start_mosh.get()),e=int(end_mosh.get()),p=varp.get(), fps=vid.get_meta_data()['fps'])
|
||||
elif current=="Repeat":
|
||||
repeat.Datamosh(ifile, mfile, s=int(start_frame_mosh.get()), e=int(end_frame_mosh.get()), p=varp.get(), fps=vid.get_meta_data()['fps'])
|
||||
elif current=="Glide":
|
||||
pymodes.library.glide(varp.get(), ifile, mfile)
|
||||
elif current=="Sort":
|
||||
pymodes.library.avi_sort(ifile, mfile, mode=keepsort.get(), rev=reversesort.get())
|
||||
elif current=="Echo":
|
||||
pymodes.library.process_streams(ifile, mfile, mid=round(mid_point.get(),1))
|
||||
os.remove(ifile)
|
||||
ProcessLabel.configure(text='STEP 3/3 FIXING THE CORRUPTED FILE...')
|
||||
ffmpeg_convert(mfile,param,sfile)
|
||||
os.remove(mfile)
|
||||
else:
|
||||
time.sleep(1)
|
||||
ProcessLabel.configure(text='STEP 2/3 MOSHING...')
|
||||
mfile=sfile[:-4]+"_corrupted.mpg"
|
||||
if current=="Fluid":
|
||||
basic_modes.library(ofile, mfile, mode=3, fluidity=int(slider_fluid.get()), gop=kf.get())
|
||||
elif current=="Stretch":
|
||||
basic_modes.library(ofile, mfile, mode=2, vh=v_h.get(), gop=kf.get())
|
||||
elif current=="Motion Transfer":
|
||||
if vfile:
|
||||
basic_modes.library(ofile, mfile, mode=1, extract_from=vfile, gop=kf.get())
|
||||
else:
|
||||
tkinter.messagebox.showinfo("No Vector File imported!", "Please choose the video from where you want to extract the vector motion.")
|
||||
button_mosh.configure(state=tkinter.NORMAL)
|
||||
ProcessLabel.configure(text='Choose any secondary video file for transfering the vectors!')
|
||||
return
|
||||
elif current=="Shuffle":
|
||||
basic_modes.library(ofile, mfile, mode=4, size=int(shuf_slider.get()), gop=kf.get())
|
||||
elif current=="Rise":
|
||||
basic_modes.library(ofile, mfile, mode=5, s=int(start_frame_mosh.get()), e=int(end_frame_mosh.get()-start_frame_mosh.get()), gop=kf.get())
|
||||
elif current=="Custom Script":
|
||||
external_script.mosh(ofile, mfile, mode=1, scriptfile=scriptfile, gop=kf.get())
|
||||
else:
|
||||
external_script.mosh(ofile, mfile, mode=2, effect=current, gop=kf.get())
|
||||
ProcessLabel.configure(text='STEP 3/3 FIXING THE CORRUPTED FILE...')
|
||||
if hw_auto.get()==1:
|
||||
hw_type=' -hwaccel auto '
|
||||
else:
|
||||
hw_type=''
|
||||
ffmpeg_convert(mfile,param,sfile,extra=hw_type)
|
||||
os.remove(mfile)
|
||||
except:
|
||||
pass
|
||||
#Check the result and complete the task
|
||||
if os.path.exists(sfile):
|
||||
tkinter.messagebox.showinfo("Exported!", "File exported successfully, \nFile Location:" +str(sfile))
|
||||
ProcessLabel.configure(text="Last used: "+current)
|
||||
button_mosh.configure(state=tkinter.NORMAL)
|
||||
else:
|
||||
tkinter.messagebox.showerror("Oops!", "Something went wrong! \nPlease recheck the settings and try again.")
|
||||
ProcessLabel.configure(text='Recheck the settings and try again!')
|
||||
button_mosh.configure(state=tkinter.NORMAL)
|
||||
|
||||
#Bottom Part
|
||||
ProcessLabel = customtkinter.CTkLabel(master=frame_right,
|
||||
width=400, height=30,corner_radius=10,
|
||||
text="START DATAMOSHING!", fg_color=("white", "gray38"))
|
||||
ProcessLabel.place(x=20,y=430)
|
||||
button_mosh = customtkinter.CTkButton(master=frame_right, height=30,width=110,corner_radius=10,
|
||||
text="MOSH", command=Threadthis)
|
||||
button_mosh.place(x=430,y=430)
|
||||
self.mainloop()
|
||||
|
||||
#--------------------------------------------------------------------#
|
||||
0
Python Version/FFglitch/FFglitch goes here
Normal file
0
Python Version/FFglitch/FFglitch goes here
Normal file
127
Python Version/Setup.py
Normal file
127
Python Version/Setup.py
Normal file
@@ -0,0 +1,127 @@
|
||||
#Automatic Setup for Datamosher-Pro
|
||||
#Author: Akash Bora
|
||||
|
||||
#Importing some built in modules
|
||||
import subprocess
|
||||
import pkg_resources
|
||||
import sys
|
||||
import time
|
||||
import os
|
||||
import shutil
|
||||
from zipfile import ZipFile
|
||||
|
||||
DIRPATH = os.path.dirname(os.path.realpath(__file__))
|
||||
#Checking the required folders
|
||||
folders= ["Assets","FFglitch","DatamoshLib","pymosh"]
|
||||
missingfolder=[]
|
||||
for i in folders:
|
||||
if not os.path.exists(i):
|
||||
missingfolder.append(i)
|
||||
if missingfolder:
|
||||
print("These folder(s) not available: "+str(missingfolder))
|
||||
print("Download them from the repository properly")
|
||||
sys.exit()
|
||||
else:
|
||||
print("All folders available!")
|
||||
|
||||
#Checking required modules
|
||||
required = {'imageio', 'imageio-ffmpeg', 'numpy', 'customtkinter', 'pillow', 'rangeslider', 'requests'}
|
||||
installed = {pkg.key for pkg in pkg_resources.working_set}
|
||||
missing = required - installed
|
||||
missingset=[*missing,]
|
||||
|
||||
#Download the modules if not installed
|
||||
if missing:
|
||||
res=input("Some modules are not installed \n do you want to download and install them? (Y/N): ")
|
||||
while not ((res=="Y") or (res=="y") or (res=="N") or (res=="n")):
|
||||
print("Please choose a valid option!")
|
||||
res=input("Some modules are not installed \n do you want to download and install them? (Y/N): ")
|
||||
if res=="Y" or res=="y":
|
||||
try:
|
||||
print("Installing modules...")
|
||||
for x in range(len(missingset)):
|
||||
y=missingset[x]
|
||||
if sys.platform.startswith("win"):
|
||||
subprocess.call('python -m pip install '+y, shell=True)
|
||||
else:
|
||||
subprocess.call('python3 -m pip install '+y, shell=True)
|
||||
except:
|
||||
print("Unable to download! \nThis are the required ones: "+str(required)+"\nUse 'pip install module_name' to download the modules one by one")
|
||||
time.sleep(3)
|
||||
sys.exit()
|
||||
elif res=="N" or res=="n":
|
||||
print("Without the modules you can't use this program. Please install them first! \nThis are the required one: "+str(required)
|
||||
+"\nUse 'pip install module_name' to download modules one by one")
|
||||
time.sleep(3)
|
||||
sys.exit()
|
||||
else:
|
||||
print("All modules installed!")
|
||||
|
||||
#Check FFglitch Status
|
||||
def checkffglitch():
|
||||
print("Checking FFglitch:")
|
||||
print("Running ffgac...")
|
||||
ffgac=str(DIRPATH).replace(os.sep, '/')+"/FFglitch/ffgac"
|
||||
ffedit=str(DIRPATH).replace(os.sep, '/')+"/FFglitch/ffedit"
|
||||
try:
|
||||
subprocess.Popen(f'"{ffgac}" -version', shell=True)
|
||||
except:
|
||||
print("permission denied! Please give permission to ffgac to execute.")
|
||||
time.sleep(1)
|
||||
print("Running ffedit...")
|
||||
try:
|
||||
subprocess.Popen(f'"{ffedit}" -version', shell=True)
|
||||
except:
|
||||
print("permission denied! Please give permission to ffedit to execute.")
|
||||
time.sleep(1)
|
||||
print("Done...")
|
||||
|
||||
#Download ffglitch if not available
|
||||
if (os.path.exists("FFglitch/ffgac") or os.path.exists("FFglitch/ffgac.exe")) and (os.path.exists("FFglitch/ffedit") or os.path.exists("FFglitch/ffedit.exe")):
|
||||
checkffglitch()
|
||||
else:
|
||||
print("ffgac/ffedit not found inside ffglitch folder, you cannot run the ffglitch modes without these programs")
|
||||
res2=input("Do you want to download ffglitch now? (Y/N): ")
|
||||
while not ((res2=="Y") or (res2=="y") or (res2=="N") or (res2=="n")):
|
||||
print("Please choose a valid option!")
|
||||
res2=input("Do you want to download ffglitch now? (Y/N): ")
|
||||
if res2=="Y" or res2=="y":
|
||||
print("Downloading FFglitch...(size: approx 17MB)")
|
||||
if sys.platform.startswith("win"): #download ffglitch for windows
|
||||
URL = "https://github.com/Akascape/FFglitch-0.9.3-executables/releases/download/zip-packages/ffglitch-0.9.3-win64.zip"
|
||||
elif sys.platform.startswith("linux"): #download ffglitch for linux
|
||||
URL = "https://github.com/Akascape/FFglitch-0.9.3-executables/releases/download/zip-packages/ffglitch-0.9.3-linux64.zip"
|
||||
else: #download ffglitch for mac
|
||||
URL = "https://github.com/Akascape/FFglitch-0.9.3-executables/releases/download/zip-packages/ffglitch-0.9.3-mac64.zip"
|
||||
try:
|
||||
try:
|
||||
import requests
|
||||
response = requests.get(URL)
|
||||
open("FFglitch//ffglitch.zip", "wb").write(response.content)
|
||||
except:
|
||||
print("Unable to download ffglitch from site! Check your connection or download it manually from https://github.com/Akascape/FFglitch-0.9.3-executables \nand paste the files (ffgac and ffedit) inside FFglitch folder.")
|
||||
time.sleep(3)
|
||||
sys.exit()
|
||||
time.sleep(1)
|
||||
print("Exctracting the files...")
|
||||
try:
|
||||
with ZipFile('FFglitch/ffglitch.zip', 'r') as zip:
|
||||
zip.extractall('FFglitch/')
|
||||
except:
|
||||
print("Failed to extract ffglitch.zip, please extract it manually in the FFglitch folder.")
|
||||
time.sleep(3)
|
||||
sys.exit()
|
||||
if os.path.exists("FFglitch/ffgac") or os.path.exists("FFglitch/ffgac.exe"):
|
||||
os.remove("FFglitch//ffglitch.zip")
|
||||
time.sleep(1)
|
||||
checkffglitch()
|
||||
print("FFglitch setup complete!")
|
||||
except:
|
||||
print("Something went wrong!")
|
||||
elif res2=="N" or res2=="n":
|
||||
print("ffglitch modes cannot run without ffgac and ffedit, download them manually and paste them inside the FFglitch folder.")
|
||||
|
||||
#Everything done!
|
||||
print("Setup Complete!")
|
||||
time.sleep(5)
|
||||
sys.exit()
|
||||
7
Python Version/pymosh/LICENSE.txt
Normal file
7
Python Version/pymosh/LICENSE.txt
Normal file
@@ -0,0 +1,7 @@
|
||||
Copyright (c) 2011 - 2014 Joe Friedl
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
27
Python Version/pymosh/__init__.py
Normal file
27
Python Version/pymosh/__init__.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from .container import avi
|
||||
|
||||
__all__ = ['Index']
|
||||
|
||||
|
||||
class Index(object):
|
||||
"""Index is an index of video frame data."""
|
||||
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def from_file(filename: str):
|
||||
instance = Index()
|
||||
instance.filename = filename
|
||||
instance.index = None
|
||||
|
||||
# Assume AVI for now
|
||||
instance.index = avi.AVIFile.from_file(filename)
|
||||
|
||||
return instance
|
||||
|
||||
def __getattr__(self, index):
|
||||
return getattr(self.index, index)
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.index)
|
||||
0
Python Version/pymosh/codec/__init__.py
Normal file
0
Python Version/pymosh/codec/__init__.py
Normal file
6
Python Version/pymosh/codec/mpeg4.py
Normal file
6
Python Version/pymosh/codec/mpeg4.py
Normal file
@@ -0,0 +1,6 @@
|
||||
IFRAME_HEADER = b'\x00\x00\x01\xb0'
|
||||
|
||||
|
||||
def is_iframe(frame):
|
||||
"""Determine whether frame is an I frame."""
|
||||
return frame[:4] == IFRAME_HEADER
|
||||
0
Python Version/pymosh/container/__init__.py
Normal file
0
Python Version/pymosh/container/__init__.py
Normal file
124
Python Version/pymosh/container/avi.py
Normal file
124
Python Version/pymosh/container/avi.py
Normal file
@@ -0,0 +1,124 @@
|
||||
import struct
|
||||
|
||||
from pymosh.codec.mpeg4 import is_iframe
|
||||
|
||||
from . import riff
|
||||
|
||||
|
||||
class AVIFile(object):
|
||||
"""A wrapper for AVI files."""
|
||||
|
||||
def __init__(self):
|
||||
self.riff = riff.RiffIndex()
|
||||
self.streams = []
|
||||
self.frame_order = []
|
||||
|
||||
@staticmethod
|
||||
def from_file(filename: str):
|
||||
instance = AVIFile()
|
||||
|
||||
instance.riff = riff.RiffIndex.from_file(filename=filename)
|
||||
|
||||
header = instance.riff.find(b'LIST', b'hdrl')
|
||||
# Get stream info
|
||||
stream_lists = header.find_all(b'LIST', b'strl')
|
||||
for l in stream_lists:
|
||||
strh = l.find(b'strh')
|
||||
data = strh.data
|
||||
fccType, = struct.unpack(b'4s', data[:4])
|
||||
stream = Stream(len(instance.streams), fccType)
|
||||
instance.streams.append(stream)
|
||||
|
||||
instance.split_streams()
|
||||
|
||||
return instance
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.streams)
|
||||
|
||||
def add_frame(self, chunk):
|
||||
stream_num = int(chunk.header[:2])
|
||||
if stream_num < len(self.streams):
|
||||
self.frame_order.append(
|
||||
(stream_num, len(self.streams[stream_num])))
|
||||
self.streams[stream_num].add_frame(chunk)
|
||||
|
||||
def split_streams(self):
|
||||
movi = self.riff.find(b'LIST', b'movi')
|
||||
for chunk in movi:
|
||||
self.add_frame(chunk)
|
||||
|
||||
def combine_streams(self):
|
||||
chunks = []
|
||||
for frame_record in self.frame_order:
|
||||
stream_num, frame_num = frame_record
|
||||
stream = self.streams[stream_num]
|
||||
frame = stream[frame_num]
|
||||
chunks.append(frame)
|
||||
return chunks
|
||||
|
||||
def _video(self):
|
||||
return filter(lambda stream: stream.type == b'vids', self.streams)
|
||||
video = property(_video)
|
||||
|
||||
def _audio(self):
|
||||
return filter(lambda stream: stream.type == b'auds', self.streams)
|
||||
audio = property(_audio)
|
||||
|
||||
def rebuild(self):
|
||||
"""Rebuild RIFF tree and index from streams."""
|
||||
movi = self.riff.find(b'LIST', b'movi')
|
||||
movi.chunks = self.combine_streams()
|
||||
self.rebuild_index()
|
||||
|
||||
def rebuild_index(self):
|
||||
old_index = self.riff.find(b'idx1')
|
||||
movi = self.riff.find(b'LIST', b'movi')
|
||||
data = b''
|
||||
offset = 0
|
||||
flags = {
|
||||
'base': 0x00000000,
|
||||
'keyframe': 0x00000010,
|
||||
}
|
||||
for chunk in movi:
|
||||
length = len(chunk)
|
||||
frame_flags = flags['base']
|
||||
# If it's a video keyframe or audio frame, use keyframe flag
|
||||
if (chunk.header[2] == b'd' and is_iframe(chunk)) or (chunk.header[2] == b'w'):
|
||||
frame_flags |= flags['keyframe']
|
||||
data += struct.pack(b'<4sIII', chunk.header, frame_flags, offset,
|
||||
length+8)
|
||||
offset += length + 8 + (length % 2)
|
||||
new_index = riff.RiffDataChunk(b'idx1', data)
|
||||
self.riff.find(b'RIFF').replace(old_index, new_index)
|
||||
|
||||
def write(self, fh):
|
||||
self.riff.write(fh)
|
||||
|
||||
|
||||
class Stream(object):
|
||||
def __init__(self, num, stream_type):
|
||||
self.num = int(num)
|
||||
self.type = stream_type
|
||||
self.chunks = []
|
||||
|
||||
def add_frame(self, chunk):
|
||||
self.chunks.append(chunk)
|
||||
|
||||
def __getitem__(self, index):
|
||||
return self.chunks.__getitem__(index)
|
||||
|
||||
def __iter__(self):
|
||||
return self.chunks.__iter__()
|
||||
|
||||
def __len__(self):
|
||||
return len(self.chunks)
|
||||
|
||||
def append(self, *args):
|
||||
return self.chunks.append(*args)
|
||||
|
||||
def extend(self, *args):
|
||||
return self.chunks.extend(*args)
|
||||
|
||||
def replace(self, chunks):
|
||||
self.chunks = chunks
|
||||
263
Python Version/pymosh/container/riff.py
Normal file
263
Python Version/pymosh/container/riff.py
Normal file
@@ -0,0 +1,263 @@
|
||||
import os
|
||||
import struct
|
||||
from io import IOBase
|
||||
|
||||
list_headers = (b'RIFF', b'LIST')
|
||||
|
||||
|
||||
class UnexpectedEOF(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class RiffIndexChunk(object):
|
||||
def __init__(self, fh, header, length, position):
|
||||
self.file = fh
|
||||
self.header = header
|
||||
self.length = int(length)
|
||||
self.position = position
|
||||
|
||||
def __str__(self):
|
||||
return str(self.bytes())
|
||||
|
||||
def bytes(self) -> bytes:
|
||||
return self.header + struct.pack('<I', self.length) + self.data
|
||||
|
||||
def __len__(self):
|
||||
return self.length
|
||||
|
||||
def __getslice__(self, start, end):
|
||||
if start is None:
|
||||
start = 0
|
||||
if end is None:
|
||||
end = self.length
|
||||
|
||||
current = self.file.tell()
|
||||
self.file.seek(self.position+start)
|
||||
if start < end and start <= self.length:
|
||||
if end > self.length:
|
||||
end = self.length
|
||||
data = self.file.read(end-start)
|
||||
self.file.seek(current)
|
||||
return data
|
||||
else:
|
||||
return ''
|
||||
|
||||
def __getitem__(self, index):
|
||||
if isinstance(index, slice):
|
||||
return self.__getslice__(index.start, index.stop)
|
||||
return self[index:index+1]
|
||||
|
||||
def _data(self):
|
||||
"""Read data from the file."""
|
||||
current_position = self.file.tell()
|
||||
self.file.seek(self.position)
|
||||
data = self.file.read(self.length)
|
||||
self.file.seek(current_position)
|
||||
if self.length % 2:
|
||||
data += b'\x00' # Padding byte
|
||||
return data
|
||||
data = property(_data)
|
||||
|
||||
def as_data(self):
|
||||
"""Return a RiffDataChunk read from the file."""
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class RiffIndexList(RiffIndexChunk):
|
||||
def __init__(self, header, list_type, *args, **kwargs):
|
||||
self.header = header
|
||||
self.type = list_type
|
||||
self.file = kwargs.get('file', None)
|
||||
self.position = kwargs.get('position', 0)
|
||||
self.chunks = kwargs.get('chunks', [])
|
||||
|
||||
def __getitem__(self, index):
|
||||
return self.chunks[index]
|
||||
|
||||
def __setitem__(self, index, value):
|
||||
return self.chunks.__setitem__(index, value)
|
||||
|
||||
def __delitem__(self, index):
|
||||
return self.chunks.__delitem__(index)
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.chunks)
|
||||
|
||||
def __len__(self):
|
||||
"""Return total data length of the list and its headers."""
|
||||
return self.chunk_length() + len(self.type) + len(self.header) + 4
|
||||
|
||||
def chunk_length(self):
|
||||
length = 0
|
||||
for chunk in self.chunks:
|
||||
chunk_len = len(chunk)
|
||||
length += chunk_len + 8 # Header and length bytes
|
||||
length += chunk_len % 2 # Pad byte
|
||||
return length
|
||||
|
||||
def __str__(self):
|
||||
return str(self.bytes())
|
||||
|
||||
def bytes(self) -> bytes:
|
||||
"""Returns a byte representation of the chunk."""
|
||||
length_bytes = struct.pack('<I', self.chunk_length() + len(self.type))
|
||||
return self.header + length_bytes + self.type
|
||||
|
||||
class NotFound(Exception):
|
||||
"""Indicates a chunk or list was not found by the find method."""
|
||||
pass
|
||||
|
||||
def find(self, header, list_type=None):
|
||||
"""Find the first chunk with specified header and optional list type."""
|
||||
for chunk in self:
|
||||
if chunk.header == header and (list_type is None or (header in
|
||||
list_headers and chunk.type == list_type)):
|
||||
return chunk
|
||||
elif chunk.header in list_headers:
|
||||
try:
|
||||
result = chunk.find(header, list_type)
|
||||
return result
|
||||
except chunk.NotFound:
|
||||
pass
|
||||
if list_type is None:
|
||||
raise self.NotFound('Chunk \'{0}\' not found.'.format(header))
|
||||
else:
|
||||
raise self.NotFound('List \'{0} {1}\' not found.'.format(header,
|
||||
list_type))
|
||||
|
||||
def find_all(self, header, list_type=None):
|
||||
"""Find all direct children with header and optional list type."""
|
||||
found = []
|
||||
for chunk in self:
|
||||
if chunk.header == header and (not list_type or (header in
|
||||
list_headers and chunk.type == list_type)):
|
||||
found.append(chunk)
|
||||
return found
|
||||
|
||||
def replace(self, child, replacement):
|
||||
"""Replace a child chunk with something else."""
|
||||
for i in range(len(self.chunks)):
|
||||
if self.chunks[i] == child:
|
||||
self.chunks[i] = replacement
|
||||
|
||||
def remove(self, child):
|
||||
"""Remove a child element."""
|
||||
for i in range(len(self)):
|
||||
if self[i] == child:
|
||||
del self[i]
|
||||
|
||||
|
||||
class RiffDataChunk(object):
|
||||
"""A RIFF chunk with data in memory instead of a file."""
|
||||
|
||||
def __init__(self, header, data):
|
||||
self.header = header
|
||||
self.length = len(data)
|
||||
self.data = data
|
||||
|
||||
@staticmethod
|
||||
def from_data(data):
|
||||
"""Create a chunk from data including header and length bytes."""
|
||||
header, _ = struct.unpack('4s<I', data[:8])
|
||||
data = data[8:]
|
||||
return RiffDataChunk(header, data)
|
||||
|
||||
def bytes(self) -> bytes:
|
||||
"""Returns a byte array representation of the chunk."""
|
||||
return self.header + struct.pack('<I', self.length) + self.data
|
||||
|
||||
def __str__(self):
|
||||
return str(self.bytes())
|
||||
|
||||
def __len__(self):
|
||||
return self.length
|
||||
|
||||
def __getslice__(self, start, end):
|
||||
return self.data[start:end]
|
||||
|
||||
def __getitem__(self, index):
|
||||
return self.data[index]
|
||||
|
||||
|
||||
class RiffIndex(RiffIndexList):
|
||||
def __init__(self):
|
||||
self.file = None
|
||||
self.chunks = []
|
||||
|
||||
@staticmethod
|
||||
def from_file(filename: str):
|
||||
instance = RiffIndex()
|
||||
|
||||
instance.file = open(filename, 'rb')
|
||||
instance.size = instance.get_size()
|
||||
instance.scan_file()
|
||||
|
||||
return instance
|
||||
|
||||
def write(self, fh: IOBase) -> None:
|
||||
def print_chunks(chunks):
|
||||
for chunk in chunks:
|
||||
fh.write(chunk.bytes())
|
||||
if chunk.header in (b'RIFF', b'LIST'):
|
||||
print_chunks(chunk.chunks)
|
||||
|
||||
print_chunks(self.chunks)
|
||||
|
||||
def get_size(self):
|
||||
current = self.file.tell()
|
||||
self.file.seek(0, 2)
|
||||
size = self.file.tell()
|
||||
self.file.seek(current)
|
||||
return size
|
||||
|
||||
def readlen(self, length):
|
||||
buf = self.file.read(length)
|
||||
if len(buf) == length:
|
||||
return buf
|
||||
else:
|
||||
raise UnexpectedEOF(
|
||||
'End of file reached after {0} bytes.'.format(len(buf)))
|
||||
|
||||
def scan_file(self):
|
||||
header = self.readlen(4)
|
||||
if header == b'RIFF':
|
||||
length, list_type = struct.unpack('<I4s', self.readlen(8))
|
||||
chunks = self.scan_chunks(length-4)
|
||||
self.chunks.append(RiffIndexList(header, list_type, file=self.file,
|
||||
position=0, chunks=chunks))
|
||||
else:
|
||||
raise Exception('Not a RIFF file!')
|
||||
|
||||
def scan_chunks(self, data_length):
|
||||
chunks = []
|
||||
total_length = 0
|
||||
while total_length < data_length:
|
||||
header = self.readlen(4)
|
||||
total_length += 4
|
||||
|
||||
length, = struct.unpack('<I', self.file.read(4))
|
||||
total_length += length + 4 # add 4 for itself
|
||||
|
||||
position = self.file.tell()
|
||||
|
||||
if header in list_headers:
|
||||
list_type = self.readlen(4)
|
||||
data = self.scan_chunks(length-4)
|
||||
if length % 2:
|
||||
# Padding byte
|
||||
self.file.seek(1, os.SEEK_CUR)
|
||||
total_length += 1
|
||||
chunks.append(RiffIndexList(header, list_type, file=self.file,
|
||||
position=position, chunks=data))
|
||||
else:
|
||||
self.file.seek(length, os.SEEK_CUR)
|
||||
if length % 2:
|
||||
# Padding byte
|
||||
self.file.seek(1, os.SEEK_CUR)
|
||||
total_length += 1
|
||||
chunks.append(RiffIndexChunk(
|
||||
self.file, header, length, position))
|
||||
return chunks
|
||||
|
||||
def close(self):
|
||||
self.file.close()
|
||||
Reference in New Issue
Block a user