-
Notifications
You must be signed in to change notification settings - Fork 26
/
live.c
1578 lines (1442 loc) · 54.2 KB
/
live.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
#include <arpa/inet.h>
#include <sys/stat.h>
#include <errno.h>
#include <libgen.h>
#include <glib.h>
#include <jansson.h>
#include "rtp.h"
#include "live.h"
#include "debug.h"
#include "utils.h"
static int post_reset_trigger = 200;
static void janus_live_event_loop_init(janus_live_pub *pub, janus_live_el **el, int id, char* name);
static void *janus_live_event_loop_thread(void *data);
static gboolean janus_live_send_handle(gpointer user_data);
static gboolean janus_rtp_jb_handle(gpointer user_data);
static int janus_live_ffmpeg_init(janus_live_pub *pub);
static int janus_live_ffmpeg_free(janus_live_pub *pub);
static void janus_rtp_jb_free(janus_live_pub *pub);
static janus_frame_packet *janus_packet_alloc(int data_len);
static void janus_packet_free(janus_frame_packet *pkt);
static void janus_live_pub_free(const janus_refcount *pub_ref);
static int janus_live_rtp_header_extension_parse_audio_level(char *buf,int len, int id, int *level);
static int janus_live_rtp_header_extension_parse_video_orientation(char *buf, int len, int id, int *rotation);
static void janus_live_h264_parse_sps(char *buffer, int *width, int *height);
static void janus_live_rtp_unpack(janus_rtp_jb *jb, janus_frame_packet *packet, gboolean video);
static int janus_live_packet_insert(janus_live_pub *pub, janus_frame_packet *p);
static janus_adecoder_opus *janus_live_opus_decoder_create(uint32_t samplerate, int channels, gboolean fec);
static void janus_live_opus_decoder_destory(janus_adecoder_opus *dc);
static void janus_live_opus_decoder_decode(janus_adecoder_opus *dc, char *buf, int len);
static janus_aencoder_fdkaac *janus_live_fdkaac_encoder_create(int sample_rate, int channels, int bitrate);
static void janus_live_fdkaac_encoder_destory(janus_aencoder_fdkaac *ec);
static void janus_live_fdkaac_encoder_encode(janus_aencoder_fdkaac *ec, char *data, int len, uint32_t pts);
static void janus_live_fdkaac_encoder_encode_inernal(janus_aencoder_fdkaac *ec, char *data, int len, uint32_t pts);
janus_live_pub *
janus_live_pub_create(const char *url, const char *acodec, const char *vcodec)
{
if(url == NULL) {
JANUS_LOG(LOG_ERR, "Missing live url information\n");
return NULL;
}
if(acodec == NULL && vcodec == NULL) {
JANUS_LOG(LOG_ERR, "Audio Video must have one\n");
return NULL;
}
/* Create the live pub */
janus_live_pub *pub = g_malloc0(sizeof(janus_live_pub));
pub->url = g_strdup(url);
JANUS_LOG(LOG_INFO, "rtmp url:%s\n", pub->url);
if(acodec)
pub->acodec = g_strdup(acodec);
if(vcodec)
pub->vcodec = g_strdup(vcodec);
pub->created = janus_get_real_time();
pub->init_flag = FALSE;
pub->closed = FALSE;
if(pub->acodec) {
pub->audio_jb = g_malloc0(sizeof(janus_rtp_jb));
pub->audio_jb->tb = 48000;
pub->audio_jb->pub = pub;
pub->audio_jb->adecoder = janus_live_opus_decoder_create(48000, 2, TRUE);
pub->audio_jb->adecoder->jb = pub->audio_jb;
pub->audio_jb->aencoder = janus_live_fdkaac_encoder_create(48000, 2, 128);
pub->audio_jb->aencoder->jb = pub->audio_jb;
}
if(pub->vcodec) {
pub->video_jb = g_malloc0(sizeof(janus_rtp_jb));
pub->video_jb->tb = 90000;
pub->video_jb->pub = pub;
pub->video_jb->buflen = JANUS_LIVE_BUFFER_MAX;
pub->video_jb->received_frame = g_malloc0(pub->video_jb->buflen);
}
/* thread start */
int id;
char tname[32];
GError *error = NULL;
id = 1;
memset(tname, 0, 32);
g_snprintf(tname, sizeof(tname), "jitter event loop, id:%d", id);
janus_live_event_loop_init(pub, &pub->jb_loop, id, tname);
if(pub->jb_loop){
pub->jb_src = g_timeout_source_new(50);
g_source_set_priority(pub->jb_src, G_PRIORITY_DEFAULT);
g_source_set_callback(pub->jb_src, janus_rtp_jb_handle, pub, NULL);
g_source_attach(pub->jb_src, pub->jb_loop->mainctx);
}
id = 2;
memset(tname, 0, 32);
g_snprintf(tname, sizeof(tname), "rtmp send event loop, id:%d", id);
janus_live_event_loop_init(pub, &pub->pub_loop, id, tname);
if(pub->pub_loop){
pub->pub_src = g_timeout_source_new(50);
g_source_set_priority(pub->pub_src, G_PRIORITY_DEFAULT);
g_source_set_callback(pub->pub_src, janus_live_send_handle, pub, NULL);
g_source_attach(pub->pub_src, pub->pub_loop->mainctx);
}
janus_mutex_init(&pub->mutex);
janus_mutex_init(&pub->mutex_live);
/* Done */
g_atomic_int_set(&pub->destroyed, 0);
janus_refcount_init(&pub->ref, janus_live_pub_free);
return pub;
}
void
janus_live_event_loop_init(janus_live_pub *pub, janus_live_el **el, int id, char* name)
{
GError *error = NULL;
janus_live_el *loop = NULL;
loop = g_malloc0(sizeof(janus_live_el));
loop->id = id;
loop->mainctx = g_main_context_new();
loop->mainloop = g_main_loop_new(loop->mainctx, FALSE);
loop->name = g_strdup(name);
loop->pub = pub;
loop->thread = g_thread_try_new(loop->name,
&janus_live_event_loop_thread,loop, &error);
if(error != NULL) {
g_free(loop->name);
loop->name = NULL;
loop->pub = NULL;
g_main_loop_unref(loop->mainloop);
g_main_context_unref(loop->mainctx);
g_free(loop);
JANUS_LOG(LOG_ERR, "Got error %d (%s) trying to launch a new event loop thread,id:%d,name:%s\n",
error->code, error->message ? error->message : "??", id, name);
*el = NULL;
return;
}
*el = loop;
return;
}
int
janus_live_pub_save_frame(janus_live_pub *pub, char *buffer, uint length, gboolean video, int slot)
{
if(!pub)
return -1;
if(!buffer || length < 1) {
return -2;
}
if(!pub->url) {
return -3;
}
janus_rtp_jb *jb = video ? pub->video_jb : pub->audio_jb;
if(!jb){
return -4;
}
/* Write frame header */
uint64_t max32 = UINT32_MAX;
int skip = 0;
int audiolevel = 0, rotation = 0, last_rotation = -1, rotated = -1;
janus_rtp_header *rtp = (janus_rtp_header *)buffer;
JANUS_LOG(LOG_INFO, "%s RTP packet, ssrc:%u, type:%d, sequence:%d, timestamp:%u, ext:%d\n",
video ? "Video" : "Audio", ntohl(rtp->ssrc), rtp->type, ntohs(rtp->seq_number), ntohl(rtp->timestamp)*1000/jb->tb, rtp->extension);
if(rtp->csrccount) {
JANUS_LOG(LOG_VERB, " -- -- Skipping CSRC list\n");
skip += rtp->csrccount*4;
}
audiolevel = -1;
rotation = -1;
if(rtp->extension) {
janus_rtp_header_extension *ext = (janus_rtp_header_extension *)(buffer+12+skip);
JANUS_LOG(LOG_VERB, " -- -- RTP extension (type=0x%"PRIX16", length=%"SCNu16")\n",
ntohs(ext->type), ntohs(ext->length));
skip += 4 + ntohs(ext->length)*4;
if(pub->audio_level_extmap_id > 0)
janus_live_rtp_header_extension_parse_audio_level(buffer, length, pub->audio_level_extmap_id, &audiolevel);
if(pub->video_orient_extmap_id > 0) {
janus_live_rtp_header_extension_parse_video_orientation(buffer, length, pub->video_orient_extmap_id, &rotation);
if(rotation != -1 && rotation != last_rotation) {
last_rotation = rotation;
rotated++;
}
}
}
if(jb->ssrc == 0) {
jb->ssrc = ntohl(rtp->ssrc);
JANUS_LOG(LOG_INFO, "SSRC detected: %"SCNu32"\n", jb->ssrc);
}
if(jb->ssrc != ntohl(rtp->ssrc)) {
JANUS_LOG(LOG_WARN, "Dropping packet with unexpected SSRC: %"SCNu32" != %"SCNu32"\n",
ntohl(rtp->ssrc), jb->ssrc);
return -5;
}
/* Generate frame packet and insert in the ordered list */
janus_frame_packet *p = janus_packet_alloc(length);
p->created = janus_get_real_time();
memcpy(p->data, buffer, length);
p->video = video;
p->ssrc = ntohl(rtp->ssrc);
p->seq = ntohs(rtp->seq_number);
p->pt = rtp->type;
//p->len = length;
p->drop = 0;
/* Due to resets, we need to mess a bit with the original timestamps */
if(jb->last_ts == 0 && jb->start_ts == 0 && jb->start_sys == 0) {
/* Simple enough... */
p->ts = ntohl(rtp->timestamp);
jb->start_ts = ntohl(rtp->timestamp);
jb->start_sys = janus_get_real_time();
} else {
/* Is the new timestamp smaller than the next one, and if so, is it a timestamp reset or simply out of order? */
gboolean late_pkt = FALSE;
if(ntohl(rtp->timestamp) < jb->last_ts && (jb->last_ts-ntohl(rtp->timestamp) > 2*1000*1000*1000)) {
if(jb->post_reset_pkts > post_reset_trigger) {
jb->reset = ntohl(rtp->timestamp);
JANUS_LOG(LOG_WARN, "Timestamp reset: %"SCNu32"\n", jb->reset);
jb->times_resetted++;
jb->post_reset_pkts = 0;
}
} else if(ntohl(rtp->timestamp) > jb->reset && ntohl(rtp->timestamp) > jb->last_ts &&
(ntohl(rtp->timestamp)-jb->last_ts > 2*1000*1000*1000)) {
if(jb->post_reset_pkts < post_reset_trigger) {
JANUS_LOG(LOG_WARN, "Late pre-reset packet after a timestamp reset: %"SCNu32"\n", ntohl(rtp->timestamp));
late_pkt = TRUE;
jb->times_resetted--;
}
} else if(ntohl(rtp->timestamp) < jb->reset) {
if(jb->post_reset_pkts < post_reset_trigger) {
JANUS_LOG(LOG_WARN, "Updating latest timestamp reset: %"SCNu32" (was %"SCNu32")\n", ntohl(rtp->timestamp), jb->reset);
jb->reset = ntohl(rtp->timestamp);
} else {
jb->reset = ntohl(rtp->timestamp);
JANUS_LOG(LOG_WARN, "Timestamp reset: %"SCNu32"\n", jb->reset);
jb->times_resetted++;
jb->post_reset_pkts = 0;
}
}
/* Take into account the number of resets when setting the internal, 64-bit, timestamp */
p->ts = (jb->times_resetted*max32)+ntohl(rtp->timestamp);
if(late_pkt)
jb->times_resetted++;
}
if(rtp->padding) {
/* There's padding data, let's check the last byte to see how much data we should skip */
uint8_t padlen = (uint8_t)buffer[length - 1];
JANUS_LOG(LOG_VERB, "Padding at sequence number %hu: %d/%d\n",
ntohs(rtp->seq_number), padlen, length);
p->len -= padlen;
if((p->len - skip - 12) <= 0) {
/* Only padding, take note that we should drop the packet later */
p->drop = 1;
JANUS_LOG(LOG_VERB, " -- All padding, marking packet as dropped\n");
}
}
if(p->len <= 12) {
/* Only header? take note that we should drop the packet later */
p->drop = 1;
JANUS_LOG(LOG_VERB, " -- Only RTP header, marking packet as dropped\n");
}
jb->last_ts = ntohl(rtp->timestamp);
if(ntohs(rtp->seq_number) != jb->last_seq + 1){
JANUS_LOG(LOG_VERB, "input %d sequence unorder, last:%d, curr:%d\n", video ? "Video" : "Audio", jb->last_seq, ntohs(rtp->seq_number));
}
jb->last_seq = ntohs(rtp->seq_number);
jb->post_reset_pkts++;
/* Fill in the rest of the details */
p->skip = skip;
p->audiolevel = audiolevel;
p->rotation = rotation;
p->next = NULL;
p->prev = NULL;
if(video)
JANUS_LOG(LOG_VERB, "janus_live_pub_save_frame video ts: %"SCNu64"\n", p->ts);
janus_mutex_lock_nodebug(&pub->mutex);
if(jb->list == NULL) {
/* First element becomes the list itself (and the last item), at least for now */
jb->list = p;
jb->last = p;
} else if(!p->drop) {
/* Check where we should insert this, starting from the end */
int added = 0;
janus_frame_packet *tmp = jb->last;
while(tmp) {
if(tmp->ts < p->ts) {
/* The new timestamp is greater than the last one we have, append */
added = 1;
if(tmp->next != NULL) {
/* We're inserting */
tmp->next->prev = p;
p->next = tmp->next;
} else {
/* Update the last packet */
jb->last = p;
}
tmp->next = p;
p->prev = tmp;
break;
} else if(tmp->ts == p->ts) {
/* Same timestamp, check the sequence number */
if(tmp->seq < p->seq && (abs(tmp->seq - p->seq) < 10000)) {
/* The new sequence number is greater than the last one we have, append */
added = 1;
if(tmp->next != NULL) {
/* We're inserting */
tmp->next->prev = p;
p->next = tmp->next;
} else {
/* Update the last packet */
jb->last = p;
}
tmp->next = p;
p->prev = tmp;
break;
} else if(tmp->seq > p->seq && (abs(tmp->seq - p->seq) > 10000)) {
/* The new sequence number (resetted) is greater than the last one we have, append */
added = 1;
if(tmp->next != NULL) {
/* We're inserting */
tmp->next->prev = p;
p->next = tmp->next;
} else {
/* Update the last packet */
jb->last = p;
}
tmp->next = p;
p->prev = tmp;
break;
} else if(tmp->seq == p->seq) {
/* Maybe a retransmission? Skip */
JANUS_LOG(LOG_WARN, "Skipping duplicate packet (seq=%"SCNu16")\n", p->seq);
p->drop = 1;
break;
}
}
/* If either the timestamp ot the sequence number we just got is smaller, keep going back */
tmp = tmp->prev;
}
if(p->drop) {
/* We don't need this */
janus_packet_free(p);
} else if(!added) {
/* We reached the start */
p->next = jb->list;
jb->list->prev = p;
jb->list = p;
}
}
/* list size add */
if(!p->drop)
jb->size++;
/* Done */
janus_mutex_unlock_nodebug(&pub->mutex);
return 0;
}
void *
janus_live_event_loop_thread(void *data)
{
janus_live_el *loop = data;
janus_live_pub *pub = (janus_live_pub *)loop->pub;
JANUS_LOG(LOG_VERB, "[loop#%d] Event loop [%s] thread started\n", loop->id, loop->name);
if(loop->mainloop == NULL) {
JANUS_LOG(LOG_ERR, "[loop#%d] Invalid loop...\n", loop->id);
g_thread_unref(g_thread_self());
return NULL;
}
JANUS_LOG(LOG_DBG, "[loop#%d] Looping...\n", loop->id);
g_main_loop_run(loop->mainloop);
/* When the loop quits, we can unref it */
g_main_loop_unref(loop->mainloop);
g_main_context_unref(loop->mainctx);
JANUS_LOG(LOG_VERB, "[loop#%d] Event loop [%s] thread ended!\n", loop->id, loop->name);
return NULL;
}
gboolean
janus_rtp_jb_handle(gpointer user_data)
{
janus_live_pub *pub = (janus_live_pub *)user_data;
gint64 now = janus_get_real_time();
janus_frame_packet *tmp = NULL, *head = NULL;
janus_rtp_jb *jb = NULL;
/*audio */
janus_mutex_lock_nodebug(&pub->mutex);
head = pub->audio_jb->list;
while(head){
jb = pub->audio_jb;
gint64 gap = (now - jb->start_sys) - (1000 * (head->ts - jb->start_ts)*1000/jb->tb);
gint64 timetout = now - head->created;
if(now - head->created > G_USEC_PER_SEC){
tmp = head->next;
if(tmp){
tmp->prev = NULL;
}
head->next = NULL;
pub->audio_jb->size--;
JANUS_LOG(LOG_INFO, "janus_rtp_jb_handle, audio sequence:%d, gap:%"SCNu64", timeout:%"SCNu64"\n", head->seq, gap/1000, timetout/1000);
if(head->seq != pub->audio_jb->last_seq_out + 1){
JANUS_LOG(LOG_WARN, "output %d sequence unorder, last:%d, curr:%d\n", "Audio", pub->audio_jb->last_seq_out, head->seq);
}
pub->audio_jb->last_seq_out = head->seq;
/* opus unpack */
int len = 0;
char *buffer = janus_rtp_payload(head->data, head->len, &len);
JANUS_LOG(LOG_INFO, "audio frame len: %d\n", len);
if(jb->adecoder){
janus_live_opus_decoder_decode(jb->adecoder, head->data, head->len);
}
janus_packet_free(head);
head = tmp;
}else{
break;
}
}
pub->audio_jb->list = head;
janus_mutex_unlock_nodebug(&pub->mutex);
/*video */
janus_mutex_lock_nodebug(&pub->mutex);
head = pub->video_jb->list;
while(head){
jb = pub->video_jb;
gint64 gap = (now - jb->start_sys) - (1000 * (head->ts - jb->start_ts)*1000/jb->tb);
gint64 timetout = now - head->created;
if(now - head->created > G_USEC_PER_SEC){
tmp = head->next;
if(tmp){
tmp->prev = NULL;
}
head->next = NULL;
pub->video_jb->size--;
JANUS_LOG(LOG_INFO, "janus_rtp_jb_handle, video sequence:%d, gap:%"SCNu64", timeout:%"SCNu64"\n", head->seq, gap/1000, timetout/1000);
if(head->seq != pub->video_jb->last_seq_out + 1){
JANUS_LOG(LOG_WARN, "output %d sequence unorder, last:%d, curr:%d\n", "Video", pub->video_jb->last_seq_out, head->seq);
}
pub->video_jb->last_seq_out = head->seq;
/* h264 unpack */
if(!head->drop){
if(pub->video_jb->ts != head->ts && pub->video_jb->frameLen) {
uint8_t type = *(pub->video_jb->received_frame + 3) & 0x1F;
janus_frame_packet *p = janus_packet_alloc(pub->video_jb->frameLen + FF_INPUT_BUFFER_PADDING_SIZE);
p->created = now;
memcpy(p->data, pub->video_jb->received_frame, pub->video_jb->frameLen);
p->video = TRUE;
p->keyFrame = pub->video_jb->keyFrame;
p->ts = pub->video_jb->ts *1000/jb->tb;
JANUS_LOG(LOG_INFO, "video frame len: %d, nalu type:%d, rtpts:%"SCNu64", ts:%"SCNu64"\n",
pub->video_jb->frameLen, type, pub->video_jb->ts, p->ts);
janus_live_packet_insert(pub, p);
pub->video_jb->frameLen = 0;
pub->video_jb->keyFrame = 0;
}
janus_live_rtp_unpack(pub->video_jb, head, TRUE);
pub->video_jb->ts = head->ts;
}
janus_packet_free(head);
head = tmp;
}else{
break;
}
}
pub->video_jb->list = head;
janus_mutex_unlock_nodebug(&pub->mutex);
JANUS_LOG(LOG_INFO, "janus_rtp_jb_handle, ajb:%d, vjb:%d\n", pub->audio_jb->size, pub->video_jb->size);
return G_SOURCE_CONTINUE;
}
int
janus_live_packet_insert(janus_live_pub *pub, janus_frame_packet *p)
{
janus_mutex_lock_nodebug(&pub->mutex_live);
if(pub->start_ts == 0 && pub->start_sys == 0) {
pub->start_ts = p->ts;
pub->start_sys = janus_get_real_time();
}
JANUS_LOG(LOG_INFO, "janus_live_packet_insert, ts:%"SCNu64", len:%d, size:%d\n", p->ts, p->len, pub->size);
if(pub->list == NULL) {
/* First element becomes the list itself (and the last item), at least for now */
pub->list = p;
pub->last = p;
} else if(!p->drop) {
/* Check where we should insert this, starting from the end */
int added = 0;
janus_frame_packet *tmp = pub->last;
while(tmp) {
if(tmp->ts <= p->ts) {
/* The new timestamp is greater than the last one we have, append */
added = 1;
if(tmp->next != NULL) {
/* We're inserting */
tmp->next->prev = p;
p->next = tmp->next;
} else {
/* Update the last packet */
pub->last = p;
}
tmp->next = p;
p->prev = tmp;
break;
}
/* If either the timestamp ot the sequence number we just got is smaller, keep going back */
tmp = tmp->prev;
}
if(!added) {
/* We reached the start */
p->next = pub->list;
pub->list->prev = p;
pub->list = p;
}
}
/* list size add */
pub->size++;
janus_mutex_unlock_nodebug(&pub->mutex_live);
}
void
janus_live_rtp_unpack(janus_rtp_jb *jb, janus_frame_packet *packet, gboolean video)
{
janus_live_pub *pub = jb->pub;
int len = 0;
char *buffer = janus_rtp_payload(packet->data, packet->len, &len);
if(len < 1) {
return;
}
if((buffer[0] & 0x1F) == 7) {
/* SPS, see if we can extract the width/height as well */
int width = 0, height = 0;
janus_live_h264_parse_sps(buffer, &width, &height);
JANUS_LOG(LOG_VERB, "Parsing width/height: %dx%d\n", width, height);
if(width > pub->max_width)
pub->max_width = width;
if(height > pub->max_height)
pub->max_height = height;
} else if((buffer[0] & 0x1F) == 24) {
/* May we find an SPS in this STAP-A? */
JANUS_LOG(LOG_HUGE, "Parsing STAP-A...\n");
char *buf = buffer;
buf++;
int tot = len-1;
uint16_t psize = 0;
while(tot > 0) {
memcpy(&psize, buf, 2);
psize = ntohs(psize);
buf += 2;
tot -= 2;
int nal = *buf & 0x1F;
JANUS_LOG(LOG_HUGE, " -- NALU of size %u: %d\n", psize, nal);
if(nal == 7) {
int width = 0, height = 0;
janus_live_h264_parse_sps(buf, &width, &height);
JANUS_LOG(LOG_VERB, "Parsing width/height: %dx%d\n", width, height);
if(width > pub->max_width)
pub->max_width = width;
if(height > pub->max_height)
pub->max_height = height;
}
buf += psize;
tot -= psize;
}
}
if(!pub->init_flag && pub->max_width && pub->max_height) {
int rc = janus_live_ffmpeg_init(pub);
if(rc == 0)
pub->init_flag = TRUE;
}
/* H.264 depay */
int jump = 0;
uint8_t fragment = *buffer & 0x1F;
uint8_t nal = *(buffer+1) & 0x1F;
uint8_t start_bit = *(buffer+1) & 0x80;
uint8_t end_bit = *(buffer+1) & 0x40;
if(fragment == 28 || fragment == 29)
JANUS_LOG(LOG_HUGE, "%s Fragment=%d, NAL=%d, Start=%d End=%d (len=%d, frameLen=%d)\n",
video ? "video" : "audio", fragment, nal, start_bit, end_bit, len, jb->frameLen);
else
JANUS_LOG(LOG_HUGE, "%s Fragment=%d (len=%d, frameLen=%d)\n", video ? "video" : "audio", fragment, len, jb->frameLen);
if(fragment == 5 ||
((fragment == 28 || fragment == 29) && nal == 5 && start_bit == 128)) {
JANUS_LOG(LOG_VERB, "(seq=%"SCNu16", ts=%"SCNu64") Key frame\n", packet->seq, packet->ts);
jb->keyFrame = 1;
/* Is this the first keyframe we find? */
if(!jb->keyframe_found) {
jb->keyframe_found = TRUE;
JANUS_LOG(LOG_INFO, "First keyframe: %"SCNu64"\n", packet->ts - jb->start_ts);
}
}
/* Frame manipulation */
if((fragment > 0) && (fragment < 24)) { /* Add a start code */
uint8_t *temp = jb->received_frame + jb->frameLen;
memset(temp, 0x00, 1);
memset(temp + 1, 0x00, 1);
memset(temp + 2, 0x01, 1);
jb->frameLen += 3;
} else if(fragment == 24) { /* STAP-A */
/* De-aggregate the NALs and write each of them separately */
buffer++;
int tot = len-1;
uint16_t psize = 0;
while(tot > 0) {
memcpy(&psize, buffer, 2);
psize = ntohs(psize);
buffer += 2;
tot -= 2;
/* Now we have a single NAL */
uint8_t *temp = jb->received_frame + jb->frameLen;
memset(temp, 0x00, 1);
memset(temp + 1, 0x00, 1);
memset(temp + 2, 0x01, 1);
// memset(temp + 3, 0x01, 1);
jb->frameLen += 3;
memcpy(jb->received_frame + jb->frameLen, buffer, psize);
jb->frameLen += psize;
/* Go on */
buffer += psize;
tot -= psize;
}
return;
} else if((fragment == 28) || (fragment == 29)) { /* FIXME true fr FU-A, not FU-B */
uint8_t indicator = *buffer;
uint8_t header = *(buffer+1);
jump = 2;
len -= 2;
if(header & 0x80) {
/* First part of fragmented packet (S bit set) */
uint8_t *temp = jb->received_frame + jb->frameLen;
memset(temp, 0x00, 1);
memset(temp + 1, 0x00, 1);
memset(temp + 2, 0x01, 1);
memset(temp + 3, (indicator & 0xE0) | (header & 0x1F), 1);
jb->frameLen += 4;
} else if (header & 0x40) {
/* Last part of fragmented packet (E bit set) */
}
}
memcpy(jb->received_frame + jb->frameLen, buffer+jump, len);
jb->frameLen += len;
if(len == 0){
JANUS_LOG(LOG_ERR, "nalu is null\n");
}
}
gboolean
janus_live_send_handle(gpointer user_data)
{
janus_live_pub *pub = (janus_live_pub *)user_data;
gint64 now = janus_get_real_time();
janus_frame_packet *tmp = NULL, *head = NULL;
/*audio */
janus_mutex_lock_nodebug(&pub->mutex_live);
head = pub->list;
while(head){
gint64 gap = (now - pub->start_sys) - (1000 * (head->ts - pub->start_ts));
gint64 timetout = now - head->created;
if(now - head->created > G_USEC_PER_SEC) {
tmp = head->next;
if(tmp){
tmp->prev = NULL;
}
head->next = NULL;
pub->size--;
JANUS_LOG(LOG_INFO, "janus_live_send_handle, %s packet len:%d,"
" ts:%"SCNu64", gap:%"SCNu64", timeout:%"SCNu64", list:%d\n",
head->video ? "video":"audio",head->len,head->ts,
gap/1000, timetout/1000, pub->size);
if(head->len > 0) {
if(head->video){
/* Save the frame */
AVPacket *packet = av_packet_alloc();
av_init_packet(packet);
packet->stream_index = 0;
packet->data = head->data;
packet->size = head->len;
if(head->keyFrame)
packet->flags |= AV_PKT_FLAG_KEY;
packet->dts = (uint32_t)head->ts;
packet->pts = (uint32_t)head->ts;
if(pub->fctx) {
int res = av_interleaved_write_frame(pub->fctx, packet);
if(res < 0) {
JANUS_LOG(LOG_ERR, "Error writing video frame to file... (error %d)\n", res);
}
}
av_packet_free(&packet);
JANUS_LOG(LOG_INFO, "rtmp video packet (len:%d) tb:%d pts:%d listsize:%d\n", head->len, pub->vStream->time_base.den, head->ts, pub->size);
}else{
AVPacket *packet = av_packet_alloc();
av_init_packet(packet);
packet->stream_index = 1;
packet->data = head->data;
packet->size = head->len;
packet->dts = (uint32_t)head->ts;
packet->pts = (uint32_t)head->ts;
av_bitstream_filter_filter(pub->aacbsf, pub->aStream->codec, NULL, &packet->data, &packet->size, packet->data, packet->size, 0);
if(pub->fctx) {
int res = av_write_frame(pub->fctx, packet);
if(res < 0) {
JANUS_LOG(LOG_ERR, "Error writing audio frame to file... (error %d)\n", res);
}
}
av_free(packet->data); /* https://blog.csdn.net/bikeytang/article/details/60883987# */
av_packet_free(&packet);
JANUS_LOG(LOG_INFO, "rtmp audio packet (len:%d) tb:%d pts:%d listsize:%d\n", head->len, pub->aStream->time_base.den, head->ts, pub->size);
}
}
janus_packet_free(head);
head = tmp;
}else{
break;
}
}
pub->list = head;
janus_mutex_unlock_nodebug(&pub->mutex_live);
return G_SOURCE_CONTINUE;
}
int
janus_live_ffmpeg_free(janus_live_pub *pub)
{
if(pub->fctx != NULL)
av_write_trailer(pub->fctx);
#ifdef USE_CODECPAR
if(pub->vEncoder != NULL)
avcodec_close(pub->vEncoder);
if(pub->aEncoder != NULL)
avcodec_close(pub->aEncoder);
#else
if(pub->vStream != NULL && pub->vStream->codec != NULL)
avcodec_close(pub->vStream->codec);
#endif
if(pub->fctx != NULL && pub->fctx->streams[0] != NULL) {
#ifndef USE_CODECPAR
av_free(pub->fctx->streams[0]->codec);
#endif
av_free(pub->fctx->streams[0]);
av_free(pub->fctx->streams[1]);
}
if(pub->fctx != NULL) {
avio_close(pub->fctx->pb);
av_free(pub->fctx);
}
if(pub->aacbsf != NULL) {
av_bitstream_filter_close(pub->aacbsf);
pub->aacbsf = NULL;
}
return 0;
}
int
janus_live_ffmpeg_init(janus_live_pub *pub)
{
/* Setup FFmpeg */
av_register_all();
/* Adjust logging to match the postprocessor's */
av_log_set_level(janus_log_level <= LOG_NONE ? AV_LOG_QUIET :
(janus_log_level == LOG_FATAL ? AV_LOG_FATAL :
(janus_log_level == LOG_ERR ? AV_LOG_ERROR :
(janus_log_level == LOG_WARN ? AV_LOG_WARNING :
(janus_log_level == LOG_INFO ? AV_LOG_INFO :
(janus_log_level == LOG_VERB ? AV_LOG_VERBOSE : AV_LOG_DEBUG))))));
pub->aacbsf = av_bitstream_filter_init("aac_adtstoasc");
if(pub->aacbsf == NULL) {
JANUS_LOG(LOG_ERR, "Error allocating aac_adtstoasc\n");
return -1;
}
/* rtmp output */
pub->fctx = avformat_alloc_context();
if(pub->fctx == NULL) {
JANUS_LOG(LOG_ERR, "Error allocating context\n");
return -1;
}
const char* metadata = "bepartfoyou (七曦)";
/* We save the metadata part as a comment (see #1189) */
if(metadata)
av_dict_set(&pub->fctx->metadata, "comment", metadata, 0);
pub->fctx->oformat = av_guess_format("flv", NULL, NULL);
if(pub->fctx->oformat == NULL) {
JANUS_LOG(LOG_ERR, "Error guessing format\n");
return -1;
}
snprintf(pub->fctx->filename, sizeof(pub->fctx->filename), "%s", pub->url);
#ifdef USE_CODECPAR
/*video */
AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_H264);
if(!codec) {
/* Error opening video codec */
JANUS_LOG(LOG_ERR, "Encoder not available\n");
return -1;
}
pub->fctx->video_codec = codec;
pub->fctx->oformat->video_codec = codec->id;
pub->vStream = avformat_new_stream(pub->fctx, codec);
// pub->vStream->id = pub->fctx->nb_streams - 1;
pub->vStream->id = 0;
pub->vEncoder = avcodec_alloc_context3(codec);
pub->vEncoder->width = pub->max_width;
pub->vEncoder->height = pub->max_height;
pub->vEncoder->time_base = (AVRational){ 1, 25 };
pub->vEncoder->pix_fmt = AV_PIX_FMT_YUV420P;
pub->vEncoder->flags |= CODEC_FLAG_GLOBAL_HEADER;
if(avcodec_open2(pub->vEncoder, codec, NULL) < 0) {
/* Error opening video codec */
JANUS_LOG(LOG_ERR, "Encoder error\n");
return -1;
}
avcodec_parameters_from_context(pub->vStream->codecpar, pub->vEncoder);
/*audio */
AVCodec *acodec = avcodec_find_encoder_by_name("libfdk_aac");
if(!acodec) {
/* Error opening video codec */
JANUS_LOG(LOG_ERR, "Encoder not available\n");
return -1;
}
pub->fctx->audio_codec = acodec;
pub->fctx->oformat->audio_codec = acodec->id;
pub->aStream = avformat_new_stream(pub->fctx, acodec);
//pub->vStream->id = pub->fctx->nb_streams-1;
pub->aStream->id = 1;
pub->aEncoder = avcodec_alloc_context3(acodec);
pub->aEncoder->codec_type = AVMEDIA_TYPE_AUDIO;
pub->aEncoder->sample_rate = 48000;
pub->aEncoder->bit_rate = 128 * 1000;
pub->aEncoder->bit_rate_tolerance = 128 * 1000 * 3 / 2;
pub->aEncoder->channels = 2;
pub->aEncoder->channel_layout = AV_CH_LAYOUT_STEREO;
pub->aEncoder->time_base.num = 1;
pub->aEncoder->time_base.den = pub->aEncoder->sample_rate;
pub->aEncoder->sample_fmt = AV_SAMPLE_FMT_S16;
pub->aEncoder->flags |= CODEC_FLAG_GLOBAL_HEADER;
if(avcodec_open2(pub->aEncoder, acodec, NULL) < 0) {
/* Error opening video codec */
JANUS_LOG(LOG_ERR, "Encoder error\n");
return -1;
}
avcodec_parameters_from_context(pub->aStream->codecpar, pub->aEncoder);
#else
pub->vStream = avformat_new_stream(pub->fctx, 0);
if(pub->vStream == NULL) {
JANUS_LOG(LOG_ERR, "Error adding stream\n");
return -1;
}
#if LIBAVCODEC_VER_AT_LEAST(53, 21)
avcodec_get_context_defaults3(pub->vStream->codec, AVMEDIA_TYPE_VIDEO);
#else
avcodec_get_context_defaults2(pub->vStream->codec, AVMEDIA_TYPE_VIDEO);
#endif
#if LIBAVCODEC_VER_AT_LEAST(54, 25)
pub->vStream->codec->codec_id = AV_CODEC_ID_H264;
#else
pub->vStream->codec->codec_id = CODEC_ID_H264;
#endif
pub->vStream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
pub->vStream->codec->time_base = (AVRational){1, 25};
pub->vStream->time_base = (AVRational){1, 90000};
pub->vStream->codec->width = pub->max_width;
pub->vStream->codec->height = pub->max_height;
pub->vStream->codec->pix_fmt = PIX_FMT_YUV420P;
//~ if (fctx->flags & AVFMT_GLOBALHEADER)
pub->vStream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
#endif
if(avio_open(&pub->fctx->pb, pub->fctx->filename, AVIO_FLAG_WRITE) < 0) {
JANUS_LOG(LOG_ERR, "Error opening file for output\n");
return -1;
}
if(avformat_write_header(pub->fctx, NULL) < 0) {
JANUS_LOG(LOG_ERR, "Error writing header\n");
return -1;
}
JANUS_LOG(LOG_ERR, "ffmpeg init success .....\n");
return 0;
}
void
janus_rtp_jb_free(janus_live_pub *pub)
{
janus_mutex_lock_nodebug(&pub->mutex);
janus_frame_packet *tmp = NULL, *head = NULL;
/*audio */
head = pub->audio_jb->list;
while(head){
tmp = head->next;
if(tmp){
tmp->prev = NULL;
}
head->next = NULL;
pub->audio_jb->size--;
janus_packet_free(head);
head = tmp;
}
pub->audio_jb->list = head;
/*video */
head = pub->video_jb->list;
while(head){
tmp = head->next;
if(tmp){
tmp->prev = NULL;
}
head->next = NULL;
pub->video_jb->size--;
janus_packet_free(head);
head = tmp;
}
pub->video_jb->list = head;
if(pub->video_jb->received_frame){
g_free(pub->video_jb->received_frame);
pub->video_jb->received_frame = NULL;
}
janus_mutex_unlock_nodebug(&pub->mutex);
}
janus_frame_packet *
janus_packet_alloc(int data_len)
{
janus_frame_packet *pkt = g_malloc0(sizeof(janus_frame_packet));
memset(pkt, 0, sizeof(janus_frame_packet));
pkt->len = data_len;
pkt->data = g_malloc0(pkt->len);
return pkt;
}
void
janus_packet_free(janus_frame_packet *pkt)
{
if(!pkt)
return;
if(pkt->data){
g_free(pkt->data);
pkt->data = NULL;
}
g_free(pkt);
pkt = NULL;
}
/* Static helper to quickly find the extension data */
static int
janus_live_rtp_header_extension_find(char *buf, int len, int id,
uint8_t *byte, uint32_t *word, char **ref)
{
if(!buf || len < 12)
return -1;
janus_rtp_header *rtp = (janus_rtp_header *)buf;
int hlen = 12;
if(rtp->csrccount) /* Skip CSRC if needed */
hlen += rtp->csrccount*4;
if(rtp->extension) {