-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.cpp
executable file
·1750 lines (1350 loc) · 42.2 KB
/
main.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
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
/*
*
* Copyright (C) 2016 OtherCrashOverride@users.noreply.github.com.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
*/
// Developer notes:
// g++ -g main.cpp -o c2cap -l vpcodec
// ffmpeg -framerate 60 -i test.h264 -vcodec copy test.mp4
// sudo apt install libjpeg-turbo8-dev
// echo 1 | sudo tee /sys/class/graphics/fb0/blank
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <getopt.h>
#include <cstdlib> //atoi
#include <exception>
#include <vector>
#include <cstring>
#include "../c2_vpcodec/include/vpcodec_1_0.h"
#include <linux/videodev2.h> // V4L
#include <sys/mman.h> // mmap
// The headers are not aware C++ exists
extern "C"
{
//#include <amcodec/codec.h>
#include <codec.h>
}
// Codec parameter flags
// size_t is used to make it
// 64bit safe for use on Odroid C2
const size_t EXTERNAL_PTS = 0x01;
const size_t SYNC_OUTSIDE = 0x02;
const size_t USE_IDR_FRAMERATE = 0x04;
const size_t UCODE_IP_ONLY_PARAM = 0x08;
const size_t MAX_REFER_BUF = 0x10;
const size_t ERROR_RECOVERY_MODE_IN = 0x20;
#include <turbojpeg.h>
#include <memory>
#include "Exception.h"
#include "Stopwatch.h"
#include "Timer.h"
#include "Mutex.h"
// Ion video header from drivers\staging\android\uapi\ion.h
#include "ion.h"
#include "meson_ion.h"
#include "ge2d.h"
#include "ge2d_cmd.h"
#include "vfm_grabber.h"
const char* DEFAULT_DEVICE = "/dev/video0";
const char* DEFAULT_OUTPUT = "default.h264";
const int BUFFER_COUNT = 4;
const int DEFAULT_WIDTH = 640;
const int DEFAULT_HEIGHT = 480;
const int DEFAULT_FRAME_RATE = 30;
const int DEFAULT_BITRATE = 1000000 * 5;
const size_t MJpegDhtLength = 0x1A4;
unsigned char MJpegDht[MJpegDhtLength] = {
/* JPEG DHT Segment for YCrCb omitted from MJPG data */
0xFF,0xC4,0x01,0xA2,
0x00,0x00,0x01,0x05,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x01,0x00,0x03,0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,
0x08,0x09,0x0A,0x0B,0x10,0x00,0x02,0x01,0x03,0x03,0x02,0x04,0x03,0x05,0x05,0x04,0x04,0x00,
0x00,0x01,0x7D,0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,
0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xA1,0x08,0x23,0x42,0xB1,0xC1,0x15,0x52,0xD1,0xF0,0x24,
0x33,0x62,0x72,0x82,0x09,0x0A,0x16,0x17,0x18,0x19,0x1A,0x25,0x26,0x27,0x28,0x29,0x2A,0x34,
0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56,
0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7A,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,
0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,
0xBA,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,
0xDA,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,
0xF8,0xF9,0xFA,0x11,0x00,0x02,0x01,0x02,0x04,0x04,0x03,0x04,0x07,0x05,0x04,0x04,0x00,0x01,
0x02,0x77,0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,0xA1,0xB1,0xC1,0x09,0x23,0x33,0x52,0xF0,0x15,0x62,
0x72,0xD1,0x0A,0x16,0x24,0x34,0xE1,0x25,0xF1,0x17,0x18,0x19,0x1A,0x26,0x27,0x28,0x29,0x2A,
0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56,
0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7A,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
0x99,0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,
0xB9,0xBA,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,
0xD9,0xDA,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,
0xF9,0xFA
};
struct BufferMapping
{
void* Start;
size_t Length;
};
struct option longopts[] = {
{ "device", required_argument, NULL, 'd' },
{ "output", required_argument, NULL, 'o' },
{ "width", required_argument, NULL, 'w' },
{ "height", required_argument, NULL, 'h' },
{ "fps", required_argument, NULL, 'f' },
{ "bitrate", required_argument, NULL, 'b' },
{ "pixformat", required_argument, NULL, 'p' },
{ 0, 0, 0, 0 }
};
//class Exception : public std::exception
//{
//public:
// Exception(const char* message)
// : std::exception()
// {
// fprintf(stderr, "%s\n", message);
// }
//
//};
codec_para_t codecContext;
void OpenCodec(int width, int height, int fps)
{
//fps *= 2;
// Initialize the codec
codecContext = { 0 };
codecContext.stream_type = STREAM_TYPE_ES_VIDEO;
codecContext.video_type = VFORMAT_MJPEG;
codecContext.has_video = 1;
codecContext.noblock = 0;
codecContext.am_sysinfo.format = VIDEO_DEC_FORMAT_MJPEG;
codecContext.am_sysinfo.width = width;
codecContext.am_sysinfo.height = height;
codecContext.am_sysinfo.rate = (96000.0 / fps);
codecContext.am_sysinfo.param = (void*)(0); //EXTERNAL_PTS | SYNC_OUTSIDE
int api = codec_init(&codecContext);
if (api != 0)
{
throw Exception("codec_init failed.");
}
}
void WriteCodecData(unsigned char* data, int dataLength)
{
int offset = 0;
while (offset < dataLength)
{
int count = codec_write(&codecContext, data + offset, dataLength - offset);
if (count > 0)
{
offset += count;
}
}
}
//timeval startTime;
//timeval endTime;
//
//void ResetTime()
//{
// gettimeofday(&startTime, NULL);
// endTime = startTime;
//}
//
//float GetTime()
//{
// gettimeofday(&endTime, NULL);
// float seconds = (endTime.tv_sec - startTime.tv_sec);
// float milliseconds = (float(endTime.tv_usec - startTime.tv_usec)) / 1000000.0f;
//
// startTime = endTime;
//
// return seconds + milliseconds;
//}
//float ConvertTimeval(timeval* value)
//{
// if (value == nullptr)
// throw Exception("value is null.");
//
// float seconds = value->tv_sec;
// float milliseconds = ((float)value->tv_usec) / 1000000.0f;
//
// return seconds + milliseconds;
//}
vl_codec_handle_t handle;
int encoderFileDescriptor = -1;
unsigned char* encodeNV12Buffer = nullptr;
char* encodeBitstreamBuffer = nullptr;
size_t encodeBitstreamBufferLength = 0;
Mutex encodeMutex;
unsigned char* mjpegData = nullptr;
size_t mjpegDataLength = 0;
bool needsMJpegDht = true;
double timeStamp = 0;
double frameRate = 0;
void EncodeFrame()
{
encodeMutex.Lock();
// Encode the video frames
vl_frame_type_t type = FRAME_TYPE_AUTO;
char* in = (char*)encodeNV12Buffer;
int in_size = encodeBitstreamBufferLength;
char* out = encodeBitstreamBuffer;
int outCnt = vl_video_encoder_encode(handle, type, in, in_size, &out);
//printf("vl_video_encoder_encode = %d\n", outCnt);
encodeMutex.Unlock();
if (outCnt > 0)
{
ssize_t writeCount = write(encoderFileDescriptor, encodeBitstreamBuffer, outCnt);
if (writeCount < 0)
{
throw Exception("write failed.");
}
}
//unsigned int pts = timeStamp * 96000;
//codec_set_pcrscr(&codecContext, (int)pts);
timeStamp += frameRate;
//fprintf(stderr, "timeStamp=%f\n", timeStamp);
}
void EncodeFrameHardware()
{
encodeMutex.Lock();
// Encode the video frames
vl_frame_type_t type = FRAME_TYPE_AUTO;
char* in = (char*)encodeNV12Buffer;
int in_size = encodeBitstreamBufferLength;
char* out = encodeBitstreamBuffer;
int outCnt = vl_video_encoder_encode(handle, type, in, in_size, &out);
//printf("vl_video_encoder_encode = %d\n", outCnt);
// Hardware
unsigned int pts = timeStamp * 96000;
//if (codec_checkin_pts(&codecContext, pts))
//{
// printf("codec_checkin_pts failed\n");
//}
if (needsMJpegDht)
{
// Find the start of scan (SOS)
unsigned char* sos = mjpegData;
while (sos < mjpegData + mjpegDataLength - 1)
{
if (sos[0] == 0xff && sos[1] == 0xda)
break;
++sos;
}
// Send everthing up to SOS
int headerLength = sos - mjpegData;
WriteCodecData(mjpegData, headerLength);
// Send DHT
WriteCodecData(MJpegDht, MJpegDhtLength);
// Send remaining data
WriteCodecData(sos, mjpegDataLength - headerLength);
//printf("dataLength=%lu, found SOS @ %d\n", dataLength, headerLength);
}
else
{
WriteCodecData(mjpegData, (int)mjpegDataLength);
}
encodeMutex.Unlock();
if (outCnt > 0)
{
ssize_t writeCount = write(encoderFileDescriptor, encodeBitstreamBuffer, outCnt);
if (writeCount < 0)
{
throw Exception("write failed.");
}
}
codec_set_pcrscr(&codecContext, (int)pts);
timeStamp += frameRate;
fprintf(stderr, "timeStamp=%f\n", timeStamp);
}
struct IonBuffer
{
ion_user_handle_t Handle;
int ExportHandle;
size_t Length;
unsigned long PhysicalAddress;
};
IonBuffer IonAllocate(int ion_fd, size_t bufferSize)
{
int io;
IonBuffer result;
// Allocate a buffer
ion_allocation_data allocation_data = { 0 };
allocation_data.len = bufferSize;
allocation_data.heap_id_mask = ION_HEAP_CARVEOUT_MASK;
allocation_data.flags = ION_FLAG_CACHED;
io = ioctl(ion_fd, ION_IOC_ALLOC, &allocation_data);
if (io != 0)
{
throw Exception("ION_IOC_ALLOC failed.");
}
printf("ion handle=%d\n", allocation_data.handle);
// Map/share the buffer
ion_fd_data ionData = { 0 };
ionData.handle = allocation_data.handle;
io = ioctl(ion_fd, ION_IOC_SHARE, &ionData);
if (io != 0)
{
throw Exception("ION_IOC_SHARE failed.");
}
printf("ion map=%d\n", ionData.fd);
// Get the physical address for the buffer
meson_phys_data physData = { 0 };
physData.handle = ionData.fd;
ion_custom_data ionCustomData = { 0 };
ionCustomData.cmd = ION_IOC_MESON_PHYS_ADDR;
ionCustomData.arg = (long unsigned int)&physData;
io = ioctl(ion_fd, ION_IOC_CUSTOM, &ionCustomData);
if (io != 0)
{
//throw Exception("ION_IOC_CUSTOM failed.");
printf("ION_IOC_CUSTOM failed (%d).", io);
}
result.Handle = allocation_data.handle;
result.ExportHandle = ionData.fd;
result.Length = allocation_data.len;
result.PhysicalAddress = physData.phys_addr;
printf("ion phys_addr=%lu\n", result.PhysicalAddress);
//ion_handle_data ionHandleData = { 0 };
//ionHandleData.handle = allocation_data.handle;
//io = ioctl(ion_fd, ION_IOC_FREE, &ionHandleData);
//if (io != 0)
//{
// throw Exception("ION_IOC_FREE failed.");
//}
return result;
}
enum class PictureFormat
{
Unknown = 0,
Yuyv = V4L2_PIX_FMT_YUYV,
MJpeg = V4L2_PIX_FMT_MJPEG
};
void WriteToFile(const char* path, const char* value)
{
int fd = open(path, O_RDWR | O_TRUNC, 0644);
if (fd < 0)
{
printf("WriteToFile open failed: %s = %s\n", path, value);
exit(1);
}
if (write(fd, value, strlen(value)) < 0)
{
printf("WriteToFile write failed: %s = %s\n", path, value);
exit(1);
}
close(fd);
}
void SetVfmState()
{
WriteToFile("/sys/class/vfm/map", "rm default");
//WriteToFile("/sys/class/vfm/map", "add default decoder ionvideo");
WriteToFile("/sys/class/vfm/map", "add default decoder vfm_grabber");
}
void ResetVfmState()
{
WriteToFile("/sys/class/vfm/map", "rm default");
WriteToFile("/sys/class/vfm/map", "add default decoder ppmgr deinterlace amvideo");
}
struct IonInfo
{
int IonFD;
int IonVideoFD;
size_t BufferSize;
unsigned long PhysicalAddress;
int VideoBufferDmaBufferFD[BUFFER_COUNT];
};
IonInfo OpenIonVideoCapture(int width, int height)
{
const int VIDEO_WIDTH = width;
const int VIDEO_HEIGHT = height;
const unsigned int VIDEO_FORMAT = V4L2_PIX_FMT_NV12;
const int VIDEO_FRAME_SIZE = VIDEO_WIDTH * VIDEO_HEIGHT;
//const int BUFFER_COUNT = 2;
IonInfo info = { 0 };
info.IonVideoFD = open("/dev/video13", O_RDWR | O_NONBLOCK); //| O_NONBLOCK
if (info.IonVideoFD < 0)
{
throw Exception("open ionvideo failed.");
}
//printf("ionvideo file handle: %x\n", info.IonVideoFD);
info.IonFD = open("/dev/ion", O_RDWR);
if (info.IonFD < 0)
{
throw Exception("open ion failed.");
}
//printf("ion file handle: %x\n", info.IonFD);
// Set the capture format
v4l2_format format = { 0 };
format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
format.fmt.pix_mp.width = VIDEO_WIDTH;
format.fmt.pix_mp.height = VIDEO_HEIGHT;
format.fmt.pix_mp.pixelformat = VIDEO_FORMAT;
int v4lcall = ioctl(info.IonVideoFD, VIDIOC_S_FMT, &format);
if (v4lcall < 0)
{
throw Exception("ionvideo VIDIOC_S_FMT failed.");
}
// Request buffers
v4l2_requestbuffers requestBuffers = { 0 };
requestBuffers.count = BUFFER_COUNT;
requestBuffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
requestBuffers.memory = V4L2_MEMORY_DMABUF;
v4lcall = ioctl(info.IonVideoFD, VIDIOC_REQBUFS, &requestBuffers);
if (v4lcall < 0)
{
throw Exception("ionvideo VIDIOC_REQBUFS failed.");
}
// Allocate buffers
int videoFrameLength = 0;
switch (format.fmt.pix_mp.pixelformat)
{
case V4L2_PIX_FMT_RGB32:
videoFrameLength = VIDEO_FRAME_SIZE * 4;
break;
case V4L2_PIX_FMT_NV12:
videoFrameLength = VIDEO_FRAME_SIZE * 2;
break;
default:
throw Exception("Unsupported video formated.");
}
info.BufferSize = videoFrameLength;
for (int i = 0; i < BUFFER_COUNT; ++i)
{
// Allocate a buffer
ion_allocation_data allocation_data = { 0 };
allocation_data.len = videoFrameLength;
allocation_data.heap_id_mask = ION_HEAP_CARVEOUT_MASK;
allocation_data.flags = ION_FLAG_CACHED;
int ionCall = ioctl(info.IonFD, ION_IOC_ALLOC, &allocation_data);
if (ionCall != 0)
{
throw Exception("failed to allocate ion buffer.");
}
// Export the dma_buf
ion_fd_data fd_data = { 0 };
fd_data.handle = allocation_data.handle;
ionCall = ioctl(info.IonFD, ION_IOC_SHARE, &fd_data);
if (ionCall < 0)
{
throw Exception("failed to retrieve ion dma_buf handle");
}
info.VideoBufferDmaBufferFD[i] = fd_data.fd;
// Physical Address
// Get the physical address for the buffer
meson_phys_data physData = { 0 };
physData.handle = fd_data.fd;
ion_custom_data ionCustomData = { 0 };
ionCustomData.cmd = ION_IOC_MESON_PHYS_ADDR;
ionCustomData.arg = (long unsigned int)&physData;
ionCall = ioctl(info.IonFD, ION_IOC_CUSTOM, &ionCustomData);
if (ionCall != 0)
{
throw Exception("ION_IOC_CUSTOM failed.");
//printf("ION_IOC_CUSTOM failed (%d).", io);
}
info.PhysicalAddress = physData.phys_addr;
// Queue the buffer for V4L to use
v4l2_buffer buffer = { 0 };
buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buffer.memory = V4L2_MEMORY_DMABUF;
buffer.index = i;
buffer.m.fd = info.VideoBufferDmaBufferFD[i];
buffer.length = 1; // Ionvideo only supports single plane
v4lcall = ioctl(info.IonVideoFD, VIDIOC_QBUF, &buffer);
if (v4lcall < 0)
{
throw Exception("failed to queue ion buffer.");
}
// DEBUG
//printf("Queued v4l2_buffer:\n");
//printf("\tindex=%x\n", buffer.index);
//printf("\ttype=%x\n", buffer.type);
//printf("\tm.fd=%x\n", buffer.m.fd);
}
// Start "streaming"
int bufferType = V4L2_BUF_TYPE_VIDEO_CAPTURE;
v4lcall = ioctl(info.IonVideoFD, VIDIOC_STREAMON, &bufferType);
if (v4lcall < 0)
{
throw Exception("ionvideo VIDIOC_STREAMON failed.");
}
return info;
}
Stopwatch sw;
Timer timer;
int ion_fd = -1;
IonBuffer YuvSource = { 0 };
IonBuffer YuvDestination = { 0 };
int main(int argc, char** argv)
{
int io;
// options
const char* device = DEFAULT_DEVICE;
const char* output = DEFAULT_OUTPUT;
int width = DEFAULT_WIDTH;
int height = DEFAULT_HEIGHT;
int fps = DEFAULT_FRAME_RATE;
int bitrate = DEFAULT_BITRATE;
PictureFormat pixformat = PictureFormat::Yuyv;
int c;
while ((c = getopt_long(argc, argv, "d:o:w:h:f:b:p:", longopts, NULL)) != -1)
{
switch (c)
{
case 'd':
device = optarg;
break;
case 'o':
output = optarg;
break;
case 'w':
width = atoi(optarg);
break;
case 'h':
height = atoi(optarg);
break;
case 'f':
fps = atoi(optarg);
break;
case 'b':
bitrate = atoi(optarg);
break;
case 'p':
if (strcmp(optarg, "yuyv") == 0)
{
pixformat = PictureFormat::Yuyv;
}
else if (strcmp(optarg, "mjpeg") == 0)
{
pixformat = PictureFormat::MJpeg;
}
else
{
throw Exception("Unknown pixformat.");
}
break;
default:
throw Exception("Unknown option.");
}
}
int captureDev = open(device, O_RDWR);
if (captureDev < 0)
{
throw Exception("capture device open failed.");
}
v4l2_capability caps = { 0 };
io = ioctl(captureDev, VIDIOC_QUERYCAP, &caps);
if (io < 0)
{
throw Exception("VIDIOC_QUERYCAP failed.");
}
printf("card = %s\n", (char*)caps.card);
printf("\tbus_info = %s\n", (char*)caps.bus_info);
printf("\tdriver = %s\n", (char*)caps.driver);
if (!caps.capabilities & V4L2_CAP_VIDEO_CAPTURE)
{
throw Exception("V4L2_CAP_VIDEO_CAPTURE not supported.");
}
else
{
fprintf(stderr, "V4L2_CAP_VIDEO_CAPTURE supported.\n");
}
v4l2_fmtdesc formatDesc = { 0 };
formatDesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fprintf(stderr, "Supported formats:\n");
while (true)
{
io = ioctl(captureDev, VIDIOC_ENUM_FMT, &formatDesc);
if (io < 0)
{
//printf("VIDIOC_ENUM_FMT failed.\n");
break;
}
fprintf(stderr, "\tdescription = %s, pixelformat=0x%x\n", formatDesc.description, formatDesc.pixelformat);
v4l2_frmsizeenum formatSize = { 0 };
formatSize.pixel_format = formatDesc.pixelformat;
while (true)
{
io = ioctl(captureDev, VIDIOC_ENUM_FRAMESIZES, &formatSize);
if (io < 0)
{
//printf("VIDIOC_ENUM_FRAMESIZES failed.\n");
break;
}
fprintf(stderr, "\t\twidth = %d, height = %d\n", formatSize.discrete.width, formatSize.discrete.height);
v4l2_frmivalenum frameInterval = { 0 };
frameInterval.pixel_format = formatSize.pixel_format;
frameInterval.width = formatSize.discrete.width;
frameInterval.height = formatSize.discrete.height;
while (true)
{
io = ioctl(captureDev, VIDIOC_ENUM_FRAMEINTERVALS, &frameInterval);
if (io < 0)
{
//printf("VIDIOC_ENUM_FRAMEINTERVALS failed.\n");
break;
}
fprintf(stderr, "\t\t\tnumerator = %d, denominator = %d\n", frameInterval.discrete.numerator, frameInterval.discrete.denominator);
++frameInterval.index;
}
++formatSize.index;
}
++formatDesc.index;
}
// Apply capture settings
v4l2_format format = { 0 };
format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
format.fmt.pix.width = width;
format.fmt.pix.height = height;
//format.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
//format.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
format.fmt.pix.pixelformat = (__u32)pixformat;
format.fmt.pix.field = V4L2_FIELD_ANY; //V4L2_FIELD_INTERLACED; //V4L2_FIELD_ANY; V4L2_FIELD_ALTERNATE
io = ioctl(captureDev, VIDIOC_S_FMT, &format);
if (io < 0)
{
throw Exception("VIDIOC_S_FMT failed.");
}
fprintf(stderr, "v4l2_format: width=%d, height=%d, pixelformat=0x%x\n",
format.fmt.pix.width, format.fmt.pix.height, format.fmt.pix.pixelformat);
// Readback device selected settings
width = format.fmt.pix.width;
height = format.fmt.pix.height;
pixformat = (PictureFormat)format.fmt.pix.pixelformat;
v4l2_streamparm streamParm = { 0 };
streamParm.type = format.type;
streamParm.parm.capture.timeperframe.numerator = 1;
streamParm.parm.capture.timeperframe.denominator = fps;
io = ioctl(captureDev, VIDIOC_S_PARM, &streamParm);
if (io < 0)
{
throw Exception("VIDIOC_S_PARM failed.");
}
fprintf(stderr, "capture.timeperframe: numerator=%d, denominator=%d\n",
streamParm.parm.capture.timeperframe.numerator,
streamParm.parm.capture.timeperframe.denominator);
// Note: Video is encoded at the requested framerate whether
// the device produces it or not. Therefore, there is no
// need to read back teh fps.
// Request buffers
v4l2_requestbuffers requestBuffers = { 0 };
requestBuffers.count = BUFFER_COUNT;
requestBuffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
requestBuffers.memory = V4L2_MEMORY_MMAP;
io = ioctl(captureDev, VIDIOC_REQBUFS, &requestBuffers);
if (io < 0)
{
throw Exception("VIDIOC_REQBUFS failed.");
}
// Map buffers
BufferMapping bufferMappings[requestBuffers.count] = { 0 };
for (int i = 0; i < requestBuffers.count; ++i)
{
v4l2_buffer buffer = { 0 };
buffer.type = requestBuffers.type;
buffer.memory = V4L2_MEMORY_MMAP;
buffer.index = i;
io = ioctl(captureDev, VIDIOC_QUERYBUF, &buffer);
if (io < 0)
{
throw Exception("VIDIOC_QUERYBUF failed.");
}
bufferMappings[i].Length = buffer.length;
bufferMappings[i].Start = mmap(NULL, buffer.length,
PROT_READ | PROT_WRITE, /* recommended */
MAP_SHARED, /* recommended */
captureDev, buffer.m.offset);
}
// Queue buffers
for (int i = 0; i < requestBuffers.count; ++i)
{
v4l2_buffer buffer = { 0 };
buffer.index = i;
buffer.type = requestBuffers.type;
buffer.memory = requestBuffers.memory;
io = ioctl(captureDev, VIDIOC_QBUF, &buffer);
if (io < 0)
{
throw Exception("VIDIOC_QBUF failed.");
}
}
// Create an output file
int fdOut;
if (std::strcmp(output, "-") == 0)
{
fdOut = 1; //stdout
}
else
{
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
fdOut = open(output, O_CREAT | O_TRUNC | O_WRONLY, mode);
if (fdOut < 0)
{
throw Exception("open output failed.");
}
}
encoderFileDescriptor = fdOut;
// GE2D
int ge2d_fd = open("/dev/ge2d", O_RDWR);
if (ge2d_fd < 0)
{
throw Exception("open /dev/ge2d failed.");
}
// Ion
ion_fd = open("/dev/ion", O_RDWR);
if (ion_fd < 0)
{
throw Exception("open ion failed.");
}
YuvSource = IonAllocate(ion_fd, width * height * 4);
void* yuvSourcePtr = mmap(NULL,
YuvSource.Length,
PROT_READ | PROT_WRITE,
MAP_FILE | MAP_SHARED,
YuvSource.ExportHandle,
0);
if (!yuvSourcePtr)
{
throw Exception("YuvSource mmap failed.");
}
YuvDestination = IonAllocate(ion_fd, width * height * 4);
void* yuvDestinationPtr = mmap(NULL,
YuvDestination.Length,
PROT_READ | PROT_WRITE,
MAP_FILE | MAP_SHARED,
YuvDestination.ExportHandle,
0);
if (!yuvDestinationPtr)
{
throw Exception("YuvDestination mmap failed.");
}
// Ionvideo
SetVfmState();
//IonInfo ionInfo = OpenIonVideoCapture(width, height);
int vfmGrabberFd = open("/dev/vfm_grabber", O_RDWR);
if (vfmGrabberFd < 0)
{
throw Exception("open vfm_grabber failed.");
}
// Create MJPEG codec
OpenCodec(width, height, 60 /*fps*/);
#if 1
// Initialize the encoder
vl_codec_id_t codec_id = CODEC_ID_H264;
width = format.fmt.pix.width;
height = format.fmt.pix.height;
fps = (int)((double)streamParm.parm.capture.timeperframe.denominator /
(double)streamParm.parm.capture.timeperframe.numerator);
//int bit_rate = bitrate;
int gop = 10;
fprintf(stderr, "vl_video_encoder_init: width=%d, height=%d, fps=%d, bitrate=%d, gop=%d\n",
width, height, fps, bitrate, gop);
vl_img_format_t img_format = IMG_FMT_NV12;
handle = vl_video_encoder_init(codec_id, width, height, fps, bitrate, gop, img_format);
fprintf(stderr, "handle = %ld\n", handle);
#endif
// Start streaming
int bufferType = V4L2_BUF_TYPE_VIDEO_CAPTURE;
io = ioctl(captureDev, VIDIOC_STREAMON, &bufferType);
if (io < 0)
{
throw Exception("VIDIOC_STREAMON failed.");
}
int nv12Size = format.fmt.pix.width * format.fmt.pix.height * 4;
unsigned char* nv12 = (unsigned char*)yuvDestinationPtr; //new unsigned char[nv12Size];
encodeNV12Buffer = nv12;
fprintf(stderr, "nv12Size = %d\n", nv12Size);
int ENCODE_BUFFER_SIZE = nv12Size; //1024 * 32;
char* encodeBuffer = new char[ENCODE_BUFFER_SIZE];
encodeBitstreamBuffer = encodeBuffer;
//fprintf(stderr, "ENCODEC_BUFFER_SIZE = %d\n", ENCODEC_BUFFER_SIZE);
// jpeg-turbo