summaryrefslogtreecommitdiff
path: root/rotord/src/rendercontext.cpp
blob: 47fa498c0c29a8149608a08896f03a5cbdd39969 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
#include "rendercontext.h"

using namespace Rotor;
using Poco::Net::HTTPResponse;
using Poco::Logger;

void Render_context::runTask() {
	while (!isCancelled()) {
		Session_task cmd;
		mutex.lock();
		if (work_queue.size()){
			cmd=work_queue[0];
			work_queue.pop_front();
			graph.cancelled=false;
		}
		mutex.unlock();
		if(cmd.task==ANALYSE_AUDIO) {
			state=ANALYSING_AUDIO;
			vector<Audio_processor*> processors;
			processors.push_back(graph.audio_thumb);
			for (auto a: graph.nodes) {
				if (dynamic_cast<Audio_processor*>(a.second)){
					processors.push_back(dynamic_cast<Audio_processor*>(a.second));
				}
			}
			if (graph.load_audio(graph.audio_filename,processors)) {
				state=IDLE;
			}
			else {
				//an error occurred: TODO have to clean up allocated data. autoptr?
				graph.audio_loaded=false;
				state=IDLE;
			}
		}
		if(cmd.task==RENDER) {
			state=RENDERING;
			renders[cmd.uid]=Render_status(RENDERING);
			if(graph.video_render(output_filename,output_framerate,start,stop)){
				state=IDLE;
				if (graph.cancelled) renders[cmd.uid].status=CANCELLED;
				else renders[cmd.uid].status=RENDER_READY;
			}
			else {
				//an error occurred: TODO have to clean up allocated data. autoptr?
				cerr<<"Rotor: render failed"<<endl;
				state=IDLE;
				renders[cmd.uid].status=FAILED;
			}
		}
		if(cmd.task==LOAD_GRAPH) {
			state=LOADING_GRAPH;
			if (graph_filename!="") {
				if (!graph.loadFile(graph_filename,media_dir)){
					cerr<<"Rotor: failed to load graph from "<<graph_filename<<endl;
				}
			}
			else if (graph_body!="") {
				if (!graph.load(graph_body,media_dir)) {
					cerr<<"Rotor: failed to load graph from body request"<<endl;
				}
			}
			if (graph.loaded){
				if (graph.audio_loaded) {
					add_queue(Session_task(cmd.uid,ANALYSE_AUDIO));
				    cerr<<"Rotor: starting audio analysis for graph"<<endl;
				}
			}
			state=IDLE;
		}
		sleep(100);
	}
	printf("Rotor: stopping thread\n");
}
void Render_context::add_queue(Session_task item) {
	mutex.lock();
	work_queue.push_back(item);
	mutex.unlock();
}
//const std::vector<std::string>& command
void Render_context::session_command(const Session_command& command,xmlIO& XML,HTTPResponse::HTTPStatus& status){

	string s;
	for (auto c:command.commands){
		s+=c;
		s+=" ";
	}
	//cerr<<"uid:"<<command.uid<<" method:"<<command.method<<" id:"<<command.id\
	//<<" commands:"<<s<<"body:"<<command.body<<endl;

	Logger& logger = Logger::get("Rotor");
	status=HTTPResponse::HTTP_BAD_REQUEST; //error by default
	if (command.commands[1]=="resolution") {
		if (command.method=="PUT") {
			if (command.body!="") {
				if (state!=RENDERING) {
					Poco::StringTokenizer t1(command.body,",");
					if (t1.count()>1){
						int w=toInt(t1[0]);
						int h=toInt(t1[1]);
						if (graph.set_resolution(w,h)){
							logger.information("resolution set to "+t1[0]+"x"+t1[1]);
							XML.addValue("status","resolution set to "+t1[0]+"x"+t1[1]);
							status=HTTPResponse::HTTP_OK;
						}
						else {
							logger.error("ERROR: invalid resolution request: "+t1[0]+"x"+t1[1]);
							XML.addValue("error","invalid resolution request: "+t1[0]+"x"+t1[1]);
						}
					}
				}
				else {
					XML.addValue("error","session busy");
				}
			}
		}
	}
	if (command.commands[1]=="bitrate") {
		if (command.method=="PUT") {
			int b=toInt(command.body);
			if (graph.set_bitrate(b)){
				logger.information("bitrate set to "+command.body);
				XML.addValue("status","bitrate set to "+command.body);
				status=HTTPResponse::HTTP_OK;
			}
			else {
				logger.error("ERROR: Could not set bitrate set to "+command.body);
				XML.addValue("error","Could not set bitrate set to "+command.body);
			}
		}
		else {
			status=HTTPResponse::HTTP_BAD_REQUEST;
			logger.error("ERROR: Bad request");
			XML.addValue("error","Bad request");
		}
	}
	if (command.commands[1]=="fragmentation") {
		if (command.method=="PUT") {
			bool f=(toInt(command.body)!=0);
			if (graph.set_fragmentation(f)){
				string fs=f?"on":"off";
				logger.information("MP4 fragmentation "+fs);
				XML.addValue("status","MP4 fragmentation "+fs);
				status=HTTPResponse::HTTP_OK;
			}
			else {
				logger.error("ERROR: Could not set MP4 fragmentation");
				XML.addValue("error","Could not set MP4 fragmentation");
			}
		}
		else {
			status=HTTPResponse::HTTP_BAD_REQUEST;
			logger.error("ERROR: Bad request");
			XML.addValue("error","Bad request");
		}
	}
	if (command.commands[1]=="audio") {
	    if (command.method=="PUT") {          			//get audio file location and initiate analysis
			if (command.body!="") {
			    if (state==IDLE) {
					graph.audio_filename=media_dir+command.body; 			//for now, store session variables in memory									//check file exists
					Poco::File f=Poco::File(graph.audio_filename);
					if (f.exists()) {
															//pass to worker thread ??if engine is ready?? ??what if engine has finished but results aren't read??
					    add_queue(Session_task(command.uid,ANALYSE_AUDIO));
					    status=HTTPResponse::HTTP_OK;
					    logger.information("Audio analysis: "+command.body);
					    XML.addValue("status","Starting audio analysis: "+command.body);
					}
					else {
					    status=HTTPResponse::HTTP_NOT_FOUND;
					    logger.error("ERROR: audio file "+command.body+" not found");
					    XML.addValue("error",command.body+" not found");
					}

			    }
			    else {
			    	logger.error("ERROR: Session busy");
					XML.addValue("error","Session busy");
				}
			}
	    }
	     if (command.method=="GET") {
		     if (state==ANALYSING_AUDIO) {
			     status=HTTPResponse::HTTP_OK;
			     XML.addValue("status","Analysing audio");
			     char c[20];
			     sprintf(c,"%02f",graph.progress);
			     XML.addValue("progress",string(c));
		     }
			else if (graph.audio_loaded) {
				//not sure about this-- should this state be retained?
				//can the data only be read once?
				//for now
				status=HTTPResponse::HTTP_OK;
				XML.addValue("status","Audio ready");
				graph.audio_thumb->print_vector(XML);
				//XML.addValue("audio",audio_thumb->print());
			}
			else {
				logger.error("ERROR: audio thumbnail requested but no audio loaded");
				XML.addValue("error","No audio loaded");
			}
	     }
	     if (command.method=="DELETE") {
		    if (state==IDLE) {
				graph.audio_filename="";
				graph.audio_loaded=false;
				logger.information("Audio deleted");
				XML.addValue("status","Audio deleted");
				status=HTTPResponse::HTTP_OK;
			}
			else {
				logger.error("ERROR: Session busy");
				XML.addValue("error","Session busy");
			}
	     }
	}
	if (command.commands[1]=="graph") {
		if (command.method=="GET") {
			if (state!=LOADING_GRAPH) {	
				if (graph.loaded) {
					status=HTTPResponse::HTTP_OK;
					//XML.addValue("patchbay",graph.toString());
					logger.information("Graph loaded");
					//XML.loadFromBuffer(graph.graphToString());
					XML.addValue("status","Graph loaded");
				}
				else {
					logger.error("ERROR: graph not loaded");
					XML.addValue("error","graph not loaded");				
				}
			}
			else {
				logger.error("ERROR: Graph loading");
				XML.addValue("error","Graph loading");
			}
		}
		if (command.method=="PUT") {     				//get new graph from file
			if (command.body!="") {
													//should interrupt whatever is happening?
													//before begining to load from xml
				if (state==IDLE) {					//eventually not like this
					/*
					if (Poco::File(graph_dir+command.body).exists()) {
							string graph_filename=graph_dir+command.body;
							if (graph.loadFile(graph_filename,media_dir)) {
								status=HTTPResponse::HTTP_OK;
								//XML.addValue("patchbay",graph.toString());
								//XML.loadFromBuffer(graph.toString());
								XML=graph.xml;
								//the graph could actually contain an xml object and we could just print it here?
								//or could our nodes even be subclassed from xml nodes?
								//the graph or the audio could load first- have to analyse the audio with vamp after the graph is loaded
								//for now the graph must load 1st
								if (graph.audio_loaded) {
									add_queue(Session_task(command.uid,ANALYSE_AUDIO));
								    status=HTTPResponse::HTTP_OK;
								    logger.information("Starting audio analysis for graph: "+command.commands[0]);
								    XML.addValue("status","Starting audio analysis for graph: "+command.commands[0]);
								}
							}
							else {
								status=HTTPResponse::HTTP_INTERNAL_SERVER_ERROR; //~/sources/poco-1.4.6-all/Net/include/Poco/Net/HTTPResponse.h
								logger.error("ERROR: graph not loaded: check file");
								XML.addValue("error","graph not loaded: check file");
							}
						}
					else if (graph.load(command.body,media_dir)) {
						status=HTTPResponse::HTTP_OK;
						logger.information("Loaded graph from http PUT body");
						XML.addValue("status","Loaded graph from PUT body");
						if (graph.audio_loaded) {
							add_queue(Session_task(command.uid,ANALYSE_AUDIO));
						    status=HTTPResponse::HTTP_OK;
						    logger.information("Starting audio analysis for graph: "+command.commands[0]);
						    XML.addValue("status","Starting audio analysis for graph: "+command.commands[0]);
						}
					}
					else {
						status=HTTPResponse::HTTP_INTERNAL_SERVER_ERROR; //~/sources/poco-1.4.6-all/Net/include/Poco/Net/HTTPResponse.h
						logger.error("ERROR: graph unreadable");
						XML.addValue("error","graph unreadable");
					}
					*/
					
					if (command.body!="") {
						graph_filename="";
						graph_body="";
						if (Poco::File(graph_dir+command.body).exists()) {
							graph_filename=graph_dir+command.body;
							add_queue(Session_task(command.uid,LOAD_GRAPH));
						    status=HTTPResponse::HTTP_OK;
						    logger.information("Loading graph from file: "+command.body);
							XML.addValue("status","Loading graph from file: "+command.body);
							//XML.addValue("render_id",command.uid); process ID?
						}
						else {
							xmlIO xml;
							bool readable=true;
							if (!xml.loadFromBuffer(command.body)){
								Json::Value root;   // will contains the root value after parsing.
								Json::Reader reader;
								if ( !reader.parse( command.body, root ) )
								{
									status=HTTPResponse::HTTP_BAD_REQUEST;
									logger.error("ERROR: Could not load graph");
									XML.addValue("error","Could not load graph");
									readable=false;
								}
							}
							if (readable) {
								graph_body=command.body;
								add_queue(Session_task(command.uid,LOAD_GRAPH));
								status=HTTPResponse::HTTP_OK;
							    logger.information("Loading graph from body request");
								XML.addValue("status","Loading graph from body request");
							}
						}
					}
					else {
						status=HTTPResponse::HTTP_BAD_REQUEST;
						logger.error("ERROR: Empty request");
						XML.addValue("error","Empty request");
				    }
				}
				else {
					logger.error("ERROR: Session busy");
					XML.addValue("error","Session busy");
				}
			}
		}
		if (command.method=="DELETE") {
			 //for now
			graph.clear();
			logger.information("graph deleted");
			XML.addValue("status","graph deleted");
			status=HTTPResponse::HTTP_OK;
		}
	}
	if (command.commands[1]=="signal") {
		if (command.method=="GET") {                                    	//generate xml from 1st signal output
			if (state==IDLE) {
				//direct call for testing
					float framerate=25.0f;
					//if (command.size()>2) {
					//	framerate=toFloat(command.id);
					//}
					string signal_xml;
					if (false) { //graph.signal_render(signal_xml,framerate)){
						status=HTTPResponse::HTTP_OK;
						logger.information("rendering signal to xml");
						XML.addValue("signal",signal_xml); //this doesn't work >> pseudo xml
					}
					else {
						status=HTTPResponse::HTTP_INTERNAL_SERVER_ERROR;
						logger.error("ERROR: could not render output signal");
						XML.addValue("error","could not render output signal");
					}
					//else {
					//	status=HTTPResponse::HTTP_NOT_FOUND;
					//	XML.addValue("error","Signal output not found in graph");
					//}
			}
			else {
				status=HTTPResponse::HTTP_SERVICE_UNAVAILABLE;
				logger.error("ERROR: context busy");
				XML.addValue("error","Context busy");
			}
		}
	}
	if (command.commands[1]=="video") {
		if (command.method=="PUT") {                                    //get vide file location and initiate analysis
			if (command.body!="") { 								//there should be a filename + a destination node
			    if (state!=RENDERING) {
			    	if (command.commands.size()>2) {
				    	string video_filename=media_dir+command.body;
																		//check file exists
						Poco::File f=Poco::File(video_filename);
						if (f.exists()) {
							if (graph.load_video(command.commands[2],video_filename)) {
																		//pass to worker thread ??if engine is ready?? ??what if engine has finished but results aren't read??
																		//DUMMY RESPONSE
								status=HTTPResponse::HTTP_OK;
								logger.information("Succesfully loaded "+command.body+" into video node "+command.commands[2]);
								XML.addValue("status","Succesfully loaded "+command.body+" into video node "+command.commands[2]);
							}
							else {
								status=HTTPResponse::HTTP_INTERNAL_SERVER_ERROR;
								logger.error("ERROR: could not load "+command.body+" into video node "+command.commands[2]);
								XML.addValue("error","could not load "+command.body+" into video node "+command.commands[2]);
							}
						}
						else {
					    status=HTTPResponse::HTTP_NOT_FOUND;
					    logger.error("ERROR: "+command.body+" not found");
						XML.addValue("error",command.body+" not found");
					}
					}
					else {
					    status=HTTPResponse::HTTP_NOT_FOUND;
					    logger.error("ERROR: video loader node not specified");
						XML.addValue("error","video loader node not specified");
					}
			    }
			    else {
					status=HTTPResponse::HTTP_BAD_REQUEST;
					logger.error("ERROR: Session busy");
					XML.addValue("error","Session busy");
			    }
			}
			else {
				status=HTTPResponse::HTTP_BAD_REQUEST;
				logger.error("ERROR: Bad request");
				XML.addValue("error","Bad request");
			}
		}
		else {
			status=HTTPResponse::HTTP_BAD_REQUEST;
			logger.error("ERROR: Bad request");
			XML.addValue("error","Bad request");
		}
	}
	if (command.commands[1]=="preview") {
		if (command.method=="GET") {
			if(state==IDLE){
				//parse json to get preview spec, return XML? this is a mess
				string preview_node=command.commands[2];
				Json::Value root;   // will contains the root value after parsing.
				Json::Reader reader;
				if (reader.parse( command.body, root )) {
					int frame=root["frame"].asInt();
					int width=root["width"].asInt();
					int height=root["height"].asInt();
					string format=root["format"].asString();
					if (graph.preview(XML,preview_node,format,frame,width,height)) {
						status=HTTPResponse::HTTP_OK;
					}
					else {
						status=HTTPResponse::HTTP_BAD_REQUEST;
						logger.error("ERROR: Could not create preview");
						XML.addValue("error","Could not preview node '"+preview_node+"', frame "+toString(frame)+" at "+toString(width)+"x"+toString(height));
					}
				}
				else {
				    std::cout  << "Failed to parse preview request\n"
				               << reader.getFormattedErrorMessages();
				    status=HTTPResponse::HTTP_BAD_REQUEST;
					logger.error("ERROR: Bad preview request");
					XML.addValue("error","Bad preview request");
				}
			}
			else {
				status=HTTPResponse::HTTP_BAD_REQUEST;
				logger.error("ERROR: Session busy");
				XML.addValue("error","Session busy");
		    }
		}
		else {
				status=HTTPResponse::HTTP_BAD_REQUEST;
				logger.error("ERROR: Bad request");
				XML.addValue("error","Bad request");
			}
	}
	if (command.commands[1]=="features") {
		if (command.method=="GET") {
			if(state==IDLE){
				//parse json to get preview spec, return XML? this is a mess
				string features_node=command.commands[2];
				if (graph.print_features(XML,features_node)) {
					status=HTTPResponse::HTTP_OK;
				}
				else {
					status=HTTPResponse::HTTP_BAD_REQUEST;
					logger.error("ERROR: Could not print features for node "+features_node);
				}
			}
			else {
				status=HTTPResponse::HTTP_BAD_REQUEST;
				logger.error("ERROR: Session busy");
				XML.addValue("error","Session busy");
		    }
		}
		else {
				status=HTTPResponse::HTTP_BAD_REQUEST;
				logger.error("ERROR: Bad request");
				XML.addValue("error","Bad request");
			}
	}
	if (command.commands[1]=="render") {
		if (command.method=="GET") {
			if(state==RENDERING){
				//graph.mutex.lock();
					status=HTTPResponse::HTTP_OK;
					XML.addValue("status","Rendering video");
					XML.addValue("progress",toString(graph.progress));
					//graph.mutex.unlock();
			}
			else {
				logger.error("ERROR: Render progress requested but not rendering");
				XML.addValue("error","Not rendering");
			}
		}
		if (command.method=="PUT") {
			if (command.body!="") {
			    if (state==IDLE) {
					Poco::StringTokenizer t1(command.body,",");
					if (t1.count()>1){
						output_filename=output_dir+t1[0];
						start=toInt(t1[1]);
						if (t1.count()>2){
							stop=toInt(t1[2]);
							if (t1.count()>3){
								float framerate=toFloat(t1[3]);
								if (framerate>0.0f) {
									output_framerate=framerate;
								}
							}
						}
					}
					else {
						start=0;
						stop=999999;
						output_filename=output_dir+command.body;
					}
					add_queue(Session_task(command.uid,RENDER));
				    status=HTTPResponse::HTTP_OK;
				    logger.information("Starting render: "+command.body);
					XML.addValue("status","Starting render: "+command.body);
					XML.addValue("render_id",command.uid);
					XML.addValue("path",output_filename);
			    }
			    else {
					status=HTTPResponse::HTTP_BAD_REQUEST;
					logger.error("ERROR: Session busy");
					XML.addValue("error","Session busy");
		    	}
			}
			else {
				status=HTTPResponse::HTTP_BAD_REQUEST;
				logger.error("ERROR: No output file specified");
				XML.addValue("error","No output file specified");
		    }
		}
		if (command.method=="DELETE") {
			status=HTTPResponse::HTTP_OK;
			logger.error("ERROR: Not implemented");
			XML.addValue("status","DUMMY RESPONSE: cancelling render");
		}
	}
	if (command.commands[1]=="cancel") {
		if (command.method=="PUT") {
			if (state==RENDERING){
				graph.cancelled=true;
				logger.information("Render cancelled.");
				XML.addValue("status","render cancelled");
			}
			else if (state==ANALYSING_AUDIO){
				graph.cancelled=true;
				logger.information("Audio analysis cancelled.");
				XML.addValue("status","audio analysis cancelled");
			}
			else {
				status=HTTPResponse::HTTP_BAD_REQUEST;
				logger.error("ERROR: no process to cancel");
				XML.addValue("error","No process to cancel");
	    	}
		}
		else {
			status=HTTPResponse::HTTP_BAD_REQUEST;
			logger.error("ERROR: Bad request");
			XML.addValue("error","Bad request");
		}
	}
}