summarylogtreecommitdiffstats
path: root/ttyvideo.cpp
blob: 361eaf20373b645433c72c7b504e1d229ac5b369 (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
// #include <opencv2/core/core_c.h>
// #include <opencv2/videoio/videoio_c.h>
// #include <opencv2/videoio/videoio.hpp>
#include <opencv2/core.hpp>
#include <opencv2/video.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include "handle.h"
#include <sys/ioctl.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>

#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif

#define NANO_CONV_FACTOR 1000000000

#define COLOR_TEXT_FORMAT "\x1B[48;05;%um\x1B[38;05;%um%c"
#define COLOR_FORMAT "\x1B[48;05;%um "
#define COLOR_RESET "\x1B[0m"

int waitFrame(uint64_t, uint64_t);
unsigned char generateANSIColor(unsigned char, unsigned char, unsigned char);
void getTTYDims();
int play(char*, char*, char*, int);
void getSystemTime(struct timespec*);

int tty_width;
int tty_height;
int tty_width_custom = 0;
int tty_height_custom = 0;

int no_interrupts = 0;

#define C (char*)

int main(int argc, char** argv) {

	char* filename       = setDefaultArgument(C"infile");
	char* width_option   = addArgument(C"Output width", TAKES_ONE_ARGUMENT, C"-w", C"--width");
	char* height_option  = addArgument(C"Output height", TAKES_ONE_ARGUMENT, C"-h", C"--height");
	char* sleep_option   = addArgument(C"Add a pause between loops or after plays (seconds)", TAKES_ONE_ARGUMENT, C"-s", C"--sleep");
	char* noexit_option  = addArgument(C"Prevent the program for exiting", TAKES_NO_ARGUMENTS, C"--no-exit", NULL);
	char* loop_option    = addArgument(C"Loop videos", TAKES_NO_ARGUMENTS, C"-l", C"--loop");
	char* help_option    = addArgument(C"Print usage", TAKES_NO_ARGUMENTS, C"--help", NULL);
	char* nointer_option = addArgument(C"No interrupts", TAKES_NO_ARGUMENTS, C"--no-interrupts", NULL);
	char* fps_option     = addArgument(C"FPS", TAKES_ONE_ARGUMENT, C"--fps", NULL);
	char* string_option  = addArgument(C"String to place in the foreground", TAKES_ONE_ARGUMENT, C"--string", NULL);
	char* info_option    = addArgument(C"Print terminal dimensions", TAKES_NO_ARGUMENTS, C"-i", C"--info");

	int argError;
	argError = handle(argc, argv);
	if(argError) {
		error((char*)"Run ttyvideo --help for more information");
		return argError;
	}

	if(help_option[0] != '\0') {
		printUsage();
		return 0;
	}

	if(info_option[0] != '\0') {
		getTTYDims();
		printf("Height: %d\nWidth: %d\n",
				tty_height, tty_width);
		return 0;
	}

	if(filename[0] == '\0')
		return error((char*)"No input file specified");

	getTTYDims(); // get initial dims

	tty_height_custom = atoi(height_option);
	tty_width_custom = atoi(width_option);

	if(tty_height == 0 && tty_width == 0) {
		if(tty_height_custom == 0 || tty_width_custom == 0) {
			error((char*)"Could not detect terminal dimensions and specified dimensions are incomplete");
			return 1;
		}
	} else {
		if(tty_height_custom > tty_height || tty_width_custom > tty_width) {
			error((char*)"The specified dimensions are too large, but we will play the video anyway");
		}
	}

	getTTYDims(); // get real dims -- including user specification

	int sleep_time = sleep_option[0] == '\0' ? 0 : atoi(sleep_option);

	int noexit = noexit_option[0] == '\0' ? 0 : 1;

	int loop = loop_option[0] == '\0' ? 0 : 1;

	setvbuf(stdout, NULL, _IOFBF, 0);

	signal(SIGINT, sig_handler);

	no_interrupts = nointer_option[0] == '\0' ? 0 : 1;

	register int frameNum = 0;
	do {
		frameNum = play(filename, string_option, fps_option, frameNum);

		if(frameNum < 0)
			return 1;

		if(terminate && !no_interrupts) {
			printf("\n");
			fflush(stdout);
			return 0;
		}

		if(sleep_time)
			sleep(sleep_time);

	} while(loop && frameNum > 1);

	if((loop && frameNum == 1) || noexit) {
		terminate = 0; // Terminate to 0 so we can work with it
		while(true) {
			sleep(1);
			// When SIG_INT is sent to a frozen frame,
			// re-render the frame
			if(terminate) {
				if(!no_interrupts) return 0;
				frameNum = play(filename, string_option, fps_option, frameNum);
				terminate = 0;
			}
		}
	}

	printf("\n");
	fflush(stdout);
	return 0;

}

int play(char* filename, char* string, char* fps_option, int subsequentPlay) {
	cv::VideoCapture cap(filename);
	if(!cap.isOpened()) return -1 * error((char*)"Can't read input");

	double fps = fps_option[0] == '\0' ? cap.get(CV_CAP_PROP_FPS) : atof(fps_option);

	struct timespec start, end;

	uint64_t delta_ns;
	uint64_t delayNecessary = fps == 0 || isnan(fps) ? 0 : NANO_CONV_FACTOR/fps;

	register int frameNum = 0;

	register int width, height, nchannels, step, offset;
	register int i, j;
	register unsigned char r_ch, b_ch, g_ch;
	cv::Mat frame;
	int ansiColor, ansiTextColor;
	unsigned char* data;

	int stringLength = strlen(string);

	int stopAfterFrame = 0;

	for(;;) {

		getSystemTime(&start);

		if(!frame.empty() || subsequentPlay) {

			cap >> frame;

			if(frame.empty()) break;

			for(i = 0; i < tty_height - 1; ++i)
				printf("\x1B[F");

		} else {

			cap >> frame;

			if(frame.empty()) break;

		}

		if(frame.depth() != CV_8U) {
			return -1 * error((char*)"Frame has incorrect depth");
		}

		width = frame.cols;
		height = frame.rows;
		nchannels = frame.channels();
		step = width * nchannels;

		getTTYDims();

		register int stringIter = 0;

		for(i = 0; i < tty_height; ++i) {
			data = (unsigned char*)(frame.data + ((int)((float)i*height/tty_height)*step));
			for(j = 0; j < tty_width; ++j) {
				offset = (int)((float)j*width/tty_width) * nchannels;
				b_ch = data[offset];
				g_ch = data[offset+1];
				r_ch = data[offset+2];

				ansiColor = generateANSIColor(r_ch, g_ch, b_ch);

				if(stringLength) {
					ansiTextColor = b_ch + g_ch + r_ch > 0x17F ? generateANSIColor(r_ch - 50, g_ch - 50, b_ch - 50) :
						generateANSIColor(r_ch + 50, g_ch + 50, b_ch + 50);

					printf(COLOR_TEXT_FORMAT, ansiColor, ansiTextColor, string[stringIter++%stringLength]);
				} else {
					printf(COLOR_FORMAT, ansiColor);
				}
			}
			printf(COLOR_RESET);
			if(i < tty_height - 1) {
				printf("\n");
			} else {
				printf("\x1B[m");
				fflush(stdout);
			}
		}

		if(stopAfterFrame) {
			break;
		}

		if(terminate && !no_interrupts) {
			stopAfterFrame = 1;
		}

		getSystemTime(&end);

		delta_ns = (end.tv_sec - start.tv_sec) * NANO_CONV_FACTOR + (end.tv_nsec - start.tv_nsec);

		waitFrame(delayNecessary, delta_ns);

		frameNum++;

	}

	return frameNum;

}

int waitFrame(uint64_t delayNecessary, uint64_t delta_ns) {

	struct timespec ts;
	long totalNanoSec;

	totalNanoSec = (delayNecessary - delta_ns);

	if(totalNanoSec < 0) return 1;

	ts.tv_sec = totalNanoSec/NANO_CONV_FACTOR;
	ts.tv_nsec = totalNanoSec%NANO_CONV_FACTOR;
	nanosleep(&ts, NULL);

	return 0;

}

unsigned char generateANSIColor(unsigned char r, unsigned char g, unsigned char b) {

	return 16 + (36 * lround(r*5.0/256)) + (6 * lround(g*5.0/256)) + lround(b*5.0/256);

}

void getTTYDims() {

	struct winsize w;
	ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
	tty_width = tty_width_custom > 0 ? tty_width_custom : w.ws_col;
	tty_height = tty_height_custom > 0 ? tty_height_custom : w.ws_row;

}

void getSystemTime(struct timespec* tv) {

		#ifdef __MACH__

		clock_serv_t cclock;
		mach_timespec_t mts;
		host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
		clock_get_time(cclock, &mts);
		mach_port_deallocate(mach_task_self(), cclock);

		tv->tv_sec = mts.tv_sec;
		tv->tv_nsec = mts.tv_nsec;

		#else

		clock_gettime(CLOCK_REALTIME, tv);

		#endif

}