summaryrefslogtreecommitdiff
path: root/src/main.cpp
blob: 42bed62ac4abbcf9fce24f0aea2d8d5398923e0a (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
/*
 * main.cpp
 *
 *  Created on: 2014. 6. 10.
 *      Author: oskwon
 */

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <poll.h>
#include <errno.h>
#include <signal.h>

#include <string>

#include "trap.h"
#include "mpegts.h"

#include "Utils.h"
#include "Logger.h"

#include "Demuxer.h"
#include "Encoder.h"

using namespace std;
//----------------------------------------------------------------------

#define RESPONSE_FD  (1)
#define BUFFFER_SIZE (188 * 256)

void signal_handler(int sig_no);
void do_exit(const char *message);

static bool is_terminated = true;
//----------------------------------------------------------------------

void *streaming_thread_main(void *params)
{
	if (is_terminated) return 0;

	INFO("streaming thread start.");
	Encoder *encoder = ((ThreadParams*) params)->encoder;
	RequestHeader *header = ((ThreadParams*) params)->request;

	try {
		int poll_state, rc, wc;
		struct pollfd poll_fd[2];
		unsigned char buffer[BUFFFER_SIZE];

		poll_fd[0].fd = encoder->get_fd();
		poll_fd[0].events = POLLIN | POLLHUP;

		while(!is_terminated) {
			poll_state = poll(poll_fd, 1, 1000);
			if (poll_state == -1) {
				throw(trap("poll error."));
			}
			else if (poll_state == 0) {
				continue;
			}
			if (poll_fd[0].revents & POLLIN) {
				rc = wc = 0;
				rc = read(encoder->get_fd(), buffer, BUFFFER_SIZE - 1);
				if (rc <= 0) {
					break;
				}
				else if (rc > 0) {
					wc = write(RESPONSE_FD, buffer, rc);
					//DEBUG("write : %d", wc);
					if (wc < rc) {
						//DEBUG("need rewrite.. remain (%d)", rc - wc);
						int retry_wc = 0;
						for (int remain_len = rc - wc; rc != wc; remain_len -= retry_wc) {
							poll_fd[0].revents = 0;

							retry_wc = write(RESPONSE_FD, (buffer + rc - remain_len), remain_len);
							wc += retry_wc;
						}
						LOG("re-write result : %d - %d", wc, rc);
					}
				}
			}
			else if (poll_fd[0].revents & POLLHUP)
			{
				if (encoder->state == Encoder::ENCODER_STAT_STARTED) {
					DEBUG("stop transcoding..");
					encoder->ioctl(Encoder::IOCTL_STOP_TRANSCODING, 0);
				}
				break;
			}
		}
	}
	catch (const trap &e) {
		ERROR("%s %s (%d)", e.what(), strerror(errno), errno);
	}
	do_exit(0);
	INFO("streaming thread stop.");

	if (encoder->state == Encoder::ENCODER_STAT_STARTED) {
		DEBUG("stop transcoding..");
		encoder->ioctl(Encoder::IOCTL_STOP_TRANSCODING, 0);
	}

	pthread_exit(0);

	return 0;
}
//----------------------------------------------------------------------

void *source_thread_main(void *params)
{
	Source *source = ((ThreadParams*) params)->source;
	Encoder *encoder = ((ThreadParams*) params)->encoder;
	RequestHeader *header = ((ThreadParams*) params)->request;

	INFO("source thread start.");

	try {
		int poll_state, rc, wc;
		struct pollfd poll_fd[2];
		unsigned char buffer[BUFFFER_SIZE];

		poll_fd[0].fd = encoder->get_fd();
		poll_fd[0].events = POLLOUT;

		poll_fd[1].fd = source->get_fd();
		poll_fd[1].events = POLLIN;

		while(!is_terminated) {
			poll_state = poll(poll_fd, 2, 1000);
			if (poll_state == -1) {
				throw(trap("poll error."));
			}
			else if (poll_state == 0) {
				continue;
			}

			if (poll_fd[0].revents & POLLOUT) {
				rc = wc = 0;
				if (poll_fd[1].revents & POLLIN) {
					rc = read(source->get_fd(), buffer, BUFFFER_SIZE - 1);
					if (rc == 0) {
						break;
					}
					else if (rc > 0) {
						wc = write(encoder->get_fd(), buffer, rc);
						//DEBUG("write : %d", wc);
						if (wc < rc) {
							//DEBUG("need rewrite.. remain (%d)", rc - wc);
							int retry_wc = 0;
							for (int remain_len = rc - wc; rc != wc; remain_len -= retry_wc) {
								poll_fd[0].revents = 0;

								poll_state = poll(poll_fd, 1, 1000);
								if (poll_fd[0].revents & POLLOUT) {
									retry_wc = write(encoder->get_fd(), (buffer + rc - remain_len), remain_len);
									wc += retry_wc;
								}
							}
							LOG("re-write result : %d - %d", wc, rc);
							usleep(500000);
						}
					}
				}
			}
		}
	}
	catch (const trap &e) {
		ERROR("%s %s (%d)", e.what(), strerror(errno), errno);
	}
	INFO("source thread stop.");

	pthread_exit(0);

	return 0;
}
//----------------------------------------------------------------------

int main(int argc, char **argv)
{
	if (access("/tmp/.debug_on", F_OK) == 0) {
		Logger::instance()->init("/tmp/transtreamproxy", Logger::DEBUG, false, "3.0");
	}
	else {
		Logger::instance()->init("/tmp/transtreamproxy", Logger::WARNING, false, "3.0");
	}
	signal(SIGINT, signal_handler);

	RequestHeader header;

	int source_thread_id, stream_thread_id;
	pthread_t source_thread_handle, stream_thread_handle;

	std::string req = read_request();

	DEBUG("request head :\n%s", req.c_str());
	if (header.parse_header(req)) {
		Encoder encoder;
		Source *source = 0;
		ThreadParams thread_params = { 0, &encoder, &header };

		int video_pid = 0, audio_pid = 0, pmt_pid = 0;

		switch(header.type) {
		case REQ_TYPE_TRANSCODING_FILE:
			try {
				MpegTS *ts = new MpegTS(header.extension["file"], true);
				pmt_pid   = ts->pmt_pid;
				video_pid = ts->video_pid;
				audio_pid = ts->audio_pid;
				source = ts;
			}
			catch (const trap &e) {
				ERROR("fail to create source : %s", e.what());
				exit(-1);
			}
			break;
		case REQ_TYPE_TRANSCODING_LIVE:
			try {
				Demuxer *dmx = new Demuxer(&header);
				pmt_pid   = dmx->pmt_pid;
				video_pid = dmx->video_pid;
				audio_pid = dmx->audio_pid;
				source = dmx;
			}
			catch (const trap &e) {
				ERROR("fail to create source : %s", e.what());
				exit(-1);
			}
			break;
		default:
			ERROR("not support source type (type : %d)", header.type);
			exit(-1);
		}
		thread_params.source = source;

		if (!encoder.retry_open(2, 3)) {
			exit(-1);
		}

		if (encoder.state == Encoder::ENCODER_STAT_OPENED) {
			std::string response;
			off_t byte_offset = 0;
			if ((byte_offset = make_response((ThreadParams*) &thread_params, response)) < 0) {
				do_exit(0);
				return 0;
			}

			write(RESPONSE_FD, response.c_str(), response.length());
			DEBUG("response data :\n%s", response.c_str());

			if (header.type == REQ_TYPE_TRANSCODING_FILE) {
				try {
					std::string position = header.extension["position"];
					if (position == "") {
						DEBUG("seek to byte_offset %llu", byte_offset);
						((MpegTS*)source)->seek_absolute(byte_offset);
						DEBUG("seek ok");
					}
					else {
						unsigned int position_offset = strtollu(position);
						if(((MpegTS*)source)->is_time_seekable && (position_offset > 0)) {
							DEBUG("seek to position_offset %ds", position_offset);
							((MpegTS*)source)->seek_time((position_offset * 1000) + ((MpegTS*)source)->first_pcr_ms);
							DEBUG("seek ok");
						}
					}
				}
				catch (const trap &e) {
					WARNING("Exception : %s", e.what());
				}
			}

			if (!encoder.ioctl(Encoder::IOCTL_SET_VPID, video_pid)) {
				do_exit("fail to set video pid.");
				exit(-1);
			}
			if (!encoder.ioctl(Encoder::IOCTL_SET_APID, audio_pid)) {
				do_exit("fail to set audio pid.");
				exit(-1);
			}
			if (!encoder.ioctl(Encoder::IOCTL_SET_PMTPID, pmt_pid)) {
				do_exit("fail to set pmtid.");
				exit(-1);
			}
		}

		is_terminated = false;
		source_thread_id = pthread_create(&source_thread_handle, 0, source_thread_main, (void *)&thread_params);
		if (source_thread_id < 0) {
			do_exit("fail to create source thread.");
		}
		else {
			pthread_detach(source_thread_handle);
			sleep(1);
			if (!encoder.ioctl(Encoder::IOCTL_START_TRANSCODING, 0)) {
				do_exit("fail to start transcoding.");
			}
			else {
				stream_thread_id = pthread_create(&stream_thread_handle, 0, streaming_thread_main, (void *)&thread_params);
				if (stream_thread_id < 0) {
					do_exit("fail to create stream thread.");
				}
			}
		}
		pthread_join(stream_thread_handle, 0);

		if (source != 0) {
			delete source;
			source = 0;
		}
	}
	return 0;
}
//----------------------------------------------------------------------

void do_exit(const char *message)
{
	is_terminated = true;
	if (message) {
		ERROR("%s", message);
	}
}
//----------------------------------------------------------------------

void signal_handler(int sig_no)
{
	INFO("signal no : %d", sig_no);
	do_exit("signal detected..");
}
//----------------------------------------------------------------------