0% found this document useful (0 votes)
10 views12 pages

Premiere Script

The document is a script for Adobe Premiere Pro that automates various tasks related to video editing, including importing audio and image files, setting keyframes, and adjusting clip properties. It defines functions for reading files, selecting file types, and managing project settings based on a JSON configuration. The script also handles the creation of sequences and the arrangement of clips on different tracks, allowing for efficient video production workflows.

Uploaded by

a1scroptnik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views12 pages

Premiere Script

The document is a script for Adobe Premiere Pro that automates various tasks related to video editing, including importing audio and image files, setting keyframes, and adjusting clip properties. It defines functions for reading files, selecting file types, and managing project settings based on a JSON configuration. The script also handles the creation of sequences and the arrangement of clips on different tracks, allowing for efficient video production workflows.

Uploaded by

a1scroptnik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

#target premierepro

app.enableQE();

var AUDIO_FORMATS = ["MP3", "AIFF", "AIF", "WAV", "MOV"]


var PICTURE_FORMATS = ["AI", "EPS", "BMP", "DIB", "RLE", "EPS", "GIF", "ICO",
"JPEG", "JPE", "JPG", "JFIF", "PNG", "PSD", "PTL", "PRTL", "TGA", "ICB", "VDA",
"VST", "TIFF"]
var RANDOMIZE_MATRIX = [[0, 1], [0, -1], [1, 0], [-1, 0]] //x and y axis motion
and direction
var MAGIC_TEMPORAL_KEY_SHIFT = 3599.9964
var SECURITY_SHIFT = 0
var START = 0
var END = -1
var FADE_BACKGROUND = 0

function readFile(filePath){
file = new File(filePath);
file.open("r", "TEXT");
var fileString = "";
while (!file.eof){
var line = file.readln();
if (fileString.indexOf(line) == -1){
fileString += line;
}
}
return fileString;
}

function readTextFile(filePath) {
var file = new File(filePath);

if (file.exists) {
file.open('r'); // Открыть файл для чтения
var content = file.read(); // Чтение содержимого файла
file.close(); // Закрыть файл

return content;
} else {
alert("Файл не найден: " + filePath);
return null;
}
}

function getClipAt(seconds, track){


for (var c = 0; c < track.clips.length; c++) {
if (track.clips[c].start.seconds <= seconds &
track.clips[c].end.seconds >= seconds){
return track.clips[c]
}
}
}

function add_keyframe(prop, t, clip){


if (!prop.isTimeVarying()){
prop.setTimeVarying(true)
}
if (select_by_ext(clip.name, PICTURE_FORMATS)){
t = t+MAGIC_TEMPORAL_KEY_SHIFT+SECURITY_SHIFT
}
if (!prop.keyExistsAtTime(t)){
prop.addKey(t)
}
}

function calculate_offset(clip1, clip2, st_end){


offs = 0-clip1.duration.seconds*st_end
if (!clip2){
return offs
}
offs += clip1.start.seconds - clip2.start.seconds
return offs
}

function set_keys_for_clip(clip, st_end, offs){


opa_prop = clip.components[0].properties[0]
add_keyframe(opa_prop, offs, clip)
eeee = st_end*2 + 1 //Convert 0;-1 to 1;-1
add_keyframe(opa_prop, offs + OPACITY_TIME*eeee, clip)
}

function set_opacity(clip, st_end){


opac_vals = [100, 100 - OPACITY_FADE]
if (!st_end){
opac_vals = [100 - OPACITY_FADE, 100]
}
opa_prop = clip.components[0].properties[0]
vvvv = opa_prop.getKeys()
opa_prop.setValueAtKey(vvvv[vvvv.length-2], opac_vals[0])
opa_prop.setValueAtKey(vvvv[vvvv.length-1], opac_vals[1])
return vvvv.slice(-2)
}

function clip_pipelile(clip1, clip2, clip_appy_effect_to, st_end){


offs = calculate_offset(clip1, clip2, st_end)
set_keys_for_clip(clip_appy_effect_to, st_end, offs)
return set_opacity(clip_appy_effect_to, st_end)
}

function keyframe_to_track_time(kfr, clip){


return kfr.seconds-MAGIC_TEMPORAL_KEY_SHIFT+SECURITY_SHIFT +
clip.start.seconds}

function set_opa_both(clip, track_with_backstage, st_end){


vv = clip_pipelile(clip, 0, clip, st_end)
if(FADE_BACKGROUND){
clip2 = getClipAt(keyframe_to_track_time(vv[0], clip),
track_with_backstage)
clip_pipelile(clip, clip2, clip2, st_end)
clip3 = getClipAt(keyframe_to_track_time(vv[1], clip),
track_with_backstage)
clip_pipelile(clip, clip3, clip3, st_end)
}
}

function string_ends_with(str_where_find, what_to_find){


if(typeof(str_where_find) !== "string" || typeof(what_to_find) !== "string") {
return false
}
if(str_where_find.length < what_to_find.length){
return false
}
string_end = str_where_find.slice(-what_to_find.length)
return string_end === what_to_find
}

//Find whether the current file has one of specified extensions


function select_by_ext(current_file, extensionz) {
for (var ei = 0; ei < extensionz.length; ei++) {
var file_name = current_file.toString()
if (typeof(file_name) != 'string'){
file_name = file_name.toString()
}
file_name = file_name.toUpperCase()
condition = string_ends_with(file_name, ".".concat(extensionz[ei]))
if (condition){
return true
}
}
return false
}

function select_by_ext_list(filez, extensionz) {


var selected = []
for (var fi = 0; fi < filez.length; fi++) {
if(select_by_ext(filez[fi], extensionz)){
selected.push(filez[fi].fsName)
}
}
return selected
}

function compareNames(n1, n2)


{
a = parseInt(File(n1).name, 10)
b = parseInt(File(n2).name, 10)
return a - b;
}

function add_back_clip(etiting_track, adding_item, audio_index, video_index){


var t = app.project.sequences[0].audioTracks[1].clips[0].start
finish_time =
app.project.sequences[0].videoTracks[1].clips[app.project.sequences[0].videoTracks[
1].clips.length-1].end
while (t.seconds < finish_time.seconds){
etiting_track.overwriteClip(adding_item, t) //, video_index, audio_index
var inserted_num = etiting_track.clips.length
t.setSecondsAsFraction(t.seconds + etiting_track.clips[inserted_num-
1].duration.seconds, 1)
}
etiting_track.clips[inserted_num-1].end = finish_time
}

function set_loudness(track, value){


for(var c = 0; c < track.clips.length; c++) {
loud_prop = track.clips[c].components[0].properties[1]
loud_val = Math.pow(10, (value-15)/20)
loud_prop.setValue(loud_val)
}
}

function get_item_size(aaa_item){
start_string = ".Intrinsic.VideoInfo>"
full_string = aaa_item.getProjectMetadata()
start_index = full_string.indexOf(start_string) + start_string.length
number_substring = full_string.slice(start_index)
x_size = parseInt(number_substring, 10)
start_string = ' x '
start_index = number_substring.indexOf(start_string) + start_string.length
number_substring = number_substring.slice(start_index)
y_size = parseInt(number_substring, 10)
return [x_size, y_size]
}

function getSizeFromFile(folder){
var sizesX = readTextFile(folder + "/" + "sizeX.txt");
var sizesY = readTextFile(folder + "/" + "sizeY.txt");
return [sizesX, sizesY];
}

function getRealSize(sizesRaw){
sizesRaw = sizesRaw.replace("[", '');
sizesRaw = sizesRaw.replace("]", '');

sizes = sizesRaw.split(',');
return sizes;
}

function get_shotname(path) {
var parts = path.split("\\");
const fileNameWithExtension = parts[parts.length - 1];
const fileName = fileNameWithExtension.split('.')[0];
return fileName;
}

var rootPath = File($.fileName).parent;


$.evalFile(rootPath + '\\extendscript-json\\index.jsx');

var settingz_text = readFile(rootPath + "\\settings.JSON")


var settingz = JSON.parse(settingz_text);

var CUR_FILENAME= readFile(rootPath + "\\cur_filename.txt")


var CUR_FILENAME_short= get_shotname(CUR_FILENAME);

var DESIRED_SCALE = Number(settingz.eff_scl)


var motion_coeff = Number(settingz.eff_off)
var OPACITY_FADE = Number(settingz.eff_tran)
var OPACITY_TIME = Number(settingz.eff_dur)

var cur_isBack = Number(settingz.back_img) // set current image on


background
var logo_size = Number(settingz.logo_size) // size logo
var is_logo = Number(settingz.is_logo) // add logo
var is_ftg = Number(settingz.is_ftg) // add footage
var AUDIO_PAUSE = Number(settingz.audio_pause) // add footage

var proj_root = File(settingz.save_to) // .parent


var prjName = settingz.save_to.split('\\').pop().split('/').pop()
var pth_to_prj = File(proj_root.toString()
+"\\"+CUR_FILENAME_short+".prproj").fsName
$.writeln(pth_to_prj);

$.writeln("Проверка перед созданием проекта:");


$.writeln("pth_to_prj: " + pth_to_prj);
$.writeln("Существует ли файл: " + File(pth_to_prj).exists);
$.writeln("app.project: " + app.project);
$.writeln("app.isDocumentOpen: " + app.isDocumentOpen());
app.newProject(pth_to_prj)
$.writeln("app.isDocumentOpen: " + app.isDocumentOpen());

var processed_media_root = (rootPath + "/TEMP/" +


decodeURIComponent(CUR_FILENAME_short) + "_TEMP");
$.writeln(processed_media_root);

var importFolder = Folder(processed_media_root.toString()+"\\audios")


var filez = importFolder.getFiles();
audio_files = select_by_ext_list(filez, AUDIO_FORMATS).sort(compareNames);

var importFolder = Folder(processed_media_root.toString()+"\\images")


var filez = importFolder.getFiles();

picture_files = select_by_ext_list(filez, PICTURE_FORMATS).sort(compareNames);

if (cur_isBack == true) {
var importFolder = Folder(processed_media_root.toString()+"\\backgrounds")
var filez = importFolder.getFiles();
back_files = select_by_ext_list(filez, PICTURE_FORMATS).sort(compareNames);
}

if(is_logo == true) {
var importFolder = Folder(processed_media_root.toString()+"\\logo")
var filez = importFolder.getFiles();
logo_files = select_by_ext_list(filez, PICTURE_FORMATS).sort(compareNames);
}

$.writeln("settingz.root: " + settingz.root);


$.writeln("processed_media_root.toString(): " + processed_media_root.toString());

$.writeln("audio_files: " + audio_files);


$.writeln("picture_files: " + picture_files);
app.project.importFiles(audio_files)
app.project.importFiles(picture_files)

if (cur_isBack == true) app.project.importFiles(back_files)


if(is_logo == true) app.project.importFiles(logo_files)

if (is_ftg == true) {
var importFolder = Folder(settingz.root + "\\Футаж")
var ftg_video = importFolder.getFiles();
app.project.importFiles(ftg_video[0].toString())

app.project.rootItem.children[app.project.rootItem.children.length-
1].setScaleToFrameSize();
}

// CHECK app
if (typeof app === "undefined" || !app || !app.project || !app.project.rootItem) {
$.writeln("ERROR: Проект не доступен или отсутствует rootItem");
throw new Error("Проект не доступен");
}

var projectItems = app.project.rootItem.children;


if (!projectItems || projectItems.length === 0) {
$.writeln("ERROR: В проекте нет элементов (app.project.rootItem.children
пуст)");
throw new Error("Проект пуст");
}

$.writeln("app.project.rootItem.children.length: " + projectItems.length);

clips = []
for (var c = 0; c < app.project.rootItem.children.length; c++) {
clips.push(app.project.rootItem.children[c])
}

//Import backstage files


if (cur_isBack == false) {
var importFolder = Folder(settingz.root + "\\Фоновый звук")
var back_audio = importFolder.getFiles();
var importFolder = Folder(settingz.root + "\\Фон")
var back_video = importFolder.getFiles();
app.project.importFiles(back_video[0].toString())
app.project.importFiles(back_audio[0].toString())
}

n = app.project.rootItem.children.length
// BACKGROUND
if (cur_isBack == true) app.project.createNewSequenceFromClips("newSequence",
app.project.rootItem.children[(audio_files.length*2)]);
if (cur_isBack == false) app.project.createNewSequenceFromClips("newSequence",
app.project.rootItem.children[n-2]);

//Set sequence size as backstage sizes


aa = app.project.sequences[0].getSettings()
if (Number(settingz.x) & Number(settingz.y)){
aa.videoFrameHeight= Number(settingz.y)
aa.videoFrameWidth= Number(settingz.x)
app.project.sequences[0].setSettings(aa)
}else{
try {
aaa_item = app.project.rootItem.children[n-2]
sizez = get_item_size(aaa_item)
x_size = sizez[0]
y_size = sizez[1]
aa.videoFrameHeight= y_size
aa.videoFrameWidth= x_size
app.project.sequences[0].setSettings(aa)
} catch(err) {
aa.videoFrameHeight= 1080
aa.videoFrameWidth= 1920
app.project.sequences[0].setSettings(aa)
}
}

previous_end_moment = '0'

if (cur_isBack == true) var back_videotrack =


app.project.sequences[0].videoTracks[0]; // back video - 0 track
var videotrack = app.project.sequences[0].videoTracks[1];
// main video - 1 track
if (is_logo == true) var logo_track = app.project.sequences[0].videoTracks[2];
// logo - 2 track

for (var c = 0; c < audio_files.length; c++) {


//VIDEO AND AUDIO
app.project.sequences[0].audioTracks[1].insertClip(clips[c],
previous_end_moment, 0, 0); //
insert audioclip

videotrack.insertClip(clips[c+audio_files.length], previous_end_moment, 0,
0); // insert
videoclip
if (cur_isBack == true) if(c!=0) back_videotrack.insertClip(clips[c+
(audio_files.length*2)], previous_end_moment, 0, 0); // insert background img
//if (is_ftg == true) ftg_track.insertClip(clips[clips.length-1],
previous_end_moment, 0, 0); // insert background img

videotrack.clips[c].start = previous_end_moment;

// set start videoclip


if (cur_isBack == true) back_videotrack.clips[c].start = previous_end_moment;
// set start
back
//if (is_ftg == true) ftg_track.clips[0].start = previous_end_moment;
// set start back

previous_end_moment = app.project.sequences[0].audioTracks[1].clips[c].end;
// update time end
audioclip
previous_end_moment.seconds = previous_end_moment.seconds + AUDIO_PAUSE
//$.writeln(previous_end_moment)
videotrack.clips[c].end = previous_end_moment;

// set end videoclip


if (cur_isBack == true) back_videotrack.clips[c].end = previous_end_moment;
// set end
back img
//if (is_ftg == true) ftg_track.clips[0].end = previous_end_moment;
// set end back
img

//if (is_ftg) {
// var blendProp = ftg_track.clips[0].components[0].properties[1];
// 5 - разница
// 14 - добавить
// blendProp.setValue(14);
// }
aaaaclcl = app.project.sequences[0].videoTracks[1].clips[c]
aaa_scl_prop = aaaaclcl.components[1].properties[1]
aaa_scl_prop.setValue(DESIRED_SCALE*100)

var size_coeff = [1, 1] //x, y


//Get actual sizes and scale
try {
aaa_item = app.project.rootItem.children[c+audio_files.length]
sizez = get_item_size(aaa_item)
x_size = sizez[0]
y_size = sizez[1]
//Set desired scale
previous_ratio = x_size/y_size
current_ratio = aa.videoFrameWidth/aa.videoFrameHeight
// If x/y decreased, motion in x direction is also decreased, in y
direction is increased.
size_coeff = [current_ratio/previous_ratio,
previous_ratio/current_ratio] //x, y
} catch(err) {

//Set keys for motion


aaa_prop = aaaaclcl.components[1].properties[0]
add_keyframe(aaa_prop, 0, aaaaclcl)
add_keyframe(aaa_prop, aaaaclcl.duration.seconds, aaaaclcl)
vvvv = aaa_prop.getKeys()
//Add motion to random direction
var random_index = Math.floor(Math.random() * 4)
var xy = RANDOMIZE_MATRIX[random_index]
var x = xy[0]*0.1
var y = xy[1]*0.1

if (y_size > x_size) {


random_index = Math.floor(Math.random() * 2);
x = (random_index === 0 ? -0.1 : 0.1);
y = 0;
} else {
random_index = Math.floor(Math.random() * 4);
var xy = RANDOMIZE_MATRIX[random_index];
x = xy[0] * 0.1;
y = xy[1] * 0.1;
}

aaa_prop.setValueAtKey(vvvv[0], [0.5, 0.5])


aaa_prop.setValueAtKey(vvvv[1], [0.5+x, 0.5+y])
}

function timeToMilliseconds(time) {
var totalMilliseconds = (time.seconds * 1000) + (time.minutes * 60 * 1000) +
(time.hours * 3600 * 1000);
return totalMilliseconds;
}

//Add cycled backstage

if (cur_isBack == false) {
add_back_clip(app.project.sequences[0].audioTracks[2],
app.project.rootItem.children[n-1], 0, 0)
add_back_clip(app.project.sequences[0].videoTracks[0],
app.project.rootItem.children[n-2], 0, 0)

app.project.sequences[0].audioTracks[0].clips[app.project.sequences[0].audioTracks[
0].clips.length-1].end =
app.project.sequences[0].videoTracks[0].clips[app.project.sequences[0].videoTracks[
0].clips.length-1].end
}

if(is_logo == true){
var logo_start = app.project.sequences[0].audioTracks[1].clips[0].start;
var logo_end = videotrack.clips[videotrack.clips.length-1].end

if (cur_isBack == true) logo_track.insertClip(clips[(audio_files.length*3)],


'0', 0, 0)
if (cur_isBack == false) logo_track.insertClip(clips[(audio_files.length*2)],
'0', 0, 0)
logo_track.clips[0].start = '0';
logo_track.clips[0].end = logo_end;

var logo_posProp = logo_track.clips[0].components[1].properties[0];


var logo_scaleProp = logo_track.clips[0].components[1].properties[1];

var posX = aa.videoFrameWidth-(aa.videoFrameWidth/12);


var posY = aa.videoFrameHeight-(aa.videoFrameHeight/8);

var lX = posX/aa.videoFrameWidth
var lY = posY/aa.videoFrameHeight

//setKey(logo_posProp, 0, [0,0]);
logo_posProp.setValue([lY, lY]);
logo_scaleProp.setValue(logo_size);
}
for (var c = 0; c < app.project.sequences[0].videoTracks[1].clips.length; c++) {
vid_clip = app.project.sequences[0].videoTracks[1].clips[c]

var aaa_item = app.project.rootItem.children[c + audio_files.length];


var sizez = get_item_size(aaa_item);

var scriptFile = new File($.fileName); // script file


var scriptFolder = scriptFile.parent; // script folder

var sizesFile = getSizeFromFile(scriptFolder); // get arrays of X and Y from


files in folder
var sizesX_file = sizesFile[0]; // X
var sizesY_file = sizesFile[1]; // Y

var x_size = Number(getRealSize(sizesX_file)[c]); // get size image


without shadow X
var y_size = Number(getRealSize(sizesY_file)[c]); //
Y

var scaleProp = vid_clip.components[1].properties[1]; // property of scale

if (y_size > x_size) { // vertical


var scale = aa.videoFrameHeight/y_size; // size
complement coeff
scaleProp.setValue((100*scale)*0.985*DESIRED_SCALE); // set scale.
vertical border image to vertical border screen
//alert(c+" is vertical.\nx_size: " + x_size + "\ny_size: " + y_size +
"\n y>x: " + (y_size>x_size) + "\n typeX: " + typeof(x_size) + "\n typeY: " +
typeof(y_size))
} else {
var x_ext = aa.videoFrameWidth-(aa.videoFrameWidth/8.7); // size
width/8
var y_ext = aa.videoFrameHeight-(aa.videoFrameHeight/6); // size
height/6

var scale = x_ext/x_size;


//alert("scale: " + scale + "\nx_size: " + x_size + "\ny_size: " +
y_size + "\nx_ext: " + x_ext + "\ny_ext: " + y_ext + "\nc: " + c)
if (scale*y_size <= y_ext) { // scale to vertical borders
scaleProp.setValue(100*scale*DESIRED_SCALE); // set scale
// alert("scale*y_size <= y_ext " + c);
} else { // scale to horisontal borders
var scale = y_ext/y_size;
scaleProp.setValue(100*scale*DESIRED_SCALE); // set scale
// alert("else " + c)
}
}
//SIZE BACKGROUND clips
if (cur_isBack == true){
var back_clip = back_videotrack.clips[c]
var back_scaleProp = back_clip.components[1].properties[1];

var cur_item = app.project.rootItem.children[c +


(audio_files.length*2)];
sizez = get_item_size(cur_item);

var x = sizez[0];
var y = sizez[1];

var scaleX = (aa.videoFrameWidth/x);


var scaleY = (aa.videoFrameHeight/y);

var min = Math.min(scaleX, scaleY);


var max = Math.max(scaleX, scaleY);

if((min*x >= aa.videoFrameWidth) && (min*y >= aa.videoFrameHeight)) {


var scale = 100*min;
}
else if((max*y >= aa.videoFrameHeight) && (max*x >=
aa.videoFrameWIdth)) {
var scale = 100*max;
}
else {
var scale = 500;
}

back_scaleProp.setValue(scale);
}
}

if (is_ftg == true) {
var QEseq = qe.project.getActiveSequence();
QEseq.addTracks(1, 3, 0, 0, 0, 0, 0);
var project = app.project;
var sequence = project.activeSequence;
var tracks = sequence.videoTracks;
var QEtrack3 = QEseq.getVideoTrackAt(3);
tracks[3].insertClip(clips[clips.length - 1], '0', 0, 0, 0);
var lastClip =
app.project.sequences[0].videoTracks[0].clips[app.project.sequences[0].videoTracks[
0].clips.length - 1];
var durG = lastClip.end.seconds;
ftg_track = app.project.sequences[0].videoTracks[3];

// Получаем длительность вставленного клипа


var insertedClip = ftg_track.clips[0];
var dur = insertedClip.duration.seconds;

// Рассчитываем количество вставок


var ct = Math.ceil(durG/dur);

//alert("Длительность оригинального клипа: " + durG + "\nДлительность


вставленного клипа: " + dur + "\nКоличество вставок: " + ct);

// Вставляем дополнительные клипы


for (var i = 1; i < ct; i++) {
var startTime = dur * i;
ftg_track.insertClip(clips[clips.length - 1], startTime, 0, 0);
}

for(var i=0; i<ct; i++){


var blendProp = ftg_track.clips[i].components[0].properties[1];
blendProp.setValue(14); // 14 - добавить
}

if (ftg_track.clips.length > 0) {
ftg_track.clips[ftg_track.clips.length - 1].end = durG;
// alert(durG + "\n" + ftg_track.clips[ftg_track.clips.length - 1].end);
}

var audioTrack = app.project.activeSequence.audioTracks[3];


var audioClips = audioTrack.clips;
for (var i=0; i<=audioClips.length; i++) {
audioClips[0].remove(0,0);
}
}

//Set audio tracks loudness


set_loudness(app.project.sequences[0].audioTracks[1], Number(settingz.voice_dB))
set_loudness(app.project.sequences[0].audioTracks[2],
Number(settingz.back_audio_dB))

//$.writeln("SAVE_FILENAME");

//res = app.project.sequences[0].exportAsMediaDirect(CUR_FILENAME,
settingz.presetPath, 0)
//$.writeln(CUR_FILENAME);
//$.writeln(res);
app.project.closeDocument(1, 0)

$.writeln("stage1");
file = new File(rootPath + '\\stage1'); // signal finish
file.open("w");
file.write('stage1')
file.close()

You might also like