forked from nscript-site/NScript.AndroidBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMediaStream.cs
More file actions
436 lines (370 loc) · 13.7 KB
/
MediaStream.cs
File metadata and controls
436 lines (370 loc) · 13.7 KB
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
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.IO;
using System.Threading.Tasks;
namespace NScript.AndroidBot
{
using FFmpeg.AutoGen;
public unsafe class MediaStream
{
public Socket VideoSocket { get; private set; }
public Socket AudioSocket { get; private set; }
private List<PacketSink> Sinks { get; set; } = new List<PacketSink>();
public AVCodecContext* codec_ctx;
public AVCodecParserContext* parser;
public AVPacket* pending;
public void* CbsUserData;
public Action<IntPtr> OnCbs { get; set; }
public Action<String> OnMsg { get; set; }
public String Name { get; set; } = String.Empty;
/// <summary>
/// 音频数据的回调函数
/// </summary>
public Action<Byte[]> OnAudioDataReceive { get; set; }
public void Cbs(void* userData)
{
OnCbs?.Invoke((IntPtr)userData);
}
public void AddSink(PacketSink sink)
{
Sinks.Add(sink);
}
#region 二进制操作
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static UInt16 buffer_read16be(Byte* buf)
{
return (UInt16)((buf[0] << 8) | buf[1]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static UInt32 buffer_read32be(Byte* buf)
{
return (UInt32)((buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static UInt64 buffer_read64be(Byte* buf)
{
UInt32 msb = buffer_read32be(buf);
UInt32 lsb = buffer_read32be(&buf[4]);
return ((UInt64)msb << 32) | lsb;
}
#endregion
public bool stream_recv_packet(AVPacket* packet)
{
// The video stream contains raw packets, without time information. When we
// record, we retrieve the timestamps separately, from a "meta" header
// added by the server before each raw packet.
//
// The "meta" header length is 12 bytes:
// [. . . . . . . .|. . . .]. . . . . . . . . . . . . . . ...
// <-------------> <-----> <-----------------------------...
// PTS packet raw packet
// size
//
// It is followed by <packet_size> bytes containing the packet/frame.
const int HEADER_SIZE = 12;
Byte* pHeader = stackalloc byte[HEADER_SIZE];
Span<Byte> header = new Span<byte>(pHeader, HEADER_SIZE);
int r = NetUtils.RecvAll(VideoSocket, header);
if (r < HEADER_SIZE)
{
OnMsg?.Invoke($"[{Name}] packet header RecvAll fail");
return false;
}
UInt64 pts = buffer_read64be(pHeader);
int len = (int)buffer_read32be(&pHeader[8]);
//assert(pts == NO_PTS || (pts & 0x8000000000000000) == 0);
//assert(len);
if (ffmpeg.av_new_packet(packet, len) != 0)
{
OnMsg?.Invoke($"[{Name}] could not allocate packet of {len} bytes");
throw new BotException("Could not allocate packet");
}
Span<Byte> data = new Span<byte>(packet->data, len);
r = NetUtils.RecvAll(VideoSocket, data);
if (r < 0 || r < len)
{
ffmpeg.av_packet_unref(packet);
OnMsg?.Invoke($"[{Name}] packet content of {len} bytes RecvAll fail");
return false;
}
unchecked
{
const UInt64 NO_PTS = (UInt64)(-1);
packet->pts = pts != NO_PTS ? (Int64)pts : ffmpeg.AV_NOPTS_VALUE;
}
return true;
}
public bool push_packet_to_sinks(AVPacket* packet)
{
for (int i = 0; i < this.Sinks.Count; ++i)
{
var sink = Sinks[i];
if (!sink.Push(packet))
{
//LOGE("Could not send config packet to sink %d", i);
return false;
}
}
return true;
}
public bool stream_parse(AVPacket* packet)
{
Byte* in_data = packet->data;
int in_len = packet->size;
Byte* out_data = null;
int out_len = 0;
int r = ffmpeg.av_parser_parse2(parser, codec_ctx,
&out_data, &out_len, in_data, in_len,
ffmpeg.AV_NOPTS_VALUE, ffmpeg.AV_NOPTS_VALUE, -1);
if (parser->key_frame == 1)
{
packet->flags |= ffmpeg.AV_PKT_FLAG_KEY;
}
packet->dts = packet->pts;
//Span<Byte> datas = new Span<byte>(packet->data, packet->size);
//Console.WriteLine(datas.ToString());
bool ok = this.push_packet_to_sinks(packet);
if (!ok)
{
//LOGE("Could not process packet");
return false;
}
return true;
}
public bool stream_push_packet(AVPacket* packet)
{
bool is_config = packet->pts == ffmpeg.AV_NOPTS_VALUE;
// A config packet must not be decoded immediately (it contains no
// frame); instead, it must be concatenated with the future data packet.
if (pending != null || is_config)
{
Int64 offset;
if (pending != null)
{
offset = pending->size;
if (ffmpeg.av_grow_packet(pending, packet->size) != 0)
{
//LOGE("Could not grow packet");
return false;
}
}
else
{
offset = 0;
pending = ffmpeg.av_packet_alloc();
if (pending == null)
{
//LOGE("Could not allocate packet");
return false;
}
if (ffmpeg.av_new_packet(pending, packet->size) != 0)
{
//LOGE("Could not create packet");
FFmpegUtils.av_packet_free(ref pending);
return false;
}
}
// smemcpy(stream->pending->data + offset, packet->data, packet->size);
Span<Byte> source = new Span<byte>(packet->data, packet->size);
Span<Byte> dest = new Span<byte>(pending->data + offset, source.Length);
source.CopyTo(dest);
if (!is_config)
{
// prepare the concat packet to send to the decoder
pending->pts = packet->pts;
pending->dts = packet->dts;
pending->flags = packet->flags;
packet = pending;
}
}
if (is_config)
{
// config packet
bool ok = this.push_packet_to_sinks(packet);
if (!ok)
{
return false;
}
}
else
{
// data packet
bool ok = this.stream_parse(packet);
if (pending != null)
{
// the pending packet must be discarded (consumed or error)
ffmpeg.av_packet_unref(pending);
FFmpegUtils.av_packet_free(ref pending);
}
if (!ok)
{
return false;
}
}
return true;
}
public void CloseSinks()
{
this.CloseSinks(Sinks.Count);
}
public void CloseSinks(int count)
{
count = Math.Max(count, Sinks.Count);
while (count > 0)
{
count--;
var sink = Sinks[count];
sink.Close();
}
}
public bool OpenSinks(AVCodec* codec, AVPixelFormat fmt)
{
for (int i = 0; i < Sinks.Count; i++)
{
var item = Sinks[i];
if (item.Open(codec, fmt) == false)
{
CloseSinks(i);
return false;
//throw new BotException("Could not open packet sink " + i);
}
}
return true;
}
private int RunVideoDecodeBackgroundWork()
{
OnMsg?.Invoke($"[{Name}] start video decoding");
AVCodec* codec = ffmpeg.avcodec_find_decoder(AVCodecID.AV_CODEC_ID_H264);
Exception ex = null;
if (codec == null)
{
ex = new BotException("H.264 decoder not found");
goto end;
}
codec_ctx = ffmpeg.avcodec_alloc_context3(codec);
if (codec_ctx == null)
{
ex = new BotException("Could not allocate codec context");
goto end;
}
if (this.OpenSinks(codec, AVPixelFormat.AV_PIX_FMT_YUV420P) == false)
{
ex = new BotException("Could not open stream sinks");
goto finally_free_codec_ctx;
}
parser = ffmpeg.av_parser_init((int)AVCodecID.AV_CODEC_ID_H264);
if (parser == null)
{
ex = new BotException("Could not initialize parser");
goto finally_close_sinks;
}
// We must only pass complete frames to av_parser_parse2()!
// It's more complicated, but this allows to reduce the latency by 1 frame!
parser->flags |= ffmpeg.PARSER_FLAG_COMPLETE_FRAMES;
AVPacket* packet = ffmpeg.av_packet_alloc();
if (packet == null)
{
OnMsg?.Invoke($"[{Name}] could not allocate packet");
ex = new BotException("Could not allocate packet");
goto finally_close_parser;
}
for (; ; )
{
bool ok = this.stream_recv_packet(packet);
if (!ok)
{
OnMsg?.Invoke($"[{Name}] video stream eof");
break; // eof
}
ok = this.stream_push_packet(packet);
ffmpeg.av_packet_unref(packet);
if (!ok)
{
OnMsg?.Invoke($"[{Name}] cannot process packet");
// cannot process packet (error already logged)
break;
}
}
//LOGD("End of frames");
if (pending != null)
{
ffmpeg.av_packet_unref(pending);
FFmpegUtils.av_packet_free(ref pending);
}
FFmpegUtils.av_packet_free(ref packet);
finally_close_parser:
ffmpeg.av_parser_close(parser);
finally_close_sinks:
this.CloseSinks();
finally_free_codec_ctx:
FFmpegUtils.avcodec_free_context(ref codec_ctx);
end:
Cbs(CbsUserData);
OnMsg?.Invoke($"[{Name}] stop video decoding");
return 0;
}
public Task ReceiveVideoDataTask { get; private set; }
public bool ReceiveVideoSocket(Socket socket) {
if (socket == null) return false;
this.VideoSocket = socket;
ReceiveVideoDataTask = new Task(() =>
{
RunVideoDecodeBackgroundWork();
});
this.ReceiveVideoDataTask.Start();
return true;
}
public Task ReceiveAudioDataTask { get; private set; }
public bool ReceiveAudioSocket(Socket socket, int fps)
{
if (socket == null) return false;
this.AudioSocket = socket;
ReceiveAudioDataTask = new Task(() =>
{
ReceiveAudioDataBackgroundWork(fps);
});
this.ReceiveAudioDataTask.Start();
return true;
}
private void ReceiveAudioDataBackgroundWork(int fps)
{
int HEADER_SIZE = (44100*4)/fps;
Byte[] buff = new byte[HEADER_SIZE];
fixed(Byte* pBuff = buff)
{
Span<Byte> header = new Span<byte>(buff);
Span<Byte4> b4 = new Span<Byte4>(pBuff, buff.Length / 4);
//DirectoryInfo dirTmp = new DirectoryInfo("./tmp");
//if (dirTmp.Exists == false) dirTmp.Create();
while (true)
{
// 录制的是 44100 Hz 单通道 Singed 32-bit PCM
int r = NetUtils.RecvAll(AudioSocket, header);
for (int i = 0; i < b4.Length; i++)
b4[i] = b4[i].Invert(); // 大端转小端
OnAudioDataReceive?.Invoke(buff);
//File.WriteAllBytes(Path.Combine(dirTmp.FullName, DateTime.Now.ToFileTimeUtc()+".pcm"), buff);
}
}
}
public struct Byte4
{
public Byte B1;
public Byte B2;
public Byte B3;
public Byte B4;
public Byte4 Invert()
{
Byte4 b = new Byte4();
b.B1 = this.B4;
b.B2 = this.B3;
b.B3 = this.B2;
b.B4 = this.B1;
return b;
}
}
}
}