summaryrefslogtreecommitdiff
path: root/rotord/rotor.cpp
blob: 559e47ca6e639b416554219b2de3d625a7ae7c4e (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
#include "rotor.h"

//float equality
bool fequal(const float u,const float v){
	if (abs(u-v)<.001) return true;
	else return false;
};
	

using namespace Rotor;

/*
    string soname="qm-vamp-plugins";
    string id="qm-tempotracker";
	string myname="";
	string output="";
	int outputNo=0;
	*/
	
void Render_context::runTask() {
	while (!isCancelled()) {
		int cmd=0;
		mutex.lock();
		if (work_queue.size()){
			cmd=work_queue[0];
			work_queue.pop_front();
		}
		mutex.unlock();
		if (cmd==ANALYSE_AUDIO) {
			state=ANALYSING_AUDIO;
			audio_analyser.process(audio_filename);
			//vampHost::runPlugin("","qm-vamp-plugins","qm-tempotracker", "",0, audio_filename, cerr,true);
			state=AUDIO_READY;
		}
		sleep(100);
	}
	printf("Rotor: stopping thread\n");
}
void Render_context::add_queue(int item) {
	mutex.lock();
	work_queue.push_back(item);
	mutex.unlock();
}

bool Signal_input::connect(Node* source) {
	if (source->output_type=="signal") {
		connection=source;
		return true;
	}
	else return false;
};

bool Signal_output::render(const float duration, const float framerate,string &xml_out){
	cerr << "Rotor: Signal_output rendering " << duration << " seconds at " << framerate << " frames per second" << endl;
	float step=1.0f/framerate;
	float v=0.0f;
	for (float f=0.0f;f<duration;f+=step) {
		float u=get_output(f);
		cerr << "Rotor: Signal_output got " << u << "as output" << endl;
		if (!fequal(u,v)) {
			xml_out+=("<signal time='"+ofToString(f)+"'>"+ofToString(u)+"</signal>\n");
			v=u;
		}
	}
	return true;
}

Command_response Render_context::session_command(const std::vector<std::string>& command){
										//method,id,command1,{command2,}{body}
										//here we allow the controlling server to communicate with running tasks
	Command_response response;
	response.status=HTTPResponse::HTTP_BAD_REQUEST;
	if (command[2]=="audio") {
	    if (command[0]=="PUT") {                                    	//get audio file location and initiate analysis
		if (command.size()>2) {
		    if (state==IDLE) {
												//check file exists
			Poco::File f=Poco::File(command[3]);
			//std::auto_ptr<std::istream> pStr(URIStreamOpener::defaultOpener().open(command[3]));
			
			
			if (f.exists()) {
												//pass to worker thread ??if engine is ready?? ??what if engine has finished but results aren't read??
			    audio_filename=command[3]; 			//for now, store session variables in memory
			    add_queue(ANALYSE_AUDIO);
			    response.description="<status context='"+command[1]+"'>Starting audio analysis: "+command[3]+"</status>\n";
			}
			else {
			    response.status=HTTPResponse::HTTP_NOT_FOUND;
			    response.description="<status context='"+command[1]+"'>File "+command[3]+" not found</status>\n";
			}
			
		    }
		    else {
			response.status=HTTPResponse::HTTP_BAD_REQUEST;
			response.description="<status context='"+command[1]+"'>Rotor: session busy</status>\n";
		    }
		}
	    }
	     if (command[0]=="GET") {
		     if (state==ANALYSING_AUDIO) {
			     response.status=HTTPResponse::HTTP_OK;
			     response.description="<status context='"+command[1]+"'>Rotor: analysing audio</status>\n";
			     char c[20];
			     sprintf(c,"%02f",audio_analyser.get_progress());
			     response.description+="<progress>"+string(c)+"</progress>\n";
		     }
		     if (state==AUDIO_READY) {
			     //not sure about this-- should this state be retained?
			     //can the data  only be read once?
			     //for now
			     response.status=HTTPResponse::HTTP_OK;
			     response.description="<status context='"+command[1]+"'>Rotor: audio ready</status>\n";
			      response.description+="<beats>";
			     for (auto& i: audio_analyser.beats) { //is actually giving no data?
				     char c[20];
				     sprintf(c,"%02f",i);
				     response.description+="<beat>"+string(c)+"</beat>";
				}     
			      response.description+="\n</beats>";
			     state=IDLE;
		     }
	     }
	     if (command[0]=="DELETE") {
		     //for now
			audio_filename="";
			response.description="<status>1</status>\n";
			response.status=HTTPResponse::HTTP_OK;
	     }
	}
	if (command[2]=="graph") {
		if (command[0]=="GET") {
			if (xml.bDocLoaded) {
				response.status=HTTPResponse::HTTP_OK;
				xml.copyXmlToString(response.description);
			}
			else {
				response.description="<status>Rotor: graph not loaded</status>\n";
			}
		}
		if (command[0]=="PUT") {                                    	//get new graph from file
			if (command.size()>2) {
												//should interrupt whatever is happening?
												//before begining to load from xml
				if (state==IDLE) {					//eventually not like this
					Poco::File f=Poco::File(command[3]);
					if (f.exists()) {
						string graph_filename=command[3]; 
						if (load_graph(graph_filename)) {
							response.status=HTTPResponse::HTTP_OK;
							//response.description="<status context='"+command[1]+"'>Rotor: loaded graph "+command[3]+"</status>\n";
							string xmlstring;
							xml.copyXmlToString(xmlstring);
							response.description=xmlstring;
							//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?
						}
						else {
							response.status=HTTPResponse::HTTP_INTERNAL_SERVER_ERROR; //~/sources/poco-1.4.6-all/Net/include/Poco/Net/HTTPResponse.h
							response.description="<status context='"+command[1]+"'>Rotor: could not load graph "+command[3]+"</status>\n";
						}
					}
					else {
					    response.status=HTTPResponse::HTTP_NOT_FOUND;
					    response.description="<status context='"+command[1]+"'>File "+command[3]+" not found</status>\n";
					}
				}
			}
		}
		if (command[0]=="DELETE") {
			 //for now
			graph=Graph();
			response.description="<status>1</status>\n";
			response.status=HTTPResponse::HTTP_OK;
		}
	}
	if (command[2]=="signal") {
		if (command[0]=="GET") {                                    	//generate xml from 1st signal output
			if (state==IDLE) {
				//direct call for testing
					float framerate=0.0f;
					if (command.size()>2) {
						framerate=ofToFloat(command[3]);
					}
					string signal_xml;
					if (graph.signal_render(framerate,signal_xml)){
						response.status=HTTPResponse::HTTP_OK;
						response.description=signal_xml;
					}
					else {
						response.status=HTTPResponse::HTTP_INTERNAL_SERVER_ERROR;
						response.description="<status context='"+command[1]+"'>Rotor: could not render output signal</status>\n";
					}
				}
				else {
					response.status=HTTPResponse::HTTP_NOT_FOUND;
					response.description="<status context='"+command[1]+"'>Signal output not found</status>\n";
				}
			}
			else {
				response.status=HTTPResponse::HTTP_SERVICE_UNAVAILABLE;
				response.description="<status context='"+command[1]+"'>Rotor: context busy</status>\n";
			}
		}
	if (command[2]=="video") {
		if (command[0]=="GET") {
													//DUMMY RESPONSE
			response.status=HTTPResponse::HTTP_OK;
			response.description="<status context='"+command[1]+"'>DUMMY RESPONSE Rotor: analysing video</status>\n";
			response.description+="<progress>45.2</progress>\n";
		}
		if (command[0]=="PUT") {                                    		//get vide file location and initiate analysis
			if (command.size()>2) {
			    if (state==IDLE) {
													//check file exists
				Poco::File f=Poco::File(command[3]);
				if (f.exists()) {
													//pass to worker thread ??if engine is ready?? ??what if engine has finished but results aren't read??
													//DUMMY RESPONSE
					response.description="<status context='"+command[1]+"'>DUMMY RESPONSE Starting video analysis: "+command[3]+"</status>\n";
				}
				else {
				    response.status=HTTPResponse::HTTP_NOT_FOUND;
				    response.description="<status context='"+command[1]+"'>File "+command[3]+" not found</status>\n";
				}
			    }
			    else {
				response.status=HTTPResponse::HTTP_BAD_REQUEST;
				response.description="<status context='"+command[1]+"'>Rotor: session busy</status>\n";
			    }
			}
		}
		if (command[0]=="DELETE") {
		     //DUMMY RESPONSE
			response.description="<status>DUMMY RESPONSE 1</status>\n";
			response.status=HTTPResponse::HTTP_OK;
	     }
		
	}
	if (command[2]=="render") {
		if (command[0]=="GET") {
													//DUMMY RESPONSE
			response.status=HTTPResponse::HTTP_OK;
			response.description="<status context='"+command[1]+"'>DUMMY RESPONSE Rotor: rendering video</status>\n";
			response.description+="<progress>25.2</progress>\n";
		}
		if (command[0]=="PUT") {
													//DUMMY RESPONSE
													//SHOULD CHECK REQUIREMENTS
			response.status=HTTPResponse::HTTP_OK;
			response.description="<status context='"+command[1]+"'>DUMMY RESPONSE Rotor: starting render</status>\n";
		}
		if (command[0]=="DELETE") {
													//DUMMY RESPONSE
													//SHOULD CHECK REQUIREMENTS
			response.status=HTTPResponse::HTTP_OK;
			response.description="<status context='"+command[1]+"'>DUMMY RESPONSE Rotor: cancelling render</status>\n";
		}
	}
	return response;
}

//how to do this?
//aim - load nodes from xml
//easily maintain the xml tree
//be able to save it or print it
//--if the list of nodes is a flat vector - don't need to store ID with the node - just refer to the index # of the node while loading?
//--if instead it refers to the index# in the unordered map - can handle deletion etc - have to check if a node exists when linking
//--also can a node link to one 'later' ? it may have to? in which case there's a 2 step process - 1 load the nodes - 2 link them
//maybe 


// a generic way to create a named node- each node is an object- will be loadable from .so
// eventually need to figure out to load .sos and enumerate classes
// in the short term either 
// - hand logic that recognises nodes and creates inputs etc
// - not sure how else?

//its a factory?
//http://stackoverflow.com/questions/4007382/how-to-create-class-objects-dynamically
//http://www.codeproject.com/Articles/3734/Different-ways-of-implementing-factories
//http://stackoverflow.com/questions/13292856/create-derived-class-in-base-class-based-on-parameter
//http://en.wikipedia.org/wiki/Factory_method_pattern

//what is a good way to pass parameters to objects?
//get all attributes of node and pass them as creation parameters?
//could just pass them all as strings, let the object choose what to do itself?
//YES

bool Render_context::load_graph(string filename){
	printf("loading %s\n",filename.c_str());
	if(xml.loadFile(filename) ){
		graph=Graph(xml.getAttribute("patchbay","ID","",0),xml.getValue("patchbay","",0));
		if(xml.pushTag("patchbay")) {
			int n1=xml.getNumTags("node");
			for (int i1=0;i1<n1;i1++){
				map<string,string> settings;
				vector<string> attrs;
				xml.getAttributeNames("node",attrs,i1);
				for (auto& attr: attrs) {
					settings[attr]=xml.getAttribute("node",attr,"",i1);
					//cerr << "Got attribute: " << attr << ":" << xml.getAttribute("node",attr,"",i1) << endl;
				}
				settings["description"]=xml.getValue("node","",i1);
				Node* node=factory.create(settings);
				if (node) {
					cerr << "Rotor: created '" << xml.getAttribute("node","type","",i1) << "'" << endl;
					string nodeID=xml.getAttribute("node","ID","",i1);
					graph.nodes[nodeID]=node;
					if(xml.pushTag("node",i1)) {
						int n2=xml.getNumTags("signal_input");
						for (int i2=0;i2<n2;i2++){
							graph.nodes[nodeID]->create_signal_input(xml.getValue("signal_input","",i2));
							string fromID=xml.getAttribute("signal_input","from","",i2);
							if (graph.nodes.find(fromID)!=graph.nodes.end()) {
								if (!graph.nodes[nodeID]->inputs[i2]->connect(graph.nodes[fromID])){
									cerr << "Rotor: graph loader cannot connect input " << i2 << " of node '" << nodeID << "' to node '" << fromID << "'" << endl;
									return false;
								}
								else cerr << "Rotor: linked input " << i2 << " of node '" << nodeID << "' to node '" << fromID << "'" << endl;
							}
							else cerr << "Rotor: linking input " << i2 << " of node: '" << nodeID << "', cannot find target '" << fromID << "'" << endl;							
						}
						xml.popTag();
					}
				}
				else {
					cerr << "Rotor: graph loader cannot find node '" << xml.getAttribute("node","type","",i1) << "'" << endl;
					return false;
				}
			}
			xml.popTag();
		}
		/*
		model_name=XML.getAttribute("map4","model","none",0);
		model_x=ofToFloat(XML.getAttribute("map4","x","none",0));
		model_y=ofToFloat(XML.getAttribute("map4","y","none",0));
		model_z=ofToFloat(XML.getAttribute("map4","z","none",0));
		if(XML.pushTag("map4")) {
		numViews=XML.getNumTags("view");
		if(numViews) {
		views=new viewpoint[numViews];
		for (int i=0;i<numViews;i++){
		    XML.pushTag("view",i);
			vector<string>keys;
			XML.getAttributeNames("settings", keys, 0);
			map<string,string>settings;
			for (int k=0;k<keys.size();k++) {
			    settings[keys[k]]=XML.getAttribute("settings",keys[k],"none",0);
			}
			views[i].setup(settings);
		    XML.popTag();
		}
		}

		numClips=XML.getNumTags("clip");
		if (numClips) {
		clips=new string[numClips];
		for (int i=0;i< numClips;i++) {
		    XML.pushTag("clip",i);
			clips[i]=XML.getAttribute("settings","file","none",0);
		    XML.popTag();
		}
		}

		XML.popTag();
		for (int i=0;i< numClips;i++) {
		printf("clip: %s\n",clips[i].c_str());
		}
		}
		*/
		return true;
	}
	else return false;
}

Node_factory::Node_factory(){
	//for now, statically load prototype map in constructor
	add_type("audio_analysis",new Audio_analysis());
	add_type("==",new Is_new_integer());
	add_type("signal_output",new Signal_output());
}