/
DVDVideoCodecVideoToolBox.cpp
1708 lines (1492 loc) · 53.3 KB
/
DVDVideoCodecVideoToolBox.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) 2010 Team XBMC
* http://www.xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#if (defined HAVE_CONFIG_H) && (!defined WIN32)
#include "config.h"
#endif
#if defined(HAVE_VIDEOTOOLBOXDECODER)
#include "GUISettings.h"
#include "DVDClock.h"
#include "DVDStreamInfo.h"
#include "DVDCodecUtils.h"
#include "DVDVideoCodecVideoToolBox.h"
#include "lib/DllSwScale.h"
#include "lib/DllAvFormat.h"
#include "utils/log.h"
#include "utils/TimeUtils.h"
#include "osx/DarwinUtils.h"
#if defined(__cplusplus)
extern "C"
{
#endif
#pragma pack(push, 4)
//-----------------------------------------------------------------------------------
// /System/Library/PrivateFrameworks/VideoToolbox.framework
enum VTFormat {
kVTFormatJPEG = 'jpeg', // kCMVideoCodecType_JPEG
kVTFormatH264 = 'avc1', // kCMVideoCodecType_H264 (MPEG-4 Part 10))
kVTFormatMPEG4Video = 'mp4v', // kCMVideoCodecType_MPEG4Video (MPEG-4 Part 2)
kVTFormatMPEG2Video = 'mp2v' // kCMVideoCodecType_MPEG2Video
};
enum {
kVTDecoderNoErr = 0,
kVTDecoderHardwareNotSupportedErr = -12470,
kVTDecoderFormatNotSupportedErr = -12471,
kVTDecoderConfigurationError = -12472,
kVTDecoderDecoderFailedErr = -12473,
};
enum {
kVTDecodeInfo_Asynchronous = 1UL << 0,
kVTDecodeInfo_FrameDropped = 1UL << 1
};
enum {
// tells the decoder not to bother returning a CVPixelBuffer
// in the outputCallback. The output callback will still be called.
kVTDecoderDecodeFlags_DontEmitFrame = 1 << 0
};
enum {
// decode and return buffers for all frames currently in flight.
kVTDecoderFlush_EmitFrames = 1 << 0
};
typedef UInt32 VTFormatId;
typedef CFTypeRef VTDecompressionSessionRef;
typedef void (*VTDecompressionOutputCallbackFunc)(
void *refCon,
CFDictionaryRef frameInfo,
OSStatus status,
UInt32 infoFlags,
CVBufferRef imageBuffer);
typedef struct _VTDecompressionOutputCallback VTDecompressionOutputCallback;
struct _VTDecompressionOutputCallback {
VTDecompressionOutputCallbackFunc callback;
void *refcon;
};
extern CFStringRef kVTVideoDecoderSpecification_EnableSandboxedVideoDecoder;
extern OSStatus VTDecompressionSessionCreate(
CFAllocatorRef allocator,
CMFormatDescriptionRef videoFormatDescription,
CFTypeRef sessionOptions,
CFDictionaryRef destinationPixelBufferAttributes,
VTDecompressionOutputCallback *outputCallback,
VTDecompressionSessionRef *session);
extern OSStatus VTDecompressionSessionDecodeFrame(
VTDecompressionSessionRef session, CMSampleBufferRef sbuf,
uint32_t decoderFlags, CFDictionaryRef frameInfo, uint32_t unk1);
extern OSStatus VTDecompressionSessionCopyProperty(VTDecompressionSessionRef session, CFTypeRef key, void* unk, CFTypeRef * value);
extern OSStatus VTDecompressionSessionCopySupportedPropertyDictionary(VTDecompressionSessionRef session, CFDictionaryRef * dict);
extern OSStatus VTDecompressionSessionSetProperty(VTDecompressionSessionRef session, CFStringRef propName, CFTypeRef propValue);
extern void VTDecompressionSessionInvalidate(VTDecompressionSessionRef session);
extern void VTDecompressionSessionRelease(VTDecompressionSessionRef session);
extern VTDecompressionSessionRef VTDecompressionSessionRetain(VTDecompressionSessionRef session);
extern OSStatus VTDecompressionSessionWaitForAsynchronousFrames(VTDecompressionSessionRef session);
//-----------------------------------------------------------------------------------
// /System/Library/Frameworks/CoreMedia.framework
union
{
void* lpAddress;
// iOS <= 4.2
OSStatus (*FigVideoFormatDescriptionCreateWithSampleDescriptionExtensionAtom1)(
CFAllocatorRef allocator, UInt32 formatId, UInt32 width, UInt32 height,
UInt32 atomId, const UInt8 *data, CFIndex len, CMFormatDescriptionRef *formatDesc);
// iOS >= 4.3
OSStatus (*FigVideoFormatDescriptionCreateWithSampleDescriptionExtensionAtom2)(
CFAllocatorRef allocator, UInt32 formatId, UInt32 width, UInt32 height,
UInt32 atomId, const UInt8 *data, CFIndex len, CFDictionaryRef extensions, CMFormatDescriptionRef *formatDesc);
} FigVideoHack;
extern OSStatus FigVideoFormatDescriptionCreateWithSampleDescriptionExtensionAtom(
CFAllocatorRef allocator, UInt32 formatId, UInt32 width, UInt32 height,
UInt32 atomId, const UInt8 *data, CFIndex len, CMFormatDescriptionRef *formatDesc);
extern CMSampleBufferRef FigSampleBufferRetain(CMSampleBufferRef buf);
//-----------------------------------------------------------------------------------
#pragma pack(pop)
#if defined(__cplusplus)
}
#endif
int CheckNP2( unsigned x )
{
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return ++x;
}
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// helper functions for debuging VTDecompression
#if _DEBUG
char* vtutil_string_to_utf8(CFStringRef s)
{
char *result;
CFIndex size;
size = CFStringGetMaximumSizeForEncoding(CFStringGetLength (s), kCFStringEncodingUTF8);
result = (char*)malloc(size + 1);
CFStringGetCString(s, result, size + 1, kCFStringEncodingUTF8);
return result;
}
char* vtutil_object_to_string(CFTypeRef obj)
{
char *result;
CFStringRef s;
if (obj == NULL)
return strdup ("(null)");
s = CFCopyDescription(obj);
result = vtutil_string_to_utf8(s);
CFRelease(s);
return result;
}
typedef struct {
VTDecompressionSessionRef session;
} VTDumpDecompressionPropCtx;
void
vtdec_session_dump_property(CFStringRef prop_name, CFDictionaryRef prop_attrs, VTDumpDecompressionPropCtx *dpc)
{
char *name_str;
CFTypeRef prop_value;
OSStatus status;
name_str = vtutil_string_to_utf8(prop_name);
if (true)
{
char *attrs_str;
attrs_str = vtutil_object_to_string(prop_attrs);
CLog::Log(LOGDEBUG, "%s = %s\n", name_str, attrs_str);
free(attrs_str);
}
status = VTDecompressionSessionCopyProperty(dpc->session, prop_name, NULL, &prop_value);
if (status == kVTDecoderNoErr)
{
char *value_str;
value_str = vtutil_object_to_string(prop_value);
CLog::Log(LOGDEBUG, "%s = %s\n", name_str, value_str);
free(value_str);
if (prop_value != NULL)
CFRelease(prop_value);
}
else
{
CLog::Log(LOGDEBUG, "%s = <failed to query: %d>\n", name_str, (int)status);
}
free(name_str);
}
void vtdec_session_dump_properties(VTDecompressionSessionRef session)
{
VTDumpDecompressionPropCtx dpc = { session };
CFDictionaryRef dict;
OSStatus status;
status = VTDecompressionSessionCopySupportedPropertyDictionary(session, &dict);
if (status != kVTDecoderNoErr)
goto error;
CFDictionaryApplyFunction(dict, (CFDictionaryApplierFunction)vtdec_session_dump_property, &dpc);
CFRelease(dict);
return;
error:
CLog::Log(LOGDEBUG, "failed to dump properties\n");
}
#endif
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// helper function that inserts an int32_t into a dictionary
static void
CFDictionarySetSInt32(CFMutableDictionaryRef dictionary, CFStringRef key, SInt32 numberSInt32)
{
CFNumberRef number;
number = CFNumberCreate(NULL, kCFNumberSInt32Type, &numberSInt32);
CFDictionarySetValue(dictionary, key, number);
CFRelease(number);
}
// helper function that inserts an double into a dictionary
static void
CFDictionarySetDouble(CFMutableDictionaryRef dictionary, CFStringRef key, double numberDouble)
{
CFNumberRef number;
number = CFNumberCreate(NULL, kCFNumberDoubleType, &numberDouble);
CFDictionaryAddValue(dictionary, key, number);
CFRelease(number);
}
// helper function that wraps dts/pts into a dictionary
static CFDictionaryRef
CreateDictionaryWithDisplayTime(double time, double dts, double pts)
{
CFStringRef key[3] = {
CFSTR("VideoDisplay_TIME"),
CFSTR("VideoDisplay_DTS"),
CFSTR("VideoDisplay_PTS")};
CFNumberRef value[3];
CFDictionaryRef display_time;
value[0] = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &time);
value[1] = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &dts);
value[2] = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &pts);
display_time = CFDictionaryCreate(
kCFAllocatorDefault, (const void **)&key, (const void **)&value, 3,
&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFRelease(value[0]);
CFRelease(value[1]);
CFRelease(value[2]);
return display_time;
}
// helper function to extract dts/pts from a dictionary
static void
GetFrameDisplayTimeFromDictionary(
CFDictionaryRef inFrameInfoDictionary, frame_queue *frame)
{
// default to DVD_NOPTS_VALUE
frame->sort_time = -1.0;
frame->dts = DVD_NOPTS_VALUE;
frame->pts = DVD_NOPTS_VALUE;
if (inFrameInfoDictionary == NULL)
return;
CFNumberRef value[3];
//
value[0] = (CFNumberRef)CFDictionaryGetValue(inFrameInfoDictionary, CFSTR("VideoDisplay_TIME"));
if (value[0])
CFNumberGetValue(value[0], kCFNumberDoubleType, &frame->sort_time);
value[1] = (CFNumberRef)CFDictionaryGetValue(inFrameInfoDictionary, CFSTR("VideoDisplay_DTS"));
if (value[1])
CFNumberGetValue(value[1], kCFNumberDoubleType, &frame->dts);
value[2] = (CFNumberRef)CFDictionaryGetValue(inFrameInfoDictionary, CFSTR("VideoDisplay_PTS"));
if (value[2])
CFNumberGetValue(value[2], kCFNumberDoubleType, &frame->pts);
return;
}
// helper function to create a format descriptor
static CMFormatDescriptionRef
CreateFormatDescription(VTFormatId format_id, int width, int height)
{
CMFormatDescriptionRef fmt_desc;
OSStatus status;
status = CMVideoFormatDescriptionCreate(
NULL, // CFAllocatorRef allocator
format_id,
width,
height,
NULL, // CFDictionaryRef extensions
&fmt_desc);
if (status == kVTDecoderNoErr)
return fmt_desc;
else
return NULL;
}
// helper function to create a avcC atom format descriptor
static CMFormatDescriptionRef
CreateFormatDescriptionFromCodecData(VTFormatId format_id, int width, int height, const uint8_t *extradata, int extradata_size, uint32_t atom)
{
CMFormatDescriptionRef fmt_desc = NULL;
OSStatus status;
FigVideoHack.lpAddress = (void*)FigVideoFormatDescriptionCreateWithSampleDescriptionExtensionAtom;
if (GetIOSVersion() < 4.3)
{
CLog::Log(LOGDEBUG, "%s - GetIOSVersion says < 4.3", __FUNCTION__);
status = FigVideoHack.FigVideoFormatDescriptionCreateWithSampleDescriptionExtensionAtom1(
NULL,
format_id,
width,
height,
atom,
extradata,
extradata_size,
&fmt_desc);
}
else
{
CLog::Log(LOGDEBUG, "%s - GetIOSVersion says >= 4.3", __FUNCTION__);
status = FigVideoHack.FigVideoFormatDescriptionCreateWithSampleDescriptionExtensionAtom2(
NULL,
format_id,
width,
height,
atom,
extradata,
extradata_size,
NULL,
&fmt_desc);
}
if (status == kVTDecoderNoErr)
return fmt_desc;
else
return NULL;
}
// helper function to create a CMSampleBufferRef from demuxer data
static CMSampleBufferRef
CreateSampleBufferFrom(CMFormatDescriptionRef fmt_desc, void *demux_buff, size_t demux_size)
{
OSStatus status;
CMBlockBufferRef newBBufOut = NULL;
CMSampleBufferRef sBufOut = NULL;
status = CMBlockBufferCreateWithMemoryBlock(
NULL, // CFAllocatorRef structureAllocator
demux_buff, // void *memoryBlock
demux_size, // size_t blockLengt
kCFAllocatorNull, // CFAllocatorRef blockAllocator
NULL, // const CMBlockBufferCustomBlockSource *customBlockSource
0, // size_t offsetToData
demux_size, // size_t dataLength
FALSE, // CMBlockBufferFlags flags
&newBBufOut); // CMBlockBufferRef *newBBufOut
if (!status)
{
status = CMSampleBufferCreate(
NULL, // CFAllocatorRef allocator
newBBufOut, // CMBlockBufferRef dataBuffer
TRUE, // Boolean dataReady
0, // CMSampleBufferMakeDataReadyCallback makeDataReadyCallback
0, // void *makeDataReadyRefcon
fmt_desc, // CMFormatDescriptionRef formatDescription
1, // CMItemCount numSamples
0, // CMItemCount numSampleTimingEntries
NULL, // const CMSampleTimingInfo *sampleTimingArray
0, // CMItemCount numSampleSizeEntries
NULL, // const size_t *sampleSizeArray
&sBufOut); // CMSampleBufferRef *sBufOut
}
CFRelease(newBBufOut);
/*
CLog::Log(LOGDEBUG, "%s - CreateSampleBufferFrom size %ld demux_buff [0x%08x] sBufOut [0x%08x]",
__FUNCTION__, demux_size, (unsigned int)demux_buff, (unsigned int)sBufOut);
*/
return sBufOut;
}
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
/* MPEG-4 esds (elementary stream descriptor) */
typedef struct {
int version;
long flags;
uint16_t esid;
uint8_t stream_priority;
uint8_t objectTypeId;
uint8_t streamType;
uint32_t bufferSizeDB;
uint32_t maxBitrate;
uint32_t avgBitrate;
int decoderConfigLen;
uint8_t* decoderConfig;
} quicktime_esds_t;
int quicktime_write_mp4_descr_length(DllAvFormat *av_format_ctx, AVIOContext *pb, int length, int compact)
{
int i;
uint8_t b;
int numBytes;
if (compact)
{
if (length <= 0x7F)
{
numBytes = 1;
}
else if (length <= 0x3FFF)
{
numBytes = 2;
}
else if (length <= 0x1FFFFF)
{
numBytes = 3;
}
else
{
numBytes = 4;
}
}
else
{
numBytes = 4;
}
for (i = numBytes-1; i >= 0; i--)
{
b = (length >> (i * 7)) & 0x7F;
if (i != 0)
{
b |= 0x80;
}
av_format_ctx->avio_w8(pb, b);
}
return numBytes;
}
void quicktime_write_esds(DllAvFormat *av_format_ctx, AVIOContext *pb, quicktime_esds_t *esds)
{
av_format_ctx->avio_w8(pb, 0); // Version
av_format_ctx->avio_wb24(pb, 0); // Flags
// elementary stream descriptor tag
av_format_ctx->avio_w8(pb, 0x03);
quicktime_write_mp4_descr_length(av_format_ctx, pb,
3 + 5 + (13 + 5 + esds->decoderConfigLen) + 3, false);
// 3 bytes + 5 bytes for tag
av_format_ctx->avio_wb16(pb, esds->esid);
av_format_ctx->avio_w8(pb, esds->stream_priority);
// decoder configuration description tag
av_format_ctx->avio_w8(pb, 0x04);
quicktime_write_mp4_descr_length(av_format_ctx, pb,
13 + 5 + esds->decoderConfigLen, false);
// 13 bytes + 5 bytes for tag
av_format_ctx->avio_w8(pb, esds->objectTypeId); // objectTypeIndication
av_format_ctx->avio_w8(pb, esds->streamType); // streamType
av_format_ctx->avio_wb24(pb, esds->bufferSizeDB); // buffer size
av_format_ctx->avio_wb32(pb, esds->maxBitrate); // max bitrate
av_format_ctx->avio_wb32(pb, esds->avgBitrate); // average bitrate
// decoder specific description tag
av_format_ctx->avio_w8(pb, 0x05);
quicktime_write_mp4_descr_length(av_format_ctx, pb, esds->decoderConfigLen, false);
av_format_ctx->avio_write(pb, esds->decoderConfig, esds->decoderConfigLen);
// sync layer configuration descriptor tag
av_format_ctx->avio_w8(pb, 0x06); // tag
av_format_ctx->avio_w8(pb, 0x01); // length
av_format_ctx->avio_w8(pb, 0x7F); // no SL
/* no IPI_DescrPointer */
/* no IP_IdentificationDataSet */
/* no IPMP_DescriptorPointer */
/* no LanguageDescriptor */
/* no QoS_Descriptor */
/* no RegistrationDescriptor */
/* no ExtensionDescriptor */
}
quicktime_esds_t* quicktime_set_esds(DllAvFormat *av_format_ctx, const uint8_t * decoderConfig, int decoderConfigLen)
{
// ffmpeg's codec->avctx->extradata, codec->avctx->extradata_size
// are decoderConfig/decoderConfigLen
quicktime_esds_t *esds;
esds = (quicktime_esds_t*)malloc(sizeof(quicktime_esds_t));
memset(esds, 0, sizeof(quicktime_esds_t));
esds->version = 0;
esds->flags = 0;
esds->esid = 0;
esds->stream_priority = 0; // 16 ? 0x1f
esds->objectTypeId = 32; // 32 = CODEC_ID_MPEG4, 33 = CODEC_ID_H264
// the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
// plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
esds->streamType = 0x11;
esds->bufferSizeDB = 64000; // Hopefully not important :)
// Maybe correct these later?
esds->maxBitrate = 200000; // 0 for vbr
esds->avgBitrate = 200000;
esds->decoderConfigLen = decoderConfigLen;
esds->decoderConfig = (uint8_t*)malloc(esds->decoderConfigLen);
memcpy(esds->decoderConfig, decoderConfig, esds->decoderConfigLen);
return esds;
}
void quicktime_esds_dump(quicktime_esds_t * esds)
{
int i;
printf("esds: \n");
printf(" Version: %d\n", esds->version);
printf(" Flags: 0x%06lx\n", esds->flags);
printf(" ES ID: 0x%04x\n", esds->esid);
printf(" Priority: 0x%02x\n", esds->stream_priority);
printf(" objectTypeId: %d\n", esds->objectTypeId);
printf(" streamType: 0x%02x\n", esds->streamType);
printf(" bufferSizeDB: %d\n", esds->bufferSizeDB);
printf(" maxBitrate: %d\n", esds->maxBitrate);
printf(" avgBitrate: %d\n", esds->avgBitrate);
printf(" decoderConfigLen: %d\n", esds->decoderConfigLen);
printf(" decoderConfig:");
for(i = 0; i < esds->decoderConfigLen; i++)
{
if(!(i % 16))
printf("\n ");
printf("%02x ", esds->decoderConfig[i]);
}
printf("\n");
}
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// TODO: refactor this so as not to need these ffmpeg routines.
// These are not exposed in ffmpeg's API so we dupe them here.
// AVC helper functions for muxers,
// * Copyright (c) 2006 Baptiste Coudurier <baptiste.coudurier@smartjog.com>
// This is part of FFmpeg
// * License as published by the Free Software Foundation; either
// * version 2.1 of the License, or (at your option) any later version.
#define VDA_RB16(x) \
((((const uint8_t*)(x))[0] << 8) | \
((const uint8_t*)(x)) [1])
#define VDA_RB24(x) \
((((const uint8_t*)(x))[0] << 16) | \
(((const uint8_t*)(x))[1] << 8) | \
((const uint8_t*)(x))[2])
#define VDA_RB32(x) \
((((const uint8_t*)(x))[0] << 24) | \
(((const uint8_t*)(x))[1] << 16) | \
(((const uint8_t*)(x))[2] << 8) | \
((const uint8_t*)(x))[3])
static const uint8_t *avc_find_startcode_internal(const uint8_t *p, const uint8_t *end)
{
const uint8_t *a = p + 4 - ((intptr_t)p & 3);
for (end -= 3; p < a && p < end; p++)
{
if (p[0] == 0 && p[1] == 0 && p[2] == 1)
return p;
}
for (end -= 3; p < end; p += 4)
{
uint32_t x = *(const uint32_t*)p;
if ((x - 0x01010101) & (~x) & 0x80808080) // generic
{
if (p[1] == 0)
{
if (p[0] == 0 && p[2] == 1)
return p;
if (p[2] == 0 && p[3] == 1)
return p+1;
}
if (p[3] == 0)
{
if (p[2] == 0 && p[4] == 1)
return p+2;
if (p[4] == 0 && p[5] == 1)
return p+3;
}
}
}
for (end += 3; p < end; p++)
{
if (p[0] == 0 && p[1] == 0 && p[2] == 1)
return p;
}
return end + 3;
}
const uint8_t *avc_find_startcode(const uint8_t *p, const uint8_t *end)
{
const uint8_t *out= avc_find_startcode_internal(p, end);
if (p<out && out<end && !out[-1])
out--;
return out;
}
const int avc_parse_nal_units(DllAvFormat *av_format_ctx,
AVIOContext *pb, const uint8_t *buf_in, int size)
{
const uint8_t *p = buf_in;
const uint8_t *end = p + size;
const uint8_t *nal_start, *nal_end;
size = 0;
nal_start = avc_find_startcode(p, end);
while (nal_start < end)
{
while (!*(nal_start++));
nal_end = avc_find_startcode(nal_start, end);
av_format_ctx->avio_wb32(pb, nal_end - nal_start);
av_format_ctx->avio_write(pb, nal_start, nal_end - nal_start);
size += 4 + nal_end - nal_start;
nal_start = nal_end;
}
return size;
}
const int avc_parse_nal_units_buf(DllAvUtil *av_util_ctx, DllAvFormat *av_format_ctx,
const uint8_t *buf_in, uint8_t **buf, int *size)
{
AVIOContext *pb;
int ret = av_format_ctx->avio_open_dyn_buf(&pb);
if (ret < 0)
return ret;
avc_parse_nal_units(av_format_ctx, pb, buf_in, *size);
av_util_ctx->av_freep(buf);
*size = av_format_ctx->avio_close_dyn_buf(pb, buf);
return 0;
}
/*
* if extradata size is greater than 7, then have a valid quicktime
* avcC atom header.
*
* -: avcC atom header :-
* -----------------------------------
* 1 byte - version
* 1 byte - h.264 stream profile
* 1 byte - h.264 compatible profiles
* 1 byte - h.264 stream level
* 6 bits - reserved set to 63
* 2 bits - NAL length
* ( 0 - 1 byte; 1 - 2 bytes; 3 - 4 bytes)
* 3 bit - reserved
* 5 bits - number of SPS
* for (i=0; i < number of SPS; i++) {
* 2 bytes - SPS length
* SPS length bytes - SPS NAL unit
* }
* 1 byte - number of PPS
* for (i=0; i < number of PPS; i++) {
* 2 bytes - PPS length
* PPS length bytes - PPS NAL unit
* }
how to detect the interlacing used on an existing stream:
- progressive is signalled by setting
frame_mbs_only_flag: 1 in the SPS.
- interlaced is signalled by setting
frame_mbs_only_flag: 0 in the SPS and
field_pic_flag: 1 on all frames.
- paff is signalled by setting
frame_mbs_only_flag: 0 in the SPS and
field_pic_flag: 1 on all frames that get interlaced and
field_pic_flag: 0 on all frames that get progressive.
- mbaff is signalled by setting
frame_mbs_only_flag: 0 in the SPS and
mb_adaptive_frame_field_flag: 1 in the SPS and
field_pic_flag: 0 on the frames,
(field_pic_flag: 1 would indicate a normal interlaced frame).
*/
const int isom_write_avcc(DllAvUtil *av_util_ctx, DllAvFormat *av_format_ctx,
AVIOContext *pb, const uint8_t *data, int len)
{
// extradata from bytestream h264, convert to avcC atom data for bitstream
if (len > 6)
{
/* check for h264 start code */
if (VDA_RB32(data) == 0x00000001 || VDA_RB24(data) == 0x000001)
{
uint8_t *buf=NULL, *end, *start;
uint32_t sps_size=0, pps_size=0;
uint8_t *sps=0, *pps=0;
int ret = avc_parse_nal_units_buf(av_util_ctx, av_format_ctx, data, &buf, &len);
if (ret < 0)
return ret;
start = buf;
end = buf + len;
/* look for sps and pps */
while (buf < end)
{
unsigned int size;
uint8_t nal_type;
size = VDA_RB32(buf);
nal_type = buf[4] & 0x1f;
if (nal_type == 7) /* SPS */
{
sps = buf + 4;
sps_size = size;
}
else if (nal_type == 8) /* PPS */
{
pps = buf + 4;
pps_size = size;
}
buf += size + 4;
}
assert(sps);
av_format_ctx->avio_w8(pb, 1); /* version */
av_format_ctx->avio_w8(pb, sps[1]); /* profile */
av_format_ctx->avio_w8(pb, sps[2]); /* profile compat */
av_format_ctx->avio_w8(pb, sps[3]); /* level */
av_format_ctx->avio_w8(pb, 0xff); /* 6 bits reserved (111111) + 2 bits nal size length - 1 (11) */
av_format_ctx->avio_w8(pb, 0xe1); /* 3 bits reserved (111) + 5 bits number of sps (00001) */
av_format_ctx->avio_wb16(pb, sps_size);
av_format_ctx->avio_write(pb, sps, sps_size);
if (pps)
{
av_format_ctx->avio_w8(pb, 1); /* number of pps */
av_format_ctx->avio_wb16(pb, pps_size);
av_format_ctx->avio_write(pb, pps, pps_size);
}
av_util_ctx->av_free(start);
}
else
{
av_format_ctx->avio_write(pb, data, len);
}
}
return 0;
}
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
// GStreamer h264 parser
// Copyright (C) 2005 Michal Benes <michal.benes@itonis.tv>
// (C) 2008 Wim Taymans <wim.taymans@gmail.com>
// gsth264parse.c:
// * License as published by the Free Software Foundation; either
// * version 2.1 of the License, or (at your option) any later version.
typedef struct
{
const uint8_t *data;
const uint8_t *end;
int head;
uint64_t cache;
} nal_bitstream;
static void
nal_bs_init(nal_bitstream *bs, const uint8_t *data, size_t size)
{
bs->data = data;
bs->end = data + size;
bs->head = 0;
// fill with something other than 0 to detect
// emulation prevention bytes
bs->cache = 0xffffffff;
}
static uint32_t
nal_bs_read(nal_bitstream *bs, int n)
{
uint32_t res = 0;
int shift;
if (n == 0)
return res;
// fill up the cache if we need to
while (bs->head < n)
{
uint8_t a_byte;
bool check_three_byte;
check_three_byte = TRUE;
next_byte:
if (bs->data >= bs->end)
{
// we're at the end, can't produce more than head number of bits
n = bs->head;
break;
}
// get the byte, this can be an emulation_prevention_three_byte that we need
// to ignore.
a_byte = *bs->data++;
if (check_three_byte && a_byte == 0x03 && ((bs->cache & 0xffff) == 0))
{
// next byte goes unconditionally to the cache, even if it's 0x03
check_three_byte = FALSE;
goto next_byte;
}
// shift bytes in cache, moving the head bits of the cache left
bs->cache = (bs->cache << 8) | a_byte;
bs->head += 8;
}
// bring the required bits down and truncate
if ((shift = bs->head - n) > 0)
res = bs->cache >> shift;
else
res = bs->cache;
// mask out required bits
if (n < 32)
res &= (1 << n) - 1;
bs->head = shift;
return res;
}
static bool
nal_bs_eos(nal_bitstream *bs)
{
return (bs->data >= bs->end) && (bs->head == 0);
}
// read unsigned Exp-Golomb code
static int
nal_bs_read_ue(nal_bitstream *bs)
{
int i = 0;
while (nal_bs_read(bs, 1) == 0 && !nal_bs_eos(bs) && i < 32)
i++;
return ((1 << i) - 1 + nal_bs_read(bs, i));
}
typedef struct
{
int profile_idc;
int level_idc;
int sps_id;
int chroma_format_idc;
int separate_colour_plane_flag;
int bit_depth_luma_minus8;
int bit_depth_chroma_minus8;
int qpprime_y_zero_transform_bypass_flag;
int seq_scaling_matrix_present_flag;
int log2_max_frame_num_minus4;
int pic_order_cnt_type;
int log2_max_pic_order_cnt_lsb_minus4;
int max_num_ref_frames;
int gaps_in_frame_num_value_allowed_flag;
int pic_width_in_mbs_minus1;
int pic_height_in_map_units_minus1;
int frame_mbs_only_flag;
int mb_adaptive_frame_field_flag;
int direct_8x8_inference_flag;
int frame_cropping_flag;
int frame_crop_left_offset;
int frame_crop_right_offset;
int frame_crop_top_offset;
int frame_crop_bottom_offset;
} sps_info_struct;
static void
parseh264_sps(uint8_t *sps, uint32_t sps_size, int *level, int *profile, bool *interlaced, int32_t *max_ref_frames)
{
nal_bitstream bs;
sps_info_struct sps_info = {0};
nal_bs_init(&bs, sps, sps_size);
sps_info.profile_idc = nal_bs_read(&bs, 8);
nal_bs_read(&bs, 1); // constraint_set0_flag
nal_bs_read(&bs, 1); // constraint_set1_flag
nal_bs_read(&bs, 1); // constraint_set2_flag
nal_bs_read(&bs, 1); // constraint_set3_flag
nal_bs_read(&bs, 4); // reserved
sps_info.level_idc = nal_bs_read(&bs, 8);
sps_info.sps_id = nal_bs_read_ue(&bs);
if (sps_info.profile_idc == 100 ||
sps_info.profile_idc == 110 ||
sps_info.profile_idc == 122 ||
sps_info.profile_idc == 244 ||
sps_info.profile_idc == 44 ||
sps_info.profile_idc == 83 ||
sps_info.profile_idc == 86)
{
sps_info.chroma_format_idc = nal_bs_read_ue(&bs);
if (sps_info.chroma_format_idc == 3)
sps_info.separate_colour_plane_flag = nal_bs_read(&bs, 1);
sps_info.bit_depth_luma_minus8 = nal_bs_read_ue(&bs);
sps_info.bit_depth_chroma_minus8 = nal_bs_read_ue(&bs);
sps_info.qpprime_y_zero_transform_bypass_flag = nal_bs_read(&bs, 1);
sps_info.seq_scaling_matrix_present_flag = nal_bs_read (&bs, 1);
if (sps_info.seq_scaling_matrix_present_flag)
{
/* TODO: unfinished */
}
}
sps_info.log2_max_frame_num_minus4 = nal_bs_read_ue(&bs);
if (sps_info.log2_max_frame_num_minus4 > 12)
{ // must be between 0 and 12
return;
}
sps_info.pic_order_cnt_type = nal_bs_read_ue(&bs);
if (sps_info.pic_order_cnt_type == 0)
{
sps_info.log2_max_pic_order_cnt_lsb_minus4 = nal_bs_read_ue(&bs);
}
else if (sps_info.pic_order_cnt_type == 1)
{ // TODO: unfinished
/*
delta_pic_order_always_zero_flag = gst_nal_bs_read (bs, 1);
offset_for_non_ref_pic = gst_nal_bs_read_se (bs);
offset_for_top_to_bottom_field = gst_nal_bs_read_se (bs);
num_ref_frames_in_pic_order_cnt_cycle = gst_nal_bs_read_ue (bs);
for( i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++ )
offset_for_ref_frame[i] = gst_nal_bs_read_se (bs);
*/
}
sps_info.max_num_ref_frames = nal_bs_read_ue(&bs);
sps_info.gaps_in_frame_num_value_allowed_flag = nal_bs_read(&bs, 1);
sps_info.pic_width_in_mbs_minus1 = nal_bs_read_ue(&bs);
sps_info.pic_height_in_map_units_minus1 = nal_bs_read_ue(&bs);
sps_info.frame_mbs_only_flag = nal_bs_read(&bs, 1);
if (!sps_info.frame_mbs_only_flag)
sps_info.mb_adaptive_frame_field_flag = nal_bs_read(&bs, 1);
sps_info.direct_8x8_inference_flag = nal_bs_read(&bs, 1);