-
Notifications
You must be signed in to change notification settings - Fork 2
/
tcp2http.c
2092 lines (1857 loc) · 62.1 KB
/
tcp2http.c
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @brief A simple HTTP TS/FLV server. Input stream use a modified tcp protocol of ffmpeg which add stream publish url.
*
* TODO:
* client in重新接入后,应比较流信息,如果不一致则踢掉所有client out
*/
#include <stdio.h>
#include <unistd.h>
#include <ctype.h>
#include <getopt.h>
#include <netdb.h>
#include <sys/epoll.h>
#include <sys/times.h>
#include <signal.h>
//getrlimit and setrlimit
#include <sys/time.h>
#include <sys/resource.h>
#define __USE_GNU
#include <sched.h>
#include <pthread.h>
#include "libavformat/avformat.h"
#include "map.h"
#include "utils.h"
//#define DEBUG
#define DO_LOCK
#define MAX_URL_SIZE 1024
#define MAX_TOKEN_SIZE 32
#define MAX_EVENTS 256
#define MAX_FD_ALLOWED (1024 * 1024 * 100)
#define MAX_GOP 512
#define MAX_OUT_THREAD 128
#define TRY_OPEN_STEP (1024 * 256)
#define TRY_OPEN_SKIP (1024 * 1024 * 10)
#define QUEUE_INPUT_SIZE (1024 * 1024 * 5) //能放下一个大的I帧
#define AVIO_CTX_BUFFER_SIZE 4096
#define REQUEST_BUF_SIZE 4096
#define INACTIVE_TIMEOUT 10 //in seconds
#define CLIENT_IN 0xACEDBF59
#define CLIENT_OUT 0xFB95CADE
typedef struct _client_out_t client_out_t;
typedef struct _outs_info_t
{
client_out_t *outs;
client_out_t *outs2send;
int64_t wait_index;
} outs_info_t;
typedef struct _client_in_t
{
//ATTENTION: 以下变量位置不能改变
uint32_t client_type;
struct _client_in_t *p_next;
int in_queue;
time_t last_active;
int fd;
int url_read;
char url[1024 + 1];
int opened;
outs_info_t outs_info[MAX_OUT_THREAD];
int keep_frames;
int video_index;
int video_pid;
FILE *dump_fp;
pthread_t thrd_read_frame;
int exit_flag;
uint8_t queue_buf_input[QUEUE_INPUT_SIZE];
int64_t input_head_offset;
int read_pos;
int write_pos;
int head;
int read_error;
void *gop[MAX_GOP];
int64_t gop_head;
int64_t gop_tail;
int last_is_key;
int key_count;
int try_open_size;
int try_open_skip;
AVFormatContext *fmt_ctx;
AVIOContext *avio_ctx;
AVPacket pkt;
int is_flv;
int flv_skip_header; //skip flv header in stream
AVBufferRef *flv_header;
} client_in_t;
struct _client_out_t
{
//ATTENTION: 以下变量位置不能改变
uint32_t client_type;
client_out_t *p_next;
int in_queue;
client_out_t *p_next2;
int in_queue2;
int thread_index;
int fd;
client_in_t *client_in;
AVBufferRef *frame;
int write_pos;
int64_t frame_pos;
int status;
char *request_buf;
FILE *dump_fp;
};
typedef struct _tcp2http_t tcp2http_t;
typedef struct _out_thread_t
{
int index;
int exit_flag;
int efd;
tcp2http_t *tcp2http;
struct epoll_event *events;
int64_t client_count;
pthread_t thrd_out;
pthread_mutex_t mutex;
} out_thread_t;
typedef struct _tcp2http_t
{
int exit_flag;
int efd;
struct epoll_event *events;
int sfd_in;
int sfd_out;
map_t *map;
client_in_t *inputs_inactive;
client_in_t *inputs;
out_thread_t out_threads[MAX_OUT_THREAD];
//parameters
int input_port;
int output_port;
int console_mode;
int keep_frames;
int max_fd;
char dump_dir[MAX_URL_SIZE];
char token[MAX_TOKEN_SIZE + 1];
int out_threads_count;
int out_threads_bind[MAX_OUT_THREAD];
} tcp2http_t;
#define ADD_NODE(p_head, node, type, ptr_name, in_queue) \
{ \
if ((node)->in_queue == 0) \
{ \
(node)->ptr_name = (p_head); \
(p_head) = (node); \
(node)->in_queue = 1; \
} \
}
#define REMOVE_NODE(p_head, node, type, ptr_name, in_queue) \
{ \
type *pp, *qq; \
pp = NULL; \
qq = (p_head); \
while (qq != NULL) \
{ \
if (qq == (node)) \
{ \
if (pp == NULL) \
(p_head) = qq->ptr_name; \
else \
pp->ptr_name = qq->ptr_name; \
qq->in_queue = 0; \
break; \
} \
pp = qq; \
qq = qq->ptr_name; \
} \
}
#define add_node(p_head, node, type) ADD_NODE(p_head, node, type, p_next, in_queue)
#define remove_node(p_head, node, type) REMOVE_NODE(p_head, node, type, p_next, in_queue)
static void process_client_out(out_thread_t *out_thread, client_out_t *client, int epoll_call);
#ifdef DO_LOCK
#define LOCK(mutex) pthread_mutex_lock(mutex)
#define UNLOCK(mutex) pthread_mutex_unlock(mutex)
#else
#define LOCK(mutex)
#define UNLOCK(mutex)
#endif
static const char *short_options = "h";
static const struct option long_options[] =
{
{ "help", 0, NULL, 'h' },
{ "input_port", 1, NULL, 0 },
{ "output_port", 1, NULL, 0 },
{ "keep_frames", 1, NULL, 0 },
{ "max_fd", 1, NULL, 0 },
{ "token", 1, NULL, 0 },
{ "threads_count", 1, NULL, 0 },
{ "threads_bind", 1, NULL, 0 },
//just for debug
{ "dump_dir", 1, NULL, 0 },
{ "console_mode", 0, NULL, 0 },
{ NULL, 0, NULL, 0 }
};
static void print_help(const char *name, FILE *stream)
{
fprintf(stream, "tcp2http [A simple HTTP server for live FLV and MPEG TS streams]\n"
"Usage\n"
"\t-h --help:\t\tDisplay this usage information.\n\n"
"\t--input_port:\t\tSet stream input port.\n"
"\t--output_port:\t\tSet the HTTP server port.\n"
"\t--keep_frames:\t\tLet server keep more video frames than a GOP, "
"which allow players to quick start but image may later than realtime.\n"
"\t--max_fd:\t\tSet the max fd to be used.\n"
"\t--token:\t\tSet the password of input stream.\n\n"
"\t--threads_count:\tSet how many output threads to use.\n"
"\t--threads_bind:\t\tSet cpu index of output threads to bind.\n\n"
"\t--dump_dir:\t\tSpecify stream dump directory, just for debug.\n"
"\t--console_mode:\t\tDebug in console, press enter key to exit program.\n"
);
}
static int parser_opt(int argc, char* const *argv, tcp2http_t *tcp2http)
{
int ret;
int long_index;
optind = 0; //ATTENTION: reset getopt_long
while ((ret = getopt_long(argc, argv, short_options, long_options, &long_index)) != -1)
{
switch (ret)
{
case 0:
//long only options
if (strncmp(long_options[long_index].name, "input_port", strlen("input_port")) == 0)
{
tcp2http->input_port = atoi(optarg);
}
else if (strncmp(long_options[long_index].name, "output_port", strlen("output_port")) == 0)
{
tcp2http->output_port = atoi(optarg);
}
else if (strncmp(long_options[long_index].name, "keep_frames", strlen("keep_frames")) == 0)
{
tcp2http->keep_frames = atoi(optarg);
if (tcp2http->keep_frames < 0 || tcp2http->keep_frames > MAX_GOP)
{
fprintf(stderr, "keep_frames value should be in range [0, %d]\n", MAX_GOP);
exit(-1);
}
}
else if (strncmp(long_options[long_index].name, "max_fd", strlen("max_fd")) == 0)
{
tcp2http->max_fd = atoi(optarg);
if (tcp2http->max_fd < 1024 || tcp2http->max_fd > MAX_FD_ALLOWED)
{
fprintf(stderr, "max_fa value should be in range [1024, MAX_FD_ALLOWED)\n");
exit(-1);
}
}
else if (strncmp(long_options[long_index].name, "token", strlen("token")) == 0)
{
strncpy(tcp2http->token, optarg, MAX_TOKEN_SIZE);
fprintf(stderr, "set server token to [%s]\n", tcp2http->token);
}
else if (strncmp(long_options[long_index].name, "threads_count", strlen("threads_count")) == 0)
{
tcp2http->out_threads_count = atoi(optarg);
if (tcp2http->out_threads_count < 1 || tcp2http->out_threads_count > MAX_OUT_THREAD)
{
fprintf(stderr, "out_threads_count value should be in range [1, MAX_OUT_THREAD]\n");
exit(-1);
}
}
else if (strncmp(long_options[long_index].name, "threads_bind", strlen("threads_bind")) == 0)
{
char tmp[MAX_URL_SIZE];
char *p = tmp, *q;
int i;
strncpy(tmp, optarg, MAX_URL_SIZE - 1);
for (i = 0; i < MAX_OUT_THREAD; i++)
{
q = strsep(&p, ",");
if (q == NULL)
break;
tcp2http->out_threads_bind[i] = atoi(q);
}
}
else if (strncmp(long_options[long_index].name, "dump_dir", strlen("dump_dir")) == 0)
{
strncpy(tcp2http->dump_dir, optarg, MAX_URL_SIZE - 1);
}
else if (strncmp(long_options[long_index].name, "console_mode", strlen("console_mode")) == 0)
{
tcp2http->console_mode = 1;
}
break;
case 'h':
print_help(argv[0], stdout);
exit(0);
case ':':
fprintf(stderr, "parameter reqired!\n");
print_help(argv[0], stderr);
exit(-1);
case '?':
fprintf(stderr, "unknown options!\n");
print_help(argv[0], stderr);
exit(-1);
case -1:
//处理完毕
break;
default:
fprintf(stderr, "unknown options! abort\n");
return -1;
}
}
return 0;
}
#ifdef DEBUG
static unsigned int get_tick_ms()
{
struct tms tm;
static uint32_t timeorigin;
static int firsttimehere = 0;
uint32_t now = times(&tm);
if(firsttimehere == 0)
{
timeorigin = now;
firsttimehere = 1;
}
return (now - timeorigin) * 10;
}
static void print_list(client_in_t *head)
{
client_in_t *ci;
int i;
for (ci = head, i = 0; ci != NULL; ci = ci->p_next, i++)
fprintf(stderr, "%d:%p|\t", i, ci);
fprintf(stderr, "\n");
}
#endif
static int parser_url(char *url, char *keys[], char *values[])
{
char *p, *q, *r;
int i;
p = strchr(url, '?');
if (p == NULL)
return 0;
*p = '\0';
p += 1;
if (strchr(p, '/') != NULL)
{
fprintf(stderr, "invalid params:%s\n", p);
return -1;
}
for (; ;)
{
q = strchr(p, '=');
if (q == NULL)
break;
*q = '\0';
r = strchr(q + 1, '&');
if (r != NULL)
*r = '\0';
for (i = 0; keys[i] != NULL; i++)
{
if (strcmp(keys[i], p) == 0)
{
p = q + 1;
values[i] = p;
break;
}
}
if (r == NULL)
break;
p = r + 1;
}
return 0;
}
static void clean_url(char *url)
{
char *p;
for (; ;)
{
p = strstr(url, "//");
if (p == NULL)
break;
memmove(p, p + 1, strlen(p + 1) + 1);
}
}
static int clean_client_in(tcp2http_t *h, client_in_t *client, int inactive)
{
struct epoll_event event;
client_out_t *co;
int i;
map_remove(h->map, client->fd);
memset(&event, 0, sizeof(event));
event.data.fd = client->fd;
epoll_ctl(h->efd, EPOLL_CTL_DEL, client->fd, &event);
close(client->fd);
client->exit_flag = 1;
while (client->exit_flag != 2)
usleep(10000);
if (client->dump_fp != NULL)
fclose(client->dump_fp);
if (client->avio_ctx != NULL)
{
av_freep(&client->avio_ctx->buffer);
av_freep(&client->avio_ctx);
}
if (client->fmt_ctx != NULL && client->opened > 0)
avformat_close_input(&client->fmt_ctx);
av_buffer_unref(&client->flv_header);
for (i = 0; i < MAX_GOP; i++)
{
if (client->gop[i] != NULL)
av_buffer_unref((AVBufferRef **)&client->gop[i]);
}
for (i = 0; i < h->out_threads_count; i++)
LOCK(&h->out_threads[i].mutex);
remove_node(h->inputs, client, client_in_t);
for (i = 0; i < h->out_threads_count; i++)
UNLOCK(&h->out_threads[i].mutex);
if (inactive != 0)
{
fprintf(stderr, "put in client [%d:%s] to inactive\n", client->fd, client->url);
add_node(h->inputs_inactive, client, client_in_t);
time(&client->last_active);
client->gop_head = 0;
client->gop_tail = 0;
for (i = 0; i < h->out_threads_count; i++)
{
LOCK(&h->out_threads[i].mutex);
for (co = client->outs_info[i].outs; co != NULL; co = co->p_next)
{
#ifdef DEBUG
fprintf(stderr, "reset client_out [%d:%p]\n", co->fd, co);
#endif
co->frame_pos = -2;
}
UNLOCK(&h->out_threads[i].mutex);
}
}
return 0;
}
static void destroy_client_out(tcp2http_t *h, client_out_t *client)
{
struct epoll_event event;
int ret;
map_remove(h->map, client->fd);
if (client->client_in != NULL)
{
remove_node(client->client_in->outs_info[client->thread_index].outs, client, client_out_t);
REMOVE_NODE(client->client_in->outs_info[client->thread_index].outs2send, client, client_out_t, p_next2, in_queue2);
}
memset(&event, 0, sizeof(event));
event.data.fd = client->fd;
ret = epoll_ctl(h->out_threads[client->thread_index].efd, EPOLL_CTL_DEL, client->fd, &event);
#ifdef DEBUG
fprintf(stderr, "epoll_ctl delete thread:%d, %d, efd:%d, sfd:%d\n", client->thread_index, (int)pthread_self(),
h->out_threads[client->thread_index].efd, client->fd);
#endif
if (ret == -1)
fprintf(stderr, "epoll_ctl delete %d error: %s\n", client->fd, strerror(errno));
close(client->fd);
if (client->dump_fp != NULL)
fclose(client->dump_fp);
av_buffer_unref(&client->frame);
free(client);
}
static void destroy_client_in(tcp2http_t *h, client_in_t *client)
{
client_out_t *co;
outs_info_t *out_info;
int i;
for (i = 0; i < h->out_threads_count; i++)
{
out_info = &client->outs_info[i];
LOCK(&h->out_threads[i].mutex);
for (; ;)
{
co = out_info->outs;
if (co == NULL)
break;
destroy_client_out(h, co);
}
UNLOCK(&h->out_threads[i].mutex);
}
free(client);
}
static void* output_proc(void *arg)
{
out_thread_t *out_thread = (out_thread_t *)arg;
tcp2http_t *tcp2http = out_thread->tcp2http;
client_out_t *co, *cot;
client_in_t *ci;
int count;
int i;
for (; ;)
{
if (out_thread->exit_flag == 1)
{
fprintf(stderr, "output_proc %d got exit flag\n", out_thread->index);
out_thread->exit_flag = 2;
return NULL;
}
//发送端进程挂掉时,此处无法立即发现,长时间只是认为对应的fd没有数据
count = epoll_wait(out_thread->efd, out_thread->events, MAX_EVENTS, 100);
for (i = 0; i < count; i++)
{
if ((out_thread->events[i].events & EPOLLERR) || (out_thread->events[i].events & EPOLLHUP))
{
fprintf(stderr, "receive epoll error, %d, %x, %x, %x, %x\n", out_thread->events[i].data.fd,
EPOLLERR, EPOLLHUP, EPOLLIN, EPOLLOUT);
co = map_get(tcp2http->map, out_thread->events[i].data.fd);
if (co != NULL && co->client_type == CLIENT_OUT)
{
LOCK(&out_thread->mutex);
destroy_client_out(tcp2http, co);
UNLOCK(&out_thread->mutex);
}
continue;
}
else
{
co = map_get(tcp2http->map, out_thread->events[i].data.fd);
if (co == NULL)
fprintf(stderr, "client is NULL for fd [%d], should not go here!\n", out_thread->events[i].data.fd);
if (co->client_type == CLIENT_OUT)
{
LOCK(&out_thread->mutex);
process_client_out(out_thread, co, 1);
UNLOCK(&out_thread->mutex);
}
else
fprintf(stderr, "unknown client type [%d] for fd [%d]\n", co->client_type, out_thread->events[i].data.fd);
}
}
LOCK(&out_thread->mutex);
for (ci = tcp2http->inputs; ci != NULL; ci = ci->p_next)
{
outs_info_t *info = &ci->outs_info[out_thread->index];
if (info->wait_index < ci->gop_tail)
{
co = info->outs2send;
cot = NULL;
for (; ;)
{
if (co == NULL)
break;
cot = co->p_next2;
process_client_out(out_thread, co, 0);
co = cot;
}
info->wait_index = ci->gop_tail;
}
}
UNLOCK(&out_thread->mutex);
}
return NULL;
}
static int output_thread_create(tcp2http_t *h, out_thread_t *out_thread, int index, int bind_to)
{
pthread_attr_t attr;
out_thread->index = index;
out_thread->tcp2http = h;
int ret;
out_thread->efd = epoll_create1(0);
if (out_thread->efd == -1)
{
fprintf(stderr, "epoll_create1 error:%s\n", strerror(errno));
return -1;
}
out_thread->events = (struct epoll_event *)malloc(MAX_EVENTS * sizeof(struct epoll_event));
if (out_thread->events == NULL)
{
fprintf(stderr, "malloc FAILED! %d\n", (int)(MAX_EVENTS * sizeof(struct epoll_event)));
close(out_thread->efd);
return -1;
}
ret = pthread_mutex_init(&out_thread->mutex, NULL);
if (ret != 0)
{
fprintf(stderr, "pthread_mutex_init FAILED! %s\n", strerror(errno));
free(out_thread->events);
close(out_thread->efd);
return -1;
}
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if (pthread_create(&out_thread->thrd_out, &attr, output_proc, out_thread) != 0)
{
fprintf(stderr, "pthread_create FAILED! %s\n", strerror(errno));
free(out_thread->events);
close(out_thread->efd);
pthread_mutex_destroy(&out_thread->mutex);
return -1;
}
fprintf(stderr, "thread out %d: %d, out_ptr:%p, efd:%d\n", index, (int)out_thread->thrd_out, out_thread, out_thread->efd);
if (bind_to >= 0)
{
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(bind_to, &mask);
ret = pthread_setaffinity_np(out_thread->thrd_out, sizeof(mask), &mask);
if (ret == 0)
fprintf(stderr, "bind output thread %d to cpu %d OK!\n", (int)out_thread->thrd_out, bind_to);
else
fprintf(stderr, "bind output thread %d to cpu %d FAILED!\n", (int)out_thread->thrd_out, bind_to);
}
return 0;
}
static void tcp2http_destroy(tcp2http_t *h)
{
client_in_t *c;
if (h->sfd_in != 0)
close(h->sfd_in);
if (h->sfd_out != 0)
close(h->sfd_out);
for (; ;)
{
c = h->inputs;
if (c == NULL)
break;
clean_client_in(h, c, 0);
destroy_client_in(h, c);
}
while (h->inputs_inactive != NULL)
{
c = h->inputs_inactive;
remove_node(h->inputs_inactive, c, client_in_t);
destroy_client_in(h, c);
}
if (h->map != NULL)
map_destroy(h->map);
if (h->efd != 0)
close(h->efd);
if (h->events != NULL)
free(h->events);
free(h);
}
static int tcp2http_create(tcp2http_t *h)
{
struct epoll_event event;
int ret;
int i;
//除了参数size被忽略外, 此函数和epoll_create完全相同
h->efd = epoll_create1(0);
if (h->efd == -1)
{
fprintf(stderr, "epoll_create1 error:%s\n", strerror(errno));
goto FAIL;
}
h->events = (struct epoll_event *)malloc(MAX_EVENTS * sizeof(event));
if (h->events == NULL)
{
fprintf(stderr, "malloc FAILED! %d\n", (int)(MAX_EVENTS * sizeof(event)));
goto FAIL;
}
h->map = map_create(h->max_fd);
if (h->map == NULL)
{
fprintf(stderr, "map_create FAILED! max_fd:%d\n", h->max_fd);
goto FAIL;
}
h->sfd_in = serve_socket(h->input_port);
if (h->sfd_in == -1)
goto FAIL;
ret = set_socket_nonblocking(h->sfd_in);
if (ret == -1)
goto FAIL;
ret = listen(h->sfd_in, SOMAXCONN);
if (ret == -1)
{
fprintf(stderr, "listen error:%s\n", strerror(errno));
goto FAIL;
}
memset(&event, 0, sizeof(event));
event.data.fd = h->sfd_in;
event.events = EPOLLIN | EPOLLET; //读入, 边缘触发
ret = epoll_ctl(h->efd, EPOLL_CTL_ADD, h->sfd_in, &event);
if (ret == -1)
{
fprintf(stderr, "epoll_ctl sfd_in error: %s\n", strerror(errno));
goto FAIL;
}
h->sfd_out = serve_socket(h->output_port);
if (h->sfd_out == -1)
goto FAIL;
ret = set_socket_nonblocking(h->sfd_out);
if (ret == -1)
goto FAIL;
ret = listen(h->sfd_out, SOMAXCONN);
if (ret == -1)
{
fprintf(stderr, "listen error:%s\n", strerror(errno));
goto FAIL;
}
memset(&event, 0, sizeof(event));
event.data.fd = h->sfd_out;
event.events = EPOLLIN | EPOLLET; //读入, 边缘触发
ret = epoll_ctl(h->efd, EPOLL_CTL_ADD, h->sfd_out, &event);
if (ret == -1)
{
fprintf(stderr, "epoll_ctl sfd_out error: %s\n", strerror(errno));
goto FAIL;
}
for (i = 0; i < h->out_threads_count; i++)
{
ret = output_thread_create(h, &h->out_threads[i], i, h->out_threads_bind[i]);
if (ret != 0)
{
int sum;
fprintf(stderr, "output_thread_create %d FAILED!\n", i);
h->out_threads_count = i;
for (i = 0; i < h->out_threads_count; i++)
h->out_threads[i].exit_flag = 1;
for (; ;)
{
sum = 0;
for (i = 0; i < h->out_threads_count; i++)
sum += h->out_threads[i].exit_flag;
if (sum == h->out_threads_count * 2)
break;
usleep(100000);
}
fprintf(stderr, "all output thread exited\n");
for (i = 0; i < h->out_threads_count; i++)
{
pthread_mutex_destroy(&h->out_threads[i].mutex);
free(h->out_threads[i].events);
}
goto FAIL;
}
}
return 0;
FAIL:
tcp2http_destroy(h);
return -1;
}
static void* read_frame_proc(void *arg)
{
client_in_t *client = (client_in_t *)arg;
AVBufferRef *buf;
int pkt_size;
int pos;
for (; ;)
{
if (client->exit_flag == 1)
{
fprintf(stderr, "%d| read_frame_proc receive found exit flag\n", client->fd);
client->exit_flag = 2;
return NULL;
}
if (client->opened < 2)
{
usleep(10000);
continue;
}
if (av_read_frame(client->fmt_ctx, &client->pkt) != 0)
{
fprintf(stderr, "%d| av_read_frame FAILED! should not go here!\n", client->fd);
usleep(10000);
continue;
}
if (client->video_index >= 0 && client->pkt.stream_index != client->video_index)
{
av_free_packet(&client->pkt);
continue;
}
if (client->is_flv)
client->pkt.pos -= 16;
if (client->pkt.pos < 0)
{
//fprintf(stderr, "%d| pkt.pos is %"PRId64"\n", client->fd, client->pkt.pos);
av_free_packet(&client->pkt);
continue;
}
pkt_size = client->pkt.pos - client->input_head_offset;
//跳过第一个GOP, 避免重复发送flv_header导致ffplay出现"Stream discovered after head already parsed"
//实测ffmpeg推送的码流没问题, 其他情况不确定.
if (client->flv_skip_header <= 1)
{
if (client->flv_skip_header == 0)
client->flv_skip_header += 1;
else if (client->pkt.flags & AV_PKT_FLAG_KEY)
{
client->key_count += 1;
client->last_is_key = 1;
client->flv_skip_header += 1;
}
client->head += pkt_size;
client->input_head_offset += pkt_size;
av_free_packet(&client->pkt);
continue;
}
pos = client->gop_tail % MAX_GOP;
buf = av_buffer_alloc(pkt_size + 1);
if (buf == NULL)
{
fprintf(stderr, "%d| av_buffer_alloc FAILED! size:%d\n", client->fd, pkt_size + 1);
av_free_packet(&client->pkt);
continue;
}
if (client->head <= client->write_pos)
{
memcpy(buf->data + 1, client->queue_buf_input + client->head, pkt_size);
client->head += pkt_size;
client->input_head_offset += pkt_size;
}
else
{
if (QUEUE_INPUT_SIZE - client->head >= pkt_size)
{
memcpy(buf->data + 1, client->queue_buf_input + client->head, pkt_size);
client->head += pkt_size;
if (client->head == QUEUE_INPUT_SIZE)
client->head = 0;
client->input_head_offset += pkt_size;
}
else
{
int part = QUEUE_INPUT_SIZE - client->head;
memcpy(buf->data + 1, client->queue_buf_input + client->head, part);
memcpy(buf->data + part + 1, client->queue_buf_input, pkt_size - part);
client->input_head_offset += pkt_size;
client->head = pkt_size - part;
}
}
//ATTENTION: gop的frame直到位置需要被空出来前才会被释放
if (client->gop[pos] != NULL)
av_buffer_unref((AVBufferRef **)&client->gop[pos]);
client->gop[pos] = buf;
if (client->video_index < 0) //audio only
{
if (client->gop_tail - client->gop_head > client->keep_frames)
client->gop_head += 1;
client->gop_tail += 1;
av_free_packet(&client->pkt);
continue;
}
buf->data[0] = 0;
if (client->last_is_key == 1)
buf->data[0] = 1;
if (client->key_count > 1 && client->gop_tail - client->gop_head > client->keep_frames)
{
int64_t i;
#ifdef DEBUG
fprintf(stderr, "%d| key_count:%d, head:%"PRId64", tail:%"PRId64", keep:%d\n", client->fd,
client->key_count, client->gop_head, client->gop_tail, client->keep_frames);
#endif
for (i = client->gop_head + 1; i < client->gop_tail; i++)
{
AVBufferRef *buf = client->gop[i % MAX_GOP];
if (buf->data[0] == 1)
{
client->key_count -= 1;
client->gop_head = i;
#ifdef DEBUG
fprintf(stderr, "%d|%d| key_count:%d, set head to:%"PRId64", frames:%"PRId64"\n",
get_tick_ms(), client->fd, client->key_count, client->gop_head,
client->gop_tail - client->gop_head);
#endif
}
//ATTENTION keep_frames * 3 / 4为了避免频繁检查重置gop_head
//实际保留帧数为(keep_frames * 3 / 4, keep_frames * 3 / 4 + GOP_SIZE)
if (client->gop_tail - i <= client->keep_frames * 3 / 4)
break;
}
}
if (client->dump_fp != NULL)
fwrite(buf->data + 1, buf->size - 1, 1, client->dump_fp);
if (client->pkt.flags & AV_PKT_FLAG_KEY)
{
#ifdef DEBUG
fprintf(stderr, "%d| got key frame, tail:%"PRId64", write to:%d, key_count:%d\n",
client->fd, client->gop_tail, (pos + 1) % MAX_GOP, client->key_count);
#endif
client->key_count += 1;
client->last_is_key = 1;
}
else
{