File: SSRVideoStreamWriter.cpp

package info (click to toggle)
simplescreenrecorder 0.4.4-7
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,812 kB
  • sloc: cpp: 15,398; ansic: 769; sh: 203; php: 137; xml: 45; makefile: 20
file content (321 lines) | stat: -rw-r--r-- 10,721 bytes parent folder | download | duplicates (4)
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
/*
Copyright (c) 2012-2020 Maarten Baert <maarten-baert@hotmail.com>

Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

#include "SSRVideoStreamWriter.h"

#include <fcntl.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>

// Returns the program name (i.e. filename of the binary)
static std::string GetProgramName() {
	std::vector<char> temp(10000);
	ssize_t size = readlink("/proc/self/exe", temp.data(), temp.size());
	if(size < 0)
		return std::string();
	std::string path(temp.data(), size);
	size_t p = path.find_last_of('/');
	if(p == std::string::npos)
		return path;
	return path.substr(p + 1);
}

SSRVideoStreamWriter::SSRVideoStreamWriter(const std::string& channel, const std::string& source) {

	std::string stream_name = NumToString(hrt_time_micro()) + "-" + NumToString(getpid()) + "-" + source + "-" + GetProgramName();

	m_channel_directory = "/dev/shm/ssr-" + ((channel.empty())? "channel-" + GetUserName() : channel);
	m_filename_main = m_channel_directory + "/video-" + stream_name;
	m_page_size = sysconf(_SC_PAGE_SIZE);
	m_width = 0;
	m_height = 0;
	m_stride = 0;
	m_next_frame_time = hrt_time_micro();

	m_fd_main = -1;
	m_mmap_ptr_main = MAP_FAILED;
	m_mmap_size_main = 0;

	for(unsigned int i = 0; i < GLINJECT_RING_BUFFER_SIZE; ++i) {
		FrameData &fd = m_frame_data[i];
		fd.m_filename_frame = m_channel_directory + "/videoframe" + NumToString(i) + "-" + stream_name;
		fd.m_fd_frame = -1;
		fd.m_mmap_ptr_frame = MAP_FAILED;
		fd.m_mmap_size_frame = 0;
	}

	try {
		Init();
	} catch(...) {
		Free();
		throw;
	}

}

SSRVideoStreamWriter::~SSRVideoStreamWriter() {
	Free();
}

void SSRVideoStreamWriter::Init() {

	GLINJECT_PRINT("[" << m_filename_main << "] Created video stream.");

	bool relax_permissions = false;
	{
		char *ssr_stream_relax_permissions = getenv("SSR_STREAM_RELAX_PERMISSIONS");
		if(ssr_stream_relax_permissions != NULL && atoi(ssr_stream_relax_permissions) > 0) {
			GLINJECT_PRINT("Warning: Using relaxed file permissions, any user on this machine will be able to read or manipulate the stream!");
			relax_permissions = true;
		}
	}

	// create channel directory (permissions may be wrong because of umask, fix this later)
	if(mkdir(m_channel_directory.c_str(), (relax_permissions)? 0777 : 0700) == -1) {
		if(errno != EEXIST) { // does the directory already exist?
			GLINJECT_PRINT("Error: Can't create channel directory!");
			throw SSRStreamException();
		}
	}

	// check ownership and permissions
	struct stat statinfo;
	if(lstat(m_channel_directory.c_str(), &statinfo) == -1) {
		GLINJECT_PRINT("Error: Can't stat channel directory!");
		throw SSRStreamException();
	}
	if(!S_ISDIR(statinfo.st_mode) || S_ISLNK(statinfo.st_mode)) {
		GLINJECT_PRINT("Error: Channel directory is not a regular directory!");
		throw SSRStreamException();
	}
	if(statinfo.st_uid == geteuid()) {
		if(chmod(m_channel_directory.c_str(), (relax_permissions)? 0777 : 0700) == -1) {
			GLINJECT_PRINT("Error: Can't set channel directory mode!");
			throw SSRStreamException();
		}
	} else {
		if(!relax_permissions) {
			GLINJECT_PRINT("Error: Channel directory is owned by a different user! "
							"Choose a different channel name, or enable relaxed file permissions to use it anyway.");
			throw SSRStreamException();
		}
	}

	// open frame files
	for(unsigned int i = 0; i < GLINJECT_RING_BUFFER_SIZE; ++i) {
		FrameData &fd = m_frame_data[i];
		fd.m_fd_frame = open(fd.m_filename_frame.c_str(), O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, (relax_permissions)? 0666 : 0600);
		if(fd.m_fd_frame == -1) {
			GLINJECT_PRINT("Error: Can't open video frame file!");
			throw SSRStreamException();
		}
		if(fchmod(fd.m_fd_frame, (relax_permissions)? 0666 : 0600) == -1) {
			GLINJECT_PRINT("Error: Can't set video frame file mode!");
			throw SSRStreamException();
		}
	}

	// open main file
	m_fd_main = open(m_filename_main.c_str(), O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, (relax_permissions)? 0666 : 0600);
	if(m_fd_main == -1) {
		GLINJECT_PRINT("Error: Can't open video stream file!");
		throw SSRStreamException();
	}
	if(fchmod(m_fd_main, (relax_permissions)? 0666 : 0600) == -1) {
			GLINJECT_PRINT("Error: Can't set video stream file mode!");
		throw SSRStreamException();
	}

	// resize main file
	m_mmap_size_main = (sizeof(GLInjectHeader) + GLINJECT_RING_BUFFER_SIZE * sizeof(GLInjectFrameInfo) + m_page_size - 1) / m_page_size * m_page_size;
	if(ftruncate(m_fd_main, m_mmap_size_main) == -1) {
		GLINJECT_PRINT("Error: Can't resize video stream file!");
		throw SSRStreamException();
	}

	// map main file
	m_mmap_ptr_main = mmap(NULL, m_mmap_size_main, PROT_READ | PROT_WRITE, MAP_SHARED, m_fd_main, 0);
	if(m_mmap_ptr_main == MAP_FAILED) {
		GLINJECT_PRINT("Error: Can't memory-map video stream file!");
		throw SSRStreamException();
	}

	// initialize header
	GLInjectHeader *header = GetGLInjectHeader();
	header->identifier = 0; // will be set later
	header->ring_buffer_read_pos = 0;
	header->ring_buffer_write_pos = 0;
	header->current_width = m_width;
	header->current_height = m_height;
	header->frame_counter = 0;

	// initialize frame info
	for(unsigned int i = 0; i < GLINJECT_RING_BUFFER_SIZE; ++i) {
		GLInjectFrameInfo *frameinfo = GetGLInjectFrameInfo(i);
		frameinfo->timestamp = 0;
		frameinfo->width = 0;
		frameinfo->height = 0;
		frameinfo->stride = 0;
	}

	// set the identifier to indicate that initialization is complete
	std::atomic_thread_fence(std::memory_order_release);
	header->identifier = GLINJECT_IDENTIFIER;
	std::atomic_thread_fence(std::memory_order_release);

}

void SSRVideoStreamWriter::Free() {

	for(unsigned int i = 0; i < GLINJECT_RING_BUFFER_SIZE; ++i) {
		FrameData &fd = m_frame_data[i];

		// unmap frame file
		if(fd.m_mmap_ptr_frame != MAP_FAILED) {
			munmap(fd.m_mmap_ptr_frame, fd.m_mmap_size_frame);
			fd.m_mmap_ptr_frame = MAP_FAILED;
		}

		// close and unlink frame file
		if(fd.m_fd_frame != -1) {
			close(fd.m_fd_frame);
			fd.m_fd_frame = -1;
			unlink(fd.m_filename_frame.c_str());
		}

	}

	// unmap main file
	if(m_mmap_ptr_main != MAP_FAILED) {
		munmap(m_mmap_ptr_main, m_mmap_size_main);
		m_mmap_ptr_main = MAP_FAILED;
	}

	// close and unlink main file
	if(m_fd_main != -1) {
		close(m_fd_main);
		m_fd_main = -1;
		unlink(m_filename_main.c_str());
	}

	GLINJECT_PRINT("[" << m_filename_main << "] Destroyed video stream.");

}

GLInjectHeader* SSRVideoStreamWriter::GetGLInjectHeader() {
	return (GLInjectHeader*) m_mmap_ptr_main;
}

GLInjectFrameInfo* SSRVideoStreamWriter::GetGLInjectFrameInfo(unsigned int frame) {
	return (GLInjectFrameInfo*) ((char*) m_mmap_ptr_main + sizeof(GLInjectHeader) + frame * sizeof(GLInjectFrameInfo));
}

void SSRVideoStreamWriter::UpdateSize(unsigned int width, unsigned int height, int stride) {
	if(m_width != width || m_height != height) {
		GLINJECT_PRINT("[" << m_filename_main << "] frame size = " << width << "x" << height << ".");
		m_width = width;
		m_height = height;
		GLInjectHeader *header = GetGLInjectHeader();
		header->current_width = m_width;
		header->current_height = m_height;
		std::atomic_thread_fence(std::memory_order_release);
	}
	m_stride = stride;
}

void* SSRVideoStreamWriter::NewFrame(unsigned int* flags) {

	// increment the frame counter
	GLInjectHeader *header = GetGLInjectHeader();
	++header->frame_counter;
	std::atomic_thread_fence(std::memory_order_release);

	// get capture parameters
	std::atomic_thread_fence(std::memory_order_acquire);
	*flags = header->capture_flags;
	if(!(*flags & GLINJECT_FLAG_CAPTURE_ENABLED))
		return NULL;

	// check the timestamp and maybe limit the fps
	unsigned int target_fps = header->capture_target_fps;
	int64_t timestamp = hrt_time_micro();
	if(target_fps > 0) {
		int64_t interval = 1000000 / target_fps;
		if(*flags & GLINJECT_FLAG_LIMIT_FPS) {
			if(timestamp < m_next_frame_time) {
				usleep(m_next_frame_time - timestamp);
				timestamp = hrt_time_micro();
			}
		} else {
			if(timestamp < m_next_frame_time - interval)
				return NULL;
		}
		m_next_frame_time = std::max(m_next_frame_time + interval, timestamp);
	}

	// make sure that at least one frame is available
	unsigned int read_pos = header->ring_buffer_read_pos;
	unsigned int write_pos = header->ring_buffer_write_pos;
	unsigned int frames_used = positive_mod((int) write_pos - (int) read_pos, GLINJECT_RING_BUFFER_SIZE * 2);
	if(frames_used >= GLINJECT_RING_BUFFER_SIZE)
		return NULL;

	// write frame info
	GLInjectFrameInfo *frameinfo = GetGLInjectFrameInfo(write_pos % GLINJECT_RING_BUFFER_SIZE);
	frameinfo->timestamp = timestamp;
	frameinfo->width = m_width;
	frameinfo->height = m_height;
	frameinfo->stride = m_stride;

	// prepare the frame file
	FrameData &fd = m_frame_data[write_pos % GLINJECT_RING_BUFFER_SIZE];
	size_t required_size = (size_t) abs(m_stride) * (size_t) m_height;
	if(required_size > fd.m_mmap_size_frame) {

		// calculate new size
		required_size = (required_size + required_size / 4 + m_page_size - 1) / m_page_size * m_page_size;

		// unmap frame file
		if(fd.m_mmap_ptr_frame != MAP_FAILED) {
			munmap(fd.m_mmap_ptr_frame, fd.m_mmap_size_frame);
			fd.m_mmap_ptr_frame = MAP_FAILED;
			fd.m_mmap_size_frame = 0;
		}

		// resize frame file
		if(ftruncate(fd.m_fd_frame, required_size) == -1) {
			GLINJECT_PRINT("Error: Can't resize video frame file!");
			throw SSRStreamException();
		}

		// map frame file
		fd.m_mmap_ptr_frame = mmap(NULL, required_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd.m_fd_frame, 0);
		if(fd.m_mmap_ptr_frame == MAP_FAILED) {
			GLINJECT_PRINT("Error: Can't memory-map video frame file!");
			throw SSRStreamException();
		}
		fd.m_mmap_size_frame = required_size;

	}

	return fd.m_mmap_ptr_frame;
}

void SSRVideoStreamWriter::NextFrame() {

	// make sure all changes are visible
	std::atomic_thread_fence(std::memory_order_release);

	// go to the next frame
	GLInjectHeader *header = GetGLInjectHeader();
	header->ring_buffer_write_pos = (header->ring_buffer_write_pos + 1) % (GLINJECT_RING_BUFFER_SIZE * 2);
	std::atomic_thread_fence(std::memory_order_release);

}