forked from TheAndyRoid/PythonPlugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonPlugin.cpp
More file actions
504 lines (353 loc) · 11.5 KB
/
PythonPlugin.cpp
File metadata and controls
504 lines (353 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
/********************************************************************************
Copyright (C) 2014 Andrew Skinner <obs@theandyroid.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
********************************************************************************/
#include "PythonPlugin.h"
#include <windowsx.h>
#include <cstdio>
#include <windows.h>
#include <cstdlib>
#include "PyOBS.h"
#include "PyXElement.h"
#define VIDEO_SOURCE_CLASS TEXT("PythonSource")
PythonPlugin *PythonPlugin::instance = NULL;
/*Called when the python source is expeteced to show a config gui*/
bool STDCALL ConfigurePythonSource(XElement *element, bool bCreating)
{
String file;
String className;
String moduleName;
Log(TEXT("Python Source Configure"));
XElement *dataElement = element->GetElement(TEXT("data"));
bool isMissingDataElement = true;
if (!dataElement) {
dataElement = element->CreateElement(TEXT("data"));
}
else{
isMissingDataElement = false;
}
//Get the plugin instance
PythonPlugin *pyPlug = PythonPlugin::instance;
if (pyPlug == NULL){
Log(TEXT("Python instance Does not exist"));
return NULL;
}
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyObject *pName, *pModule, *pFunc;
if (isMissingDataElement){
moduleName = TEXT("ScriptManager");
className = TEXT("ScriptManager");
}
else{
file = dataElement->GetString(TEXT("PythonFile"));
className = dataElement->GetString(TEXT("PythonGUIClass"));
moduleName = addToPythonPath(file);
}
bool reload = dataElement->GetInt(TEXT("Debug"));
pyHasError();
pName = CTSTRtoPyUnicode(moduleName);
PyObject *dict = PyImport_GetModuleDict();//borrowed ref
if (PyDict_Contains(dict, pName) && reload){ //make a debug option to reload source
pModule = PyDict_GetItem(dict, pName); //borrowed ref
pModule = PyImport_ReloadModule(pModule);
pyHasError();
}
else {
pModule = PyImport_Import(pName);
pyHasError();
}
if (pyHasError()){
Py_XDECREF(pModule);
Py_XDECREF(pName);
return false;
}
if (pModule != NULL) {
pFunc = PyObject_GetAttr(pModule, CTSTRtoPyUnicode(className));
if (pFunc && PyCallable_Check(pFunc)) {
PyObject *pyConfig = PyObject_CallObject((PyObject*)&PyXElement_Object, NULL);
((PyXElement*)pyConfig)->element = dataElement;
PyObject *argList = Py_BuildValue("(O)", pyConfig);
PyObject *ret = PyObject_CallObject(pFunc, argList);
Py_DECREF(argList);
if (pyHasError()){
Py_XDECREF(pModule);
Py_XDECREF(pName);
Py_XDECREF(pyConfig);
PyGILState_Release(gstate);
return false;
}
Py_DECREF(pyConfig);
Py_DECREF(ret);
}
else {
}
Py_XDECREF(pFunc);
}
else {
PyErr_Print();
}
Py_XDECREF(pModule);
Py_XDECREF(pName);
PyGILState_Release(gstate);
if (isMissingDataElement){
//The setup gui has run now run the specified gui
// check if the required element now exist and restart gui
//check if the elements have been added to config. if not then setup gui failed.
String log = dataElement->GetString(TEXT("PythonFile"));
if (!dataElement->GetString(TEXT("PythonFile")) || !dataElement->GetString(TEXT("PythonGUIClass")) || !dataElement->GetString(TEXT("PythonPluginClass"))){
//User canceled
return false;
}
else{
return ConfigurePythonSource(element, false);
}
}
else{
return true;
}
}
/*Called when the element is created at stream start.*/
ImageSource* STDCALL CreatePythonSource(XElement *data)
{
Log(TEXT("Python Create ImageSource"));
XElement *thisSource = data->GetParent();
XElement *sources = thisSource->GetParent();
XElement *thisScene = sources->GetParent();
String sourceName = thisSource->GetName();
String sceneName = thisScene->GetName();
//Get the plugin instance
PythonPlugin *pyPlug = PythonPlugin::instance;
if (pyPlug == NULL){
Log(TEXT("Python instance Does not exist"));
return NULL;
}
//Create Image source
CppImageSource *pImageSource = new CppImageSource(data);
pyPlug->tmpImgSrc = pImageSource;
String file;
String className;
String moduleName;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
file = data->GetString(TEXT("PythonFile"));
className = data->GetString(TEXT("PythonPluginClass"));
if (file == NULL || className == NULL){
PyGILState_Release(gstate);
return NULL;
}else{
moduleName = addToPythonPath(file);
}
//Python
PyObject *pName, *pModule, *pFunc;
pyImageSource *pyImgSrc = NULL;
pName = CTSTRtoPyUnicode(moduleName);
bool reload = data->GetInt(TEXT("Debug"));
PyObject *dict = PyImport_GetModuleDict();
if (PyDict_Contains(dict, pName) && reload){
pModule = PyDict_GetItem(dict, pName);
pModule = PyImport_ReloadModule(pModule);
pyHasError();
}
else{
pModule = PyImport_Import(pName);
pyHasError();
}
bool pyObjectCreated = false;
if (pModule != NULL) {
pFunc = PyObject_GetAttr(pModule, CTSTRtoPyUnicode(className));
pyHasError();
// pFunc is a new reference
if (pFunc && PyCallable_Check(pFunc)) {
//pass in config
PyObject *argList = Py_BuildValue("");
PyObject *pyConfig = PyObject_CallObject((PyObject*)&PyXElement_Object, NULL);
((PyXElement*)pyConfig)->element = data;
Py_DECREF(argList);
argList = Py_BuildValue("(O)",pyConfig);
pyImgSrc = (pyImageSource*)PyObject_CallObject(pFunc, argList);
if (pyHasError()){
Log(TEXT("Unable to create class %ws"),className);
}
else if (!isPyObjectBaseClass((PyObject*)pyImgSrc, &String(TEXT("ImageSource")))){
Log(TEXT("PYTHON ERROR Class: %ws , is not derived from OBS.ImageSource"),className);
}else{
pImageSource->pyImgSrc = (PyObject*)pyImgSrc;
//Clear pyPlug
pyPlug->tmpImgSrc = NULL;
pyObjectCreated = true;
}
Py_DECREF(argList);
Py_XDECREF(pyConfig);
}
else {
}
Py_XDECREF(pFunc);
}
else {
PyErr_Print();
}
Py_XDECREF(pModule);
Py_XDECREF(pName);
PyGILState_Release(gstate);
if (pyObjectCreated){
return pImageSource;
}
else{
return NULL;
}
}
PythonPlugin::PythonPlugin()
{
isDynamicLocale = false;
Log(TEXT("Python plugin loaded"));
if (!locale->HasLookup(KEY("PluginName"))) {
isDynamicLocale = true;
int localizationStringCount = sizeof(localizationStrings) / sizeof(CTSTR);
Log(TEXT("Python Plugin strings not found, dynamically loading %d strings"), sizeof(localizationStrings) / sizeof(CTSTR));
for (int i = 0; i < localizationStringCount; i += 2) {
locale->AddLookupString(localizationStrings[i], localizationStrings[i + 1]);
}
if (!locale->HasLookup(KEY("PluginName"))) {
AppWarning(TEXT("Uh oh..., unable to dynamically add our localization keys"));
}
}
//Register callbacks with obs
OBSRegisterImageSourceClass(VIDEO_SOURCE_CLASS, STR("ClassName"), (OBSCREATEPROC)CreatePythonSource, (OBSCONFIGPROC)ConfigurePythonSource);
//Load the OBS Extension
PyImport_AppendInittab("OBS", PyInit_OBS);
Py_Initialize();
PyEval_InitThreads();
/*Must set arguments for guis to work*/
#if PY_MAJOR_VERSION >= 3
wchar_t *argv[] = { TEXT("OBS"), NULL };
int argc = sizeof(argv) / sizeof(wchar_t*) - 1;
#else
char *argv[] = { "OBS", NULL };
int argc = sizeof(argv) / sizeof(char*) - 1;
#endif
PySys_SetArgv(argc, argv);
String path = OBSGetPluginDataPath();
path.FindReplace(TEXT("\\"), TEXT("/"));
path = path + String("/Python");
String appPath(OBSGetAppPath());
appPath.FindReplace(TEXT("\\"), TEXT("/"));
appPath = appPath + String("/plugins/PythonPlugin");
PyImport_ImportModule("OBS");
PythonRunString(String("import sys,os"));
PythonRunString(String("os.makedirs('") + path + String("')"));
PythonRunString(String("sys.path.append('") + path + String("')"));
PythonRunString(String("sys.path.append('") + appPath + String("')"));
#if PY_MAJOR_VERSION >= 3
PythonRunString(String("os.environ['PYTHONUNBUFFERED'] = '1'"));
PythonRunString(String("sys.stdout = open('") + path + String("/stdOut.txt','w',1)"));
PythonRunString(String("sys.stderr = open('") + path + String("/stdErr.txt','w',1)"));
#else
PythonRunString(String("sys.stdout = open('") + path + String("/stdOut.txt','w',0)"));
PythonRunString(String("sys.stderr = open('") + path + String("/stdErr.txt','w',0)"));
#endif
PythonRunString(String("print('Python ' + sys.version)"));
pyHasError();
//Release the GIL
PyThreadState *pts = PyGILState_GetThisThreadState();
PyEval_ReleaseThread(pts);
}
PythonPlugin::~PythonPlugin()
{
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
Log(TEXT("Python plugin Destroyed"));
if (isDynamicLocale) {
int localizationStringCount = sizeof(localizationStrings) / sizeof(CTSTR);
Log(TEXT("Plugin instance deleted; removing dynamically loaded localization strings"));
for (int i = 0; i < localizationStringCount; i += 2) {
locale->RemoveLookupString(localizationStrings[i]);
}
}
//Run Alocated cleanup functions
//One cleanup per uinque file
clearShutdownFunctions();
if (Py_IsInitialized()){
Py_Finalize();
}
Log(TEXT("Python plugin Destroyed"));
isDynamicLocale = false;
}
CTSTR GetPluginName(){
return STR("PluginName");
}
CTSTR GetPluginDescription()
{
return STR("PluginDescription");
}
bool LoadPlugin(){
if (!isPythonInPath()){
#if PY_MAJOR_VERSION >= 3
int ret = OBSMessageBox(OBSGetMainWindow(), TEXT("'Python34' not found in PATH environment variable! \n Python Plugin will instantly close OBS if Python can't be loaded.\n Attempt to load Python Plugin?\n"), TEXT("ERROR- 'Python27' NOT IN PATH"), 4);
#else
int ret = OBSMessageBox(OBSGetMainWindow(), TEXT("'Python27' not found in PATH environment variable! \n Python Plugin will instantly close OBS if Python can't be loaded.\n Attempt to load Python Plugin?\n"), TEXT("ERROR- 'Python27' NOT IN PATH"), 4);
#endif
if (ret == 7){ // No
AppWarning(TEXT("Python Plugin - User Aborted Loading!"));
return false;
}
else if(ret == 6){ //yes
AppWarning(TEXT("Python Plugin - User Ignored warning! Attempting to Load"));
}
else{
return false;
}
}
if (PythonPlugin::instance != NULL){
return false;
}
PythonPlugin::instance = new PythonPlugin();
return true;
}
void UnloadPlugin(){
if (PythonPlugin::instance == NULL)
return;
delete PythonPlugin::instance;
PythonPlugin::instance = NULL;
}
void OnStartStream()
{
}
void OnStopStream()
{
PythonPlugin *pyPlug = PythonPlugin::instance;
if (pyPlug == NULL){
Log(TEXT("Python instance Does not exist"));
}
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyGILState_Release(gstate);
return;
}
void PythonPlugin::addShutdownFunction(String filename, PyObject *function){
shutdownFunc[filename] = function;
Py_INCREF(function);
}
void PythonPlugin::clearShutdownFunctions(){
for (shutdown_map::iterator i = shutdownFunc.begin(); i != shutdownFunc.end(); ++i){
PyObject* pyFunc = i->second;
//call shutdown func
if (pyFunc != NULL){
PyObject *argList = Py_BuildValue("()");
PyObject_CallObject(pyFunc, argList);
Py_DECREF(argList);
}
Py_DECREF(pyFunc);
}
shutdownFunc.clear();
}