-
Notifications
You must be signed in to change notification settings - Fork 17
/
RtmpH264.cpp
640 lines (530 loc) · 15.1 KB
/
RtmpH264.cpp
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
// RtmpH264.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include "RtmpH264.h"
#include "objbase.h"
char* audioConfig = NULL;
long audioConfigLen = 0;
void stream_stop(RTMPMOD_SPublishObj* psObj);
x264_t * h = NULL;//对象句柄,
x264_picture_t m_picInput;//传入图像YUV
x264_picture_t m_picOutput;//输出图像RAW
x264_param_t param;//参数设置
unsigned int nSendCount = 0;
x264_nal_t* nal_t = NULL;
int i_nal = 0;
unsigned char *pps = 0;
int pps_len;
unsigned char * sps = 0;
int sps_len;
RtmpH264* pRtmpH264 = NULL;
// Class constructor
RtmpH264::RtmpH264() : m_isCreatePublish(false),m_SwsContext(NULL)
{
rtmp_PublishObj.hEncoder = 0;
rtmp_PublishObj.nSampleRate = 0;
rtmp_PublishObj.nChannels = 0;
rtmp_PublishObj.nTimeDelta = 0;
rtmp_PublishObj.szPcmAudio = 0;
rtmp_PublishObj.nPcmAudioSize = 0;
rtmp_PublishObj.nPcmAudioLen = 0;
rtmp_PublishObj.szAacAudio = 0;
rtmp_PublishObj.nAacAudioSize = 0;
}
//创建推送连接
int RtmpH264::CreatePublish(char* url, int outChunkSize, int isOpenPrintLog, int logType)
{
int rResult = 0;
rResult = RTMP264_Connect(url, &rtmp_PublishObj.rtmp, isOpenPrintLog, logType);
if (rResult == 1)
{
m_isCreatePublish = true;
m_startTime = ::GetTickCount();
//修改发送分包的大小 默认128字节
RTMPPacket pack;
RTMPPacket_Alloc(&pack, 4);
pack.m_packetType = RTMP_PACKET_TYPE_CHUNK_SIZE;
pack.m_nChannel = 0x02;
pack.m_headerType = RTMP_PACKET_SIZE_LARGE;
pack.m_nTimeStamp = 0;
pack.m_nInfoField2 = 0;
pack.m_nBodySize = 4;
pack.m_body[3] = outChunkSize & 0xff; //大字节序
pack.m_body[2] = outChunkSize >> 8;
pack.m_body[1] = outChunkSize >> 16;
pack.m_body[0] = outChunkSize >> 24;
rtmp_PublishObj.rtmp->m_outChunkSize = outChunkSize;
RTMP_SendPacket(rtmp_PublishObj.rtmp,&pack,1);
RTMPPacket_Free(&pack);
}
return rResult;
}
//断开推送连接
void RtmpH264::DeletePublish()
{
rtmp_PublishObj.hEncoder = 0;
rtmp_PublishObj.nSampleRate = 0;
rtmp_PublishObj.nChannels = 0;
rtmp_PublishObj.nTimeDelta = 0;
rtmp_PublishObj.szPcmAudio = 0;
rtmp_PublishObj.nPcmAudioSize = 0;
rtmp_PublishObj.nPcmAudioLen = 0;
rtmp_PublishObj.szAacAudio = 0;
rtmp_PublishObj.nAacAudioSize = 0;
if (m_isCreatePublish)
{
RTMP264_Close();
}
m_isCreatePublish = false;
}
/*初始化视频编码器
<param name = "width">视频宽度< / param>
*<param name = "height">视频高度< / param>
*<param name = "fps">帧率< / param>
*<param name = "bitrate">比特率< / param>
*<param name = "bConstantsBitrate"> 是否恒定码率 < / param>
*/
int RtmpH264::InitVideoParams(unsigned long width, unsigned long height, unsigned long fps, unsigned long bitrate, bool bConstantsBitrate = false)
{
m_width = width;//宽,根据实际情况改
m_height = height;//高
m_frameRate = fps;
m_bitRate = bitrate;
x264_param_default(¶m);//设置默认参数具体见common/common.c
//* 使用默认参数,在这里因为是实时网络传输,所以使用了zerolatency的选项,使用这个选项之后就不会有delayed_frames,如果使用的不是这样的话,还需要在编码完成之后得到缓存的编码帧
x264_param_default_preset(¶m, "veryfast", "zerolatency");
//* cpuFlags
param.i_threads = X264_SYNC_LOOKAHEAD_AUTO; /* 取空缓冲区继续使用不死锁的保证 */
param.i_sync_lookahead = X264_SYNC_LOOKAHEAD_AUTO;
//* 视频选项
param.i_width = m_width;
param.i_height = m_height;
param.i_frame_total = 0; //* 编码总帧数.不知道用0.
param.i_keyint_min = 0;//关键帧最小间隔
param.i_keyint_max = (int)fps*2;//关键帧最大间隔
param.b_annexb = 1;//1前面为0x00000001,0为nal长度
param.b_repeat_headers = 0;//关键帧前面是否放sps跟pps帧,0 否 1,放
param.i_csp = X264_CSP_I420;
//* B帧参数
param.i_bframe = 0; //B帧
param.b_open_gop = 0;
param.i_bframe_pyramid = 0;
param.i_bframe_adaptive = X264_B_ADAPT_FAST;
//* 速率控制参数
param.rc.i_lookahead = 0;
param.rc.i_bitrate = (int)m_bitRate; //* 码率(比特率,单位Kbps)
if(!bConstantsBitrate)
{
param.rc.i_rc_method = X264_RC_ABR;//参数i_rc_method表示码率控制,CQP(恒定质量),CRF(恒定码率),ABR(平均码率)
param.rc.i_vbv_max_bitrate = (int)m_bitRate*1; // 平均码率模式下,最大瞬时码率,默认0(与-B设置相同)
}
else
{
param.rc.b_filler = 1;
param.rc.i_rc_method = X264_RC_ABR;//参数i_rc_method表示码率控制,CQP(恒定质量),CRF(恒定码率),ABR(平均码率)
param.rc.i_vbv_max_bitrate = m_bitRate; // 平均码率模式下,最大瞬时码率,默认0(与-B设置相同)
param.rc.i_vbv_buffer_size = m_bitRate; //vbv-bufsize
}
//* muxing parameters
param.i_fps_den = 1; // 帧率分母
param.i_fps_num = fps;// 帧率分子
param.i_timebase_num = 1;
param.i_timebase_den = 1000;
h = x264_encoder_open(¶m);//根据参数初始化X264级别
x264_picture_init(&m_picOutput);//初始化图片信息
x264_picture_alloc(&m_picInput, X264_CSP_I420, m_width, m_height);//图片按I420格式分配空间,最后要x264_picture_clean
m_picInput.i_pts = 0;
i_nal = 0;
x264_encoder_headers(h, &nal_t, &i_nal);
if (i_nal > 0)
{
for (int i = 0; i < i_nal; i++)
{
//获取SPS数据,PPS数据
if (nal_t[i].i_type == NAL_SPS)
{
sps = new unsigned char[nal_t[i].i_payload - 4];
sps_len = nal_t[i].i_payload - 4;
memcpy(sps, nal_t[i].p_payload + 4, nal_t[i].i_payload - 4);
}
else if (nal_t[i].i_type == NAL_PPS)
{
pps = new unsigned char[nal_t[i].i_payload - 4];;
pps_len = nal_t[i].i_payload - 4;
memcpy(pps, nal_t[i].p_payload + 4, nal_t[i].i_payload - 4);
}
}
InitSpsPps(pps, pps_len, sps, sps_len, m_width, m_height, m_frameRate);
m_SwsContext= sws_getContext(m_width, m_height, AV_PIX_FMT_BGR24, m_width, m_height, AV_PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL);
return 1;
}
return 0;
}
//释放编码器内存
void RtmpH264::FreeEncodeParams()
{
if (pps)
{
delete[] pps;
pps = NULL;
}
if (sps)
{
delete[] sps;
sps = NULL;
}
if(h)
{
x264_encoder_close(h);
h = NULL;
}
if(m_SwsContext)
{
sws_freeContext(m_SwsContext);
m_SwsContext = NULL;
}
stream_stop(&rtmp_PublishObj);
//DeleteCriticalSection(&m_Cs);
}
/**
* 图片编码发送
*
* @成功则返回 1 , 失败则返回0
*/
int RtmpH264::SendScreenCapture(BYTE * frame, unsigned long Stride, unsigned long StrideHeight, unsigned long timespan)
{
//int nDataLen = Stride * StrideHeight;
/*uint8_t * rgb_buff = new uint8_t[nDataLen];
memcpy(rgb_buff, frame, nDataLen);*/
//下面的位图转完是倒立的
uint8_t *rgb_src[3] = { frame, NULL, NULL };
int rgb_stride[3]={Stride, 0, 0};
sws_scale(m_SwsContext, rgb_src, rgb_stride, 0, m_height, m_picInput.img.plane, m_picInput.img.i_stride);
//delete[] rgb_buff;
i_nal = 0;
x264_encoder_encode(h, &nal_t, &i_nal, &m_picInput, &m_picOutput);
m_picInput.i_pts++;//少这句的话会出现 x264 [warning]: non-strictly-monotonic PTS
int rResult = 0;
for (int i = 0; i < i_nal; i++)
{
int bKeyFrame = 0;
//获取帧数据
if (nal_t[i].i_type == NAL_SLICE || nal_t[i].i_type == NAL_SLICE_IDR)
{
if (nal_t[i].i_type == NAL_SLICE_IDR)
bKeyFrame = 1;
//EnterCriticalSection(&m_Cs);
rResult = SendH264Packet(nal_t[i].p_payload + 4, nal_t[i].i_payload - 4, bKeyFrame, timespan);
//LeaveCriticalSection(&m_Cs);
}
}
return rResult;
}
#define EB_MAX(a,b) (((a) > (b)) ? (a) : (b))
#define EB_MIN(a,b) (((a) < (b)) ? (a) : (b))
#define PCM_BITSIZE 2
//停止音频编码
void stream_stop(RTMPMOD_SPublishObj* psObj)
{
int nRet;
if (psObj->hEncoder)
{
while (1)
{
nRet = faacEncEncode(psObj->hEncoder, 0, 0, (unsigned char*)(psObj->szAacAudio + RTMP_MAX_HEADER_SIZE + 2), psObj->nAacAudioSize - RTMP_MAX_HEADER_SIZE - 2);
if (0 == nRet) break;
}
nRet = faacEncClose(psObj->hEncoder);
}
if (psObj->szPcmAudio)
{
free(psObj->szPcmAudio);
}
if (psObj->szAacAudio)
{
free(psObj->szAacAudio);
}
psObj->hEncoder = 0;
psObj->nSampleRate = 0;
psObj->nChannels = 0;
psObj->nTimeDelta = 0;
psObj->szPcmAudio = 0;
psObj->nPcmAudioSize = 0;
psObj->nPcmAudioLen = 0;
psObj->szAacAudio = 0;
psObj->nAacAudioSize = 0;
}
//初始化音频编码器
bool stream_init(RTMPMOD_SPublishObj* psObj, unsigned long nSampleRate, unsigned long nChannels)
{
faacEncConfigurationPtr pConfiguration;
unsigned long nInputSamples;
unsigned long nMaxOutputBytes;
int nRet;
char* szPcmAudio;
unsigned long nPcmAudioSize;
char* szAacAudio;
unsigned long nAacAudioSize;
unsigned char * buf;
unsigned long len;
// skip
if ((psObj->hEncoder) && (nSampleRate == psObj->nSampleRate) && (nChannels == psObj->nChannels))
{
return true;
}
// close
stream_stop(psObj);
// open FAAC engine
faacEncHandle hEncoder = faacEncOpen(nSampleRate, nChannels, &nInputSamples, &nMaxOutputBytes);
if (hEncoder == NULL)
{
//assert(0);
return false;
}
// set encoding configuration
pConfiguration = faacEncGetCurrentConfiguration(hEncoder);
pConfiguration->aacObjectType = LOW;
pConfiguration->bitRate = 32000;
pConfiguration->mpegVersion = MPEG4;
pConfiguration->allowMidside = 0;
pConfiguration->useTns = 0;
pConfiguration->useLfe = 0;
pConfiguration->bandWidth = 0;
pConfiguration->quantqual = 100;
pConfiguration->outputFormat = 0;
pConfiguration->inputFormat = (PCM_BITSIZE == 2) ? FAAC_INPUT_16BIT : FAAC_INPUT_32BIT;
pConfiguration->shortctl = SHORTCTL_NORMAL;
nRet = faacEncSetConfiguration(hEncoder, pConfiguration);
if (!nRet)
{
//assert(0);
nRet = faacEncClose(hEncoder);
return false;
}
// buffer
nPcmAudioSize = nInputSamples * PCM_BITSIZE * nChannels;
szPcmAudio = (char*)malloc(nPcmAudioSize);
nAacAudioSize = nMaxOutputBytes + RTMP_MAX_HEADER_SIZE + 2;
szAacAudio = (char*)malloc(nAacAudioSize);
if ((!szPcmAudio) || (!szAacAudio))
{
nRet = faacEncClose(hEncoder);
if (szPcmAudio)
{
free(szPcmAudio);
}
if (szAacAudio)
{
free(szAacAudio);
}
//assert(0);
return false;
}
// success
psObj->hEncoder = hEncoder;
psObj->nSampleRate = nSampleRate;
psObj->nChannels = nChannels;
psObj->nTimeDelta = (nInputSamples * 1000 / nSampleRate);
psObj->szPcmAudio = szPcmAudio;
psObj->nPcmAudioSize = nPcmAudioSize;
psObj->nPcmAudioLen = 0;
psObj->szAacAudio = szAacAudio;
psObj->nAacAudioSize = nAacAudioSize;
// send aac header
faacEncGetDecoderSpecificInfo(hEncoder, &buf, &len);
memcpy(psObj->szAacAudio + RTMP_MAX_HEADER_SIZE + 2, buf, len);
len += 2;
psObj->szAacAudio[RTMP_MAX_HEADER_SIZE + 0] = (char)0xAF;
psObj->szAacAudio[RTMP_MAX_HEADER_SIZE + 1] = (char)0x00;
psObj->packet.m_headerType = RTMP_PACKET_SIZE_LARGE;
psObj->packet.m_packetType = RTMP_PACKET_TYPE_AUDIO;
psObj->packet.m_hasAbsTimestamp = 0;
psObj->packet.m_nChannel = 0x04;
psObj->packet.m_nTimeStamp = psObj->nTimeStamp;
psObj->packet.m_nInfoField2 = psObj->rtmp->m_stream_id;
psObj->packet.m_nBodySize = len;
psObj->packet.m_body = psObj->szAacAudio + RTMP_MAX_HEADER_SIZE;
psObj->packet.m_nBytesRead = 0;
// send packet
//assert(psObj->rtmp);
//EnterCriticalSection(&m_Cs);
RTMP_SendPacket(psObj->rtmp, &psObj->packet, true);
//LeaveCriticalSection(&m_Cs);
// success
return true;
}
//编码后发送音频数据
long RTMPMOD_PublishSendAudio(RTMPMOD_SPublishObj* hObj, char* szBuf, unsigned long nBufLen, unsigned long nSampleRate, unsigned long nChannels, unsigned long timespan)
{
RTMPMOD_SPublishObj* psObj = (RTMPMOD_SPublishObj*)hObj;
unsigned long nDone = 0;
unsigned long nCopy;
int nRet;
// check
if ((!psObj) || (!szBuf) || (!nBufLen) || (!nSampleRate) || ((1 != nChannels) && (2 != nChannels)))
{
return 0;
}
// init
if (!psObj->rtmp)
{
return 0;
}
if (!stream_init(psObj, nSampleRate, nChannels))
{
return 0;
}
// encode and send
while (nDone < nBufLen)
{
// copy
nCopy = EB_MIN((nBufLen - nDone), (psObj->nPcmAudioSize - psObj->nPcmAudioLen));
memcpy(psObj->szPcmAudio + psObj->nPcmAudioLen, szBuf + nDone, nCopy);
nDone += nCopy;
psObj->nPcmAudioLen += nCopy;
// ready
if (psObj->nPcmAudioLen == psObj->nPcmAudioSize)
{
// encode
nRet = faacEncEncode(psObj->hEncoder, (int*)psObj->szPcmAudio, (psObj->nPcmAudioSize / PCM_BITSIZE) / psObj->nChannels,
(unsigned char*)(psObj->szAacAudio + RTMP_MAX_HEADER_SIZE + 2), psObj->nAacAudioSize - RTMP_MAX_HEADER_SIZE - 2);
psObj->nPcmAudioLen = 0;
if (nRet <= 0)
{
continue;
}
psObj->nTimeStamp = timespan;
//psObj->nTimeStamp += psObj->nTimeDelta;
// packet
psObj->szAacAudio[RTMP_MAX_HEADER_SIZE + 0] = (char)0xAF;
psObj->szAacAudio[RTMP_MAX_HEADER_SIZE + 1] = (char)0x01;
psObj->packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM;
psObj->packet.m_packetType = RTMP_PACKET_TYPE_AUDIO;
psObj->packet.m_hasAbsTimestamp = 0;
psObj->packet.m_nChannel = 0x04;
psObj->packet.m_nTimeStamp = psObj->nTimeStamp;
psObj->packet.m_nInfoField2 = psObj->rtmp->m_stream_id;
psObj->packet.m_nBodySize = nRet + 2;
psObj->packet.m_body = psObj->szAacAudio + RTMP_MAX_HEADER_SIZE;
psObj->packet.m_nBytesRead = 0;
//EnterCriticalSection(&m_Cs);
// send packet
if (!RTMP_SendPacket(psObj->rtmp, &psObj->packet, true))
{
return 0;
}
//LeaveCriticalSection(&m_Cs);
}
}
// success
return 1;
}
//创建推送流连接
long RTMP_CreatePublish(char* url, unsigned long outChunkSize, int isOpenPrintLog, int logType)
{
int nResult = -1;
if (pRtmpH264)
{
pRtmpH264->FreeEncodeParams();
pRtmpH264->DeletePublish();
delete pRtmpH264;
}
pRtmpH264 = new RtmpH264();
nResult = pRtmpH264->CreatePublish(url, (int)outChunkSize, isOpenPrintLog, logType);
if (nResult != 1)
pRtmpH264->m_isCreatePublish = false;
return nResult;
}
//断开推送流
void RTMP_DeletePublish()
{
if (pRtmpH264)
{
pRtmpH264->FreeEncodeParams();
pRtmpH264->DeletePublish();
delete pRtmpH264;
}
pRtmpH264 = NULL;
}
//初始化编码器
long RTMP_InitVideoParams(unsigned long width, unsigned long height, unsigned long fps, unsigned long bitrate, bool bConstantsBitrate)
{
int nResult = -1;
if (!pRtmpH264)
{
return -1;
}
__try
{
nResult = pRtmpH264->InitVideoParams(width, height, fps, bitrate, bConstantsBitrate);
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
nResult = -1;
pRtmpH264->m_isCreatePublish = false;
RTMP_DeletePublish();
throw(-1);
}
if (nResult != 1)
{
pRtmpH264->m_isCreatePublish = false;
RTMP_DeletePublish();
}
return nResult;
}
//发送截图 对截图进行x264编码
long RTMP_SendScreenCapture(char * frame, unsigned long Stride, unsigned long Height, unsigned long timespan)
{
int nResult = -1;
if (!pRtmpH264)
{
return -1;
}
__try
{
if (!pRtmpH264->m_isCreatePublish)
return -1;
nResult = pRtmpH264->SendScreenCapture((BYTE *)frame, Stride, Height, timespan);
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
nResult = -1;
pRtmpH264->m_isCreatePublish = false;
RTMP_DeletePublish();
throw(-1);
}
if (nResult != 1)
{
pRtmpH264->m_isCreatePublish = false;
RTMP_DeletePublish();
}
return nResult;
}
//发送音频数据 原始数据为PCM
long RTMP_SendAudioFrame(char* szBuf, unsigned long nBufLen, unsigned long nSampleRate, unsigned long nChannels, unsigned long timespan)
{
int nResult = -1;
if (!pRtmpH264)
{
return -1;
}
__try
{
if (!pRtmpH264->m_isCreatePublish)
return -1;
nResult = RTMPMOD_PublishSendAudio(&pRtmpH264->rtmp_PublishObj, szBuf, nBufLen, nSampleRate, nChannels, timespan);
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
nResult = -1;
pRtmpH264->m_isCreatePublish = false;
RTMP_DeletePublish();
throw(-1);
}
if (nResult != 1)
{
pRtmpH264->m_isCreatePublish = false;
RTMP_DeletePublish();
}
return nResult;
}