-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathread_avi.m
2263 lines (2072 loc) · 90.3 KB
/
read_avi.m
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
function [o1, o2, o3, o4, o5] = read_avi( ret_val, varargin )
% readAvi
% Reads an uncompressed AVI file of a variety of formats, including
% the following:
% 10-bit : uyvy : yuy2 : yv12 : rgb
% If FILENAME does not include an extension, then '.avi' will be used.
% SYNTAX
% [info] = read_avi('Info',filename);
% [c1,c2,c3] = read_avi(color_out,filename);
% [...] = read_avi(...,'flag',...);
% DESCRIPTION
% [info] = read_avi('Info',filename);
% returns only a struct, containing information about the file.
% This struct can then be passed as an argument to this function
% preceded by the 'struct' flag, and the file will be read.
% [c1,c2,c3] = read_avi(color_out,filename);
% returns the color components of the frames read in from the file.
% The color components will depend on color_out. If no frames are
% requested in particular, only the first frame is read.
% [...] = read_avi(...,'Flag',...);
% designates a flag to be set inside the function. See below for a
% complete list of possible flags.
% INPUT ARGUMENTS
% color_out >
% 'Info' -- return listing of header information (see aviinfo).
% 'RGB' -- return image planes in the RGB colorspace.
% 'YCbCr' -- return image planes in the YCbCr colorspace.
%
% filename >
% Avi file to be opened. If the 'struct' flag has
% already been given, do NOT also give a filename
%
% flag >
% 'struct', avi_struct A struct returned by aviinfo or by this
% function with the 'Info' property.
% 'sroi',top,left,bottom,right, Spatial region of interest. By
% default, all of each image is
% returned.
% 'frames',start,stop, Specify the first and last frames,
% inclusive, to be read ('start' and 'stop').
% By default, read first frame.
% '128' Subtract 128 from all Cb and Cr values. By
% default, Cb and Cr values are left in the
% [0..255] range.
% 'interp' Linearly interpolate Cb and Cr values. By default,
% color planes are pixel replicated. Note:
% Interpolation is slow. Only implemented for
% YUV colorspaces excepting YV12.
% 'audio',['frames' or 'seconds'], start, stop
% Request audio be returned if it exists. If 'frames' are
% requested, the audio for the given frames [1..NumFrames]
% will be returned. If 'seconds' are requested, audio with
% the given duration [0..TotalTime) will be returned. Feel
% free to request more than is in the file; I handle it :)
% OUTPUT ARGUMENTS
% c1 >
% Depending on the color_out property, could be Info if 'Info', Y if
% 'YCbCr', or R if 'RGB'.
%
% c2, c3 >
% Depending on the color_out property, could be Cb and Cr if 'YCbCr'
% or G and B if 'RGB'.
%
% c4 >
% If audio is requested and exists, this is the raw audio data,
% separated by channels.
%
% c5 >
% if audio is requested and exists, this is the Audio Rate.
% EXAMPLES
%---[info] = read_avi('Info','twocops.avi');
%---[r,g,b] = read_avi('RGB','twocops.avi','frames',1,30);
%---[y,cb,cr] = read_avi('YCbCr','twocops.avi','frames',61,90,'128');
%---info = aviinfo('my.avi');
% [r, g, b] = read_avi('RGB', 'struct', info);
%---[y,cb,cr,aud,rate] = read_avi('YCbCr','my.avi','audio','seconds',0,5);
% NOTES
% When reading files with the YV12 fourcc, the cb and cr color
% components will be extrapolated to fit the Y component matrix size.
% The current extrapolation algorithm simply copies the cb and cr
% values. A better implementation might include a bi-linear
% interpolation.
% SIGNATURE
% Programmer: Zebulon Fross
% Version: 08/10/2010
%
% Initialization
is_whole_image = 1;
frame_start = 1;
frame_stop = 1;
audio_start = 0;
audio_stop = 0;
used_frames = 0;
sroi = [];
is_sub128 = 0;
is_interp = 0;
ret_info = 0;
ret_ycbcr = 1;
% Parse return information type flag
if strcmpi(ret_val,'info')
ret_info = 1;
elseif strcmpi(ret_val,'RGB')
ret_ycbcr = 0;
elseif ~strcmpi(ret_val,'YCbCr')
error('Return type flag not recognized');
end
persistent info;
% Validate input/output.
error(nargoutchk(0,5,nargout));
error(nargchk(2,19,nargin));
try
cnt=1;
while cnt <= length(varargin),
% argin_type = 1 if parsing input option
argin_type = 1;
if ~ischar(varargin{cnt}),
error('parameter not recognized');
end
if strcmpi(varargin(cnt),'struct') == 1,
info = varargin{cnt+1};
cnt = cnt + 2;
elseif strcmpi(varargin(cnt),'sroi') == 1,
sroi.top = varargin{cnt+1};
sroi.left = varargin{cnt+2};
sroi.bottom = varargin{cnt+3};
sroi.right = varargin{cnt+4};
is_whole_image = 0;
cnt = cnt + 5;
elseif strcmpi(varargin(cnt),'frames') == 1,
frame_start = varargin{cnt+1};
frame_stop = varargin{cnt+2};
cnt = cnt + 3;
elseif strcmp(varargin(cnt),'128') == 1,
is_sub128 = 1;
cnt = cnt + 1;
if ~ret_ycbcr,
error('RGB and ''128'' flag are incompatible');
end
elseif strcmpi(varargin(cnt),'interp') == 1,
is_interp = 1;
cnt = cnt + 1;
elseif strcmpi(varargin(cnt),'audio') == 1,
cnt = cnt + 1;
if strcmpi(varargin(cnt),'frames') == 1,
used_frames = 1;
end
audio_start = varargin{cnt+1};
audio_stop = varargin{cnt+2};
cnt = cnt + 3;
else
% assume file name is given
% argin_type = 0, means reading an AVI file structure
argin_type = 0;
filename = varargin{cnt};
[~,~,ext] = fileparts(filename);
if isempty(ext)
filename = strcat(filename,'.avi');
end
new_dir = dir(filename);
if isempty(info) || ...
~strcmp(info.Filename, filename) || ...
~strcmp(info.FileModDate, new_dir.date) || ...
~eq(info.FileSize, new_dir.bytes)
%this alternate function provides bit data about the avi
%which is not provided in the current matlab implementation
info = view_alt_aviinfo(filename);
end
cnt = cnt + 1;
end
end
catch e
fprintf('Reading video file %s\n', filename);
if argin_type
error(e.identifier, ...
'Unable to parse input arguments. Please check calling syntax for function read_avi.');
else
error(e.identifier, ...
'Unable read AVI file header information. Please check file structure with another program.');
end
end
% if frames were given for audio, convert frames to seconds
if used_frames == 1,
audio_start = (audio_start-1)/info.FramesPerSecond;
audio_stop = audio_stop/info.FramesPerSecond;
end
% check for invalid audio request
if (audio_stop < audio_start)
error('MATLAB:readavialt', 'invalid audio chunk request');
end
if ret_info == 1
o1 = info;
return ;
end
% TODO: Is this correct?
if ispc
file = fopen(info.Filename, 'r', 'l');
else
file = fopen(info.Filename, 'r', 'b');
end
assert(file >= 0);
% ensure frame request is valid
if frame_start <= 0 || frame_start > info.NumFrames
error('frame numbers to read must be valid');
end
if frame_stop < frame_start || frame_stop > info.NumFrames
error('frame numbers to read must be valid');
end
if is_whole_image,
o1=zeros(info.Height,...
info.Width,...
frame_stop-frame_start+1,'single');
else
o1=zeros(sroi.bottom-sroi.top+1,...
sroi.right-sroi.left+1,...
frame_stop-frame_start+1,'single');
end
if nargout > 1
o2=o1;
o3=o1;
o4=[];
o5= 0;
end
%% gather video data -------------------------------------------------
out_pos = 1;
% read in the requested frames
for ind = frame_start:frame_stop
% seek to position of frame
fseek(file, info.vidFrames(1, ind), -1);
if ( strcmp(info.ColorType, 'UYVY') )
if (strcmpi(info.Codec, 'UYVY') || ...
strcmpi(info.Codec, 'ffds') || ...
strcmpi(info.Codec, 'HDYC') || ...
strcmpi(info.Codec, 'DIB '))
[y,cb,cr] = read_uyvy_frame(file, is_whole_image, ...
sroi, is_interp, ...
info.Height, info.Width);
% % One fluke AVI file had upsidedown images, and so needed
% % images to be flipped. None of the ITS datasets have this
% % problem, so this appears to have been a mistake.
% if (strcmpi(info.Codec, 'DIB '))
% % I am still not sure how to interpret DIB files
% y = flipud( y);
% cb = flipud(cb);
% cr = flipud(cr);
% end
elseif (strcmpi(info.Codec, 'v210'))
[y, cb, cr] = ...
read_10bit_uyvy(file, is_whole_image, ...
sroi, is_interp, ...
info.Height, info.Width);
elseif (strcmpi(info.Codec, 'yuy2'))
[y,cb,cr] = read_yuyv_frame(file, is_whole_image, ...
sroi, is_interp, ...
info.Height, info.Width);
elseif (strcmpi(info.Codec, 'yv12'))
[y, cb, cr] = read_yv12_frame(file, is_whole_image, ...
sroi, is_interp, ...
info.Height, info.Width);
% if the codec is not one of the previous, we will resort to
% the compressed file reader
else
% this piece of code is experimental for reading
% compressed avi files. The mex file does not work on
% 64-bit machines. On 32-bit machines, the program
% returns slightly-faulty data.
error('could not interpet avi codec');
% try
% eStr = ['The mex function could not read this AVI ' ...
% 'file. This could be because the mex function' ...
% ' is not available or because the file''s ' ...
% 'codec is not installed on this system.'];
% % determine the correct mex function to call
% if ( strcmp(computer, 'PCWIN') )
% [r, g, b] = read_compressed_avi_32(info.Filename, ...
% ind, ...
% info.Height, ...
% info.Width);
% else
% eStr = ['Your operating system is not supported by' ...
% ' our mex function. Please run this again ' ...
% 'on a 32-bit Windows machine.'];
% error(eStr);
% end
% [y, cb, cr] ...
% = rgb2ycbcr_double(double( r ), ...
% double( g ), ...
% double( b ));
% catch e
% rethrow(e);
% end
end
% append y, cb, and cr to output variables
if ret_ycbcr,
o1(:,:,out_pos) = y;
if nargout > 1,
if is_sub128
cb = single(cb)-128;
cr = single(cr)-128;
end
o2(:,:,out_pos) = cb;
o3(:,:,out_pos) = cr;
end
else
[o1(:,:,out_pos),o2(:,:,out_pos),o3(:,:,out_pos)] ...
= ycbcr2rgb_double(single(y),...
single(cb),...
single(cr));
end
elseif strcmp(info.ColorType, 'RGB'),
if info.BitDepth == 24,
[r,g,b] = read_rgb24_frame(file, is_whole_image, ...
sroi, info.Height, ...
info.Width);
elseif info.BitDepth == 32,
[r,g,b] ...
= read_rgb32_frame(file, is_whole_image, sroi, ...
info.Height, ...
info.Width);
% if the codec is not one of the previous, we will resort to
% the compressed file reader
else
% this piece of code is experimental for reading
% compressed avi files. The mex file does not work on
% 64-bit machines. On 32-bit machines, the program
% returns slightly-faulty data.
error('could not interpet avi codec');
% try
% eStr = ['The mex function could not read this AVI ' ...
% 'file. This could be because the mex function' ...
% ' is not available or because the file''s ' ...
% 'codec is not installed on this system.'];
% % determine the correct mex function to call
% if ( strcmp(computer, 'PCWIN') )
% [r, g, b] = read_compressed_avi_32(info.Filename, ...
% ind, ...
% info.Height, ...
% info.Width);
% else
% eStr = ['Your operating system is not supported by' ...
% ' our mex function. Please run this again ' ...
% 'on a 32-bit Windows machine.'];
% error(eStr);
% end
% catch e
% rethrow(e);
% end
end
if ~ret_ycbcr,
o1(:,:,out_pos) = r;
o2(:,:,out_pos) = g;
o3(:,:,out_pos) = b;
else
[y, cb, cr] = rgb2ycbcr_double(r,g,b);
o1(:,:,out_pos) = y;
if nargout > 1,
if is_sub128
cb = single(cb)-128;
cr = single(cr)-128;
end
o2(:,:,out_pos) = cb;
o3(:,:,out_pos) = cr;
end
end
else
error('unsupported input format');
end
out_pos = out_pos + 1;
end
%% only return audio if requested and if it exists -------------------
if audio_stop > 0 && isfield(info, 'audFrames')
data = [];
% determine the datatype to read in
BytesPerSample = info.BitsPerSample/8;
if (BytesPerSample == 1),
dtype='uchar'; % unsigned 8-bit
elseif (BytesPerSample == 2),
dtype='int16'; % signed 16-bit
elseif (BytesPerSample == 3)
dtype='bit24'; % signed 24-bit
elseif (BytesPerSample == 4),
% 32-bit 16.8 float (type 1 - 32-bit)
if (strcmpi(info.AudioFormat, 'Format # 0x1'))
dtype = 'bit32'; %signed 32-bit
% 32-bit normalized floating point
elseif (strcmpi(info.AudioFormat, 'Format # 0x3'))
dtype = 'float'; % floating point
elseif (strcmpi(info.AudioFormat, 'Format # 0xFFFE'))
%32 Bit data with either integer or floating point numbers. Use
%info.SubFormat to determine whether or not the audio data is
%32 bit or 32 bit floating point. Also, a check will still be
%in place below just in case this information does not exist or
%is something "weird".
if(info.SubFormat == 1)
%PCM data is contained, meaning that the data is 32 bit,
%not floating point.
dtype = 'bit32'; %signed 32-bit
elseif(info.SubFormat == 3)
%IEEE floating point data is contained, meaning that the
%data is 32 bit floating point numbers.
dtype = 'float'; % floating point
else
%The SubFormat is formatted in a way that isn't checked by
%this program, it will be assumed that 32 bit will be used.
dtype = 'bit32'; %signed 32-bit
warning('SubFormat not formatted in a way this program understands. Audio may be incorrect.');
end
else
dtype = 'bit32';
end
end
skip_samples = uint32(audio_start*info.BytesPerSec/BytesPerSample);
stop_samples = uint32(audio_stop*info.BytesPerSec/BytesPerSample);
total_samples = (stop_samples - skip_samples)/info.NumAudioChannels;
sample_count = 0;
if sample_count < skip_samples
ind = 0;
else
ind = 1;
end
% determine where to start reading the audio by skipping parts
total_samples_thus_far = 0;
while sample_count < skip_samples
ind = ind + 1;
sz = info.audFrames(2, ind);
% Total samples in a chunk = size of chunk / Bytes per sample
TotalSamples = floor(sz/BytesPerSample);
sample_count = sample_count + TotalSamples;
total_samples_thus_far = total_samples_thus_far + TotalSamples;
end
% determine how much needs to be skipped in the initial chunk
% seek to initial chunk and skip necessary samples
if(ind == 1)
fseek(file, info.audFrames(1, ind), -1);
fseek(file, floor(double(skip_samples)*BytesPerSample), 0);
if(info.NumAudioChannels > 2)
%Get a Reference Size to know how many samples you need to
%actually have.
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
samples_needed = size(data,2);
%Clear Data
data = [];
%Now grab all the data in the full chunk and chop off the not
%needed data in the beginning.
fseek(file, info.audFrames(1, ind), -1);
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
data = data(:,(size(data,2)-samples_needed+1):size(data,2));
if(size(data,2) ~= samples_needed)
%These two HAVE to be equal for the seeking through the
%audio to be correct.
error('Seeking through Audio data has failed!');
end
ind = ind + 1;
try
fseek(file, info.audFrames(1, ind), -1);
catch
%No more audio in the file, it was all read in. That's
%fine, this will be taken care of down below.
end
end
else
%Re-adjust skip_samples since we are not starting at the beginning
%of the clip.
skip_samples_in_file = skip_samples - (total_samples_thus_far - TotalSamples);
if(skip_samples < 0)
error('Skip Samples was not calculated correctly')
end
fseek(file, info.audFrames(1, ind), -1);
fseek(file, floor(double(skip_samples_in_file)*BytesPerSample), 0);
%Ok, so when 6 channel audio is present, seeking in the file messes
%up the order of the audio channels for the first sample that is
%read in. Therefore, this program will read the whole chunk in and
%then only store the number of samples that is needed.
if(info.NumAudioChannels > 2)
%Get a Reference Size to know how many samples you need to
%actually have.
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
samples_needed = size(data,2);
%Clear Data
data = [];
%Now grab all the data in the full chunk and chop off the not
%needed data in the beginning.
fseek(file, info.audFrames(1, ind), -1);
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
data = data(:,(size(data,2)-samples_needed+1):size(data,2));
if(size(data,2) ~= samples_needed)
%These two HAVE to be equal for the seeking through the
%audio to be correct.
error('Seeking through Audio data has failed!');
end
ind = ind + 1;
try
fseek(file, info.audFrames(1, ind), -1);
catch
%No more audio in the file, it was all read in. That's
%fine, this will be taken care of down below.
end
end
end
% while we haven't read in all that has been requested
while size(data, 2) < total_samples
if(isempty(data))
%Dividing has to do with staying within the audio region!
%Otherwise, it goes outside of the audio region and noise
%is added.
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
else
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
end
ind = ind + 1;
% break out if there is no more audio to read. We won't
% penalize for users requesting too much.
if (ind > size(info.audFrames, 2))
break;
end
fseek(file, info.audFrames(1, ind), -1);
end
%Chop off extra data before scaling occurs. This has been moved from
%the bottom of this function to here. This is because if the program
%read to much and left the audio section of the data, noise enters the
%data. This noise needs to be removed before the data can be
%normalized. Thus, this is what is accomplished here.
if size(data, 2) < total_samples
total_samples = size(data, 2);
end
% truncate the output just in case we read too much
data = data(:, 1:total_samples);
data = data';
% Normalize data range: min will hit -1, max will not quite hit +1.
if BytesPerSample==1,
data = (data-128)/128; % [-1,1)
elseif BytesPerSample==2,
data = data/32768; % [-1,1)
elseif BytesPerSample==3,
data = data/(2^23); % [-1,1)
elseif BytesPerSample==4,
% Type 3 32-bit is already normalized
if(~strcmpi(info.AudioFormat, 'Format # 0x3') && info.SubFormat ~= 3)
data = data/(2^31); % [-1,1)
end
end
%Only needed for 32 bit audio - This checks if the 32 bit audio should
%be int32 (default) or if it should be float 32 bit. While this can
%be known from the aviinfo function (info.AudioFormat = 0x3) it is
%unknown if the audio format is WAVE_FORMAT_EXTENSIBLE(0xfffe).
%Therefore, this needs to be checked, this function is responsible for
%checking. This also provides a "check" for info.SubFormat, just
%in case it was not formatted or not formatted correctly.
if(strcmpi(info.AudioFormat, 'Format # 0xFFFE') && (strcmpi(dtype,'bit32') || strcmpi(dtype,'float')))
if(max(max(isnan(data))) == 1) %The assumed format was not correct.
%32 bit float will be used
skip_samples = uint32(audio_start*info.BytesPerSec/BytesPerSample);
stop_samples = uint32(audio_stop*info.BytesPerSec/BytesPerSample);
total_samples = (stop_samples - skip_samples)/info.NumAudioChannels;
sample_count = 0;
if sample_count < skip_samples
ind = 0;
else
ind = 1;
end
% determine where to start reading the audio by skipping parts
total_samples_thus_far = 0;
while sample_count < skip_samples
ind = ind + 1;
sz = info.audFrames(2, ind);
% Total samples in a chunk = size of chunk / Bytes per sample
TotalSamples = floor(sz/BytesPerSample);
sample_count = sample_count + TotalSamples;
total_samples_thus_far = total_samples_thus_far + TotalSamples;
end
% determine how much needs to be skipped in the initial chunk
% seek to initial chunk and skip necessary samples
if(strcmpi(dtype,'bit32'))
data = [];
dtype = 'float';
else
data = [];
dtype = 'bit32';
end
if(ind == 1)
fseek(file, info.audFrames(1, ind), -1);
fseek(file, floor(double(skip_samples)*BytesPerSample), 0);
if(info.NumAudioChannels > 2)
%Get a Reference Size to know how many samples you need to
%actually have.
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
samples_needed = size(data,2);
%Clear Data
data = [];
%Now grab all the data in the full chunk and chop off the not
%needed data in the beginning.
fseek(file, info.audFrames(1, ind), -1);
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
data = data(:,(size(data,2)-samples_needed+1):size(data,2));
if(size(data,2) ~= samples_needed)
%These two HAVE to be equal for the seeking through the
%audio to be correct.
error('Seeking through Audio data has failed!');
end
ind = ind + 1;
try
fseek(file, info.audFrames(1, ind), -1);
catch
%No more audio in the file, it was all read in. That's
%fine, this will be taken care of down below.
end
end
else
%Re-adjust skip_samples since we are not starting at the beginning
%of the clip.
skip_samples_in_file = skip_samples - (total_samples_thus_far - TotalSamples);
if(skip_samples < 0)
error('Skip Samples was not calculated correctly')
end
fseek(file, info.audFrames(1, ind), -1);
fseek(file, floor(double(skip_samples_in_file)*BytesPerSample), 0);
%Ok, so when 6 channel audio is present, seeking in the file messes
%up the order of the audio channels for the first sample that is
%read in. Therefore, this program will read the whole chunk in and
%then only store the number of samples that is needed.
if(info.NumAudioChannels > 2)
%Get a Reference Size to know how many samples you need to
%actually have.
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
samples_needed = size(data,2);
%Clear Data
data = [];
%Now grab all the data in the full chunk and chop off the not
%needed data in the beginning.
fseek(file, info.audFrames(1, ind), -1);
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
data = data(:,(size(data,2)-samples_needed+1):size(data,2));
if(size(data,2) ~= samples_needed)
%These two HAVE to be equal for the seeking through the
%audio to be correct.
error('Seeking through Audio data has failed!');
end
ind = ind + 1;
try
fseek(file, info.audFrames(1, ind), -1);
catch
%No more audio in the file, it was all read in. That's
%fine, this will be taken care of down below.
end
end
end
% while we haven't read in all that has been requested
while size(data, 2) < total_samples
if(isempty(data))
%Dividing has to do with staying within the audio region!
%Otherwise, it goes outside of the audio region and noise
%is added.
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
else
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
end
ind = ind + 1;
% break out if there is no more audio to read. We won't
% penalize for users requesting too much.
if (ind > size(info.audFrames, 2))
break;
end
fseek(file, info.audFrames(1, ind), -1);
end
if size(data, 2) < total_samples
total_samples = size(data, 2);
end
% truncate the output just in case we read too much
data = data(:, 1:total_samples);
data = data';
if(strcmpi(dtype,'bit32'))
data = data/(2^31); % [-1,1)
end
else %Check the histogram of the audio output. If Gaussian in
%shape then everything is ok. If two big peaks, the wrong
%format was used. 32 bit float will be used.
two_peaks = 0;
peak_left = 0;
peak_right = 0;
%Obtain the histogram
max_chan = [0,0];
for i = 1:info.NumAudioChannels
%Make sure the channel is not just all zeros
temp = max(max(data(:,i)));
if(temp > max_chan(1,1))
max_chan(1,1) = temp;
max_chan(1,2) = i;
end
end
clear temp
temp = histc(data(:,max_chan(1,2)),[min(min(data)):.01:max(max(data))]);
%check if two peaks exist.
%Split the histogram into two parts (the peaks will be on
%either end of the spectrum if the wrong format was used.
temp1 = temp(1:round((size(temp,1))/4));
temp2 = temp(round(size(temp,1)*(3/4)):size(temp));
temp3 = temp(round(size(temp,1)*(1/4)):round(size(temp,1)*(3/4)));
%Set middle peak value for comparison
middle_peak = max(temp3);
%If a side peak is higher than the middle peak or is within 50%
%of the middle_peak in value, more than one peak exists.
if(max(temp1) > middle_peak || max(temp1) > (middle_peak - floor(middle_peak*.5)))
%A peak on the left side exists
peak_left = 1;
end
if(max(temp2) > middle_peak || max(temp2) > (middle_peak - floor(middle_peak*.5)))
%A peak on the right side exists
peak_right = 1;
end
if(peak_left == 1 && peak_right == 1)
%The wrong format was used!
two_peaks = 1;
display('32 Bit Floating Point Audio Has Been Detected');
elseif(peak_left == 1 || peak_right == 1)
%Only one peak exists which is strange
warning('Only one peak detected and its not centered! Audio may not be correct!');
end
if(two_peaks == 1)
%Audio format was wrong, use 32 bit floating point format.
skip_samples = uint32(audio_start*info.BytesPerSec/BytesPerSample);
stop_samples = uint32(audio_stop*info.BytesPerSec/BytesPerSample);
total_samples = (stop_samples - skip_samples)/info.NumAudioChannels;
sample_count = 0;
if sample_count < skip_samples
ind = 0;
else
ind = 1;
end
% determine where to start reading the audio by skipping parts
total_samples_thus_far = 0;
while sample_count < skip_samples
ind = ind + 1;
sz = info.audFrames(2, ind);
% Total samples in a chunk = size of chunk / Bytes per sample
TotalSamples = floor(sz/BytesPerSample);
sample_count = sample_count + TotalSamples;
total_samples_thus_far = total_samples_thus_far + TotalSamples;
end
% determine how much needs to be skipped in the initial chunk
% seek to initial chunk and skip necessary samples
if(strcmpi(dtype,'bit32'))
data = [];
dtype = 'float';
else
data = [];
dtype = 'bit32';
end
if(ind == 1)
fseek(file, info.audFrames(1, ind), -1);
fseek(file, floor(double(skip_samples)*BytesPerSample), 0);
if(info.NumAudioChannels > 2)
%Get a Reference Size to know how many samples you need to
%actually have.
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
samples_needed = size(data,2);
%Clear Data
data = [];
%Now grab all the data in the full chunk and chop off the not
%needed data in the beginning.
fseek(file, info.audFrames(1, ind), -1);
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
data = data(:,(size(data,2)-samples_needed+1):size(data,2));
if(size(data,2) ~= samples_needed)
%These two HAVE to be equal for the seeking through the
%audio to be correct.
error('Seeking through Audio data has failed!');
end
ind = ind + 1;
try
fseek(file, info.audFrames(1, ind), -1);
catch
%No more audio in the file, it was all read in. That's
%fine, this will be taken care of down below.
end
end
else
%Re-adjust skip_samples since we are not starting at the beginning
%of the clip.
skip_samples_in_file = skip_samples - (total_samples_thus_far - TotalSamples);
if(skip_samples < 0)
error('Skip Samples was not calculated correctly')
end
fseek(file, info.audFrames(1, ind), -1);
fseek(file, floor(double(skip_samples_in_file)*BytesPerSample), 0);
%Ok, so when 6 channel audio is present, seeking in the file messes
%up the order of the audio channels for the first sample that is
%read in. Therefore, this program will read the whole chunk in and
%then only store the number of samples that is needed.
if(info.NumAudioChannels > 2)
%Get a Reference Size to know how many samples you need to
%actually have.
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
samples_needed = size(data,2);
%Clear Data
data = [];
%Now grab all the data in the full chunk and chop off the not
%needed data in the beginning.
fseek(file, info.audFrames(1, ind), -1);
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
data = data(:,(size(data,2)-samples_needed+1):size(data,2));
if(size(data,2) ~= samples_needed)
%These two HAVE to be equal for the seeking through the
%audio to be correct.
error('Seeking through Audio data has failed!');
end
ind = ind + 1;
try
fseek(file, info.audFrames(1, ind), -1);
catch
%No more audio in the file, it was all read in. That's
%fine, this will be taken care of down below.
end
end
end
% while we haven't read in all that has been requested
while size(data, 2) < total_samples
if(isempty(data))
%Dividing has to do with staying within the audio region!
%Otherwise, it goes outside of the audio region and noise
%is added.
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
else
data = [data fread(file, [info.NumAudioChannels, ...
floor((info.audFrames(1,ind)+info.audFrames(2,ind)-ftell(file))...
/(BytesPerSample*info.NumAudioChannels))], dtype)];
end
ind = ind + 1;
% break out if there is no more audio to read. We won't
% penalize for users requesting too much.
if (ind > size(info.audFrames, 2))
break;
end
fseek(file, info.audFrames(1, ind), -1);
end
if size(data, 2) < total_samples
total_samples = size(data, 2);
end
% truncate the output just in case we read too much
data = data(:, 1:total_samples);
data = data';
if(strcmpi(dtype,'bit32'))
data = data/(2^31); % [-1,1)
end
end
end
end
% return only what was requested
o4 = data;
if size(o4, 1) < total_samples
total_samples = size(o4, 1);
end
% truncate the output just in case we read too much
o4 = o4(1:total_samples, :);
% give the user the audio rate
o5 = info.AudioRate;
if(info.BitsPerSample == 32)
%Need to let the AVI write function know whether the 32 bit audio
%is floating point or not. This information will be placed in o5
%which displays the audio rate. This was chosen because it is the
%only returnable item that doesn't contain video or audio data.
if(strcmpi(dtype,'bit32'))
%Its 32 bit (not floating point)
o5 = [info.AudioRate, 0];
else
%Its 32 bit floating point
o5 = [info.AudioRate, 1];
end
end
end
fclose(file);
return ;
%% -----------------------------------------------------------------------
function [r,g,b] ...
= read_rgb24_frame(fid, is_whole_image, sroi, num_rows, num_cols)
% Read one RGB24 frame
% read in image
temp = readAndCheck(fid, [3*num_cols,num_rows], '*uint8');
% flip.
temp = temp(:,num_rows:-1:1);
% pick off the planes
temp = reshape(temp', num_rows, 3, num_cols);
b = single(squeeze(temp(:,1,:)));
g = single(squeeze(temp(:,2,:)));
r = single(squeeze(temp(:,3,:)));
if ~is_whole_image,
r = r(sroi.top:sroi.bottom, sroi.left:sroi.right);
g = g(sroi.top:sroi.bottom, sroi.left:sroi.right);
b = b(sroi.top:sroi.bottom, sroi.left:sroi.right);
end
return ;
%% -----------------------------------------------------------------------