download getid3.mp3.php
Language: PHP
LOC: 898
Project Info
Tunez
Server: SourceForge
Type: cvs
...tunez\tunez\tunez\html\id3\
   getid3.aac.php
   getid3.ape.php
   getid3.asf.php
   getid3.au.php
   getid3.avr.php
   getid3.bmp.php
   getid3.bonk.php
   getid3.check.php
   getid3.exe.php
   getid3.flac.php
   getid3.frames.php
   getid3.functions.php
   getid3.getimagesize.php
   getid3.gif.php
   getid3.id3v1.php
   getid3.id3v2.php
   getid3.iso.php
   getid3.jpg.php
   getid3.la.php
   getid3.lookup.php
   getid3.lpac.php
   getid3.lyrics3.php
   getid3.matroska.php
   getid3.midi.php
   getid3.mod.php
   getid3.monkey.php
   getid3.mp3.php
   getid3.mpc.php
   getid3.mpeg.php
   getid3.nsv.php
   getid3.ogg.php
   getid3.ogginfo.php
   getid3.optimfrog.php
   getid3.php
   getid3.png.php
   getid3.putid3.php
   getid3.quicktime.php
   getid3.rar.php
   getid3.real.php
   getid3.rgad.php
   getid3.riff.php
   getid3.shorten.php
   getid3.swf.php
   getid3.thumbnail.php
   getid3.voc.php
   getid3.vqf.php
   getid3.write.php
   getid3.zip.php

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org>               //
//  available at http://getid3.sourceforge.net                ///
//            or http://www.getid3.org                        ///
/////////////////////////////////////////////////////////////////
//                                                             //
// getid3.mp3.php - part of getID3()                           //
// See getid3.readme.txt for more details                      //
//                                                             //
/////////////////////////////////////////////////////////////////

// number of frames to scan to determine if MPEG-audio sequence is valid
// Lower this number to 5-20 for faster scanning
// Increase this number to 50+ for most accurate detection of valid VBR/CBR
// mpeg-audio streams
define('MPEG_VALID_CHECK_FRAMES', 35);

function getMP3headerFilepointer(&$fd, &$ThisFileInfo) {

	getOnlyMPEGaudioInfo($fd, $ThisFileInfo, $ThisFileInfo['avdataoffset']);

	if (isset($ThisFileInfo['mpeg']['audio']['bitrate_mode'])) {
		$ThisFileInfo['audio']['bitrate_mode'] = strtolower($ThisFileInfo['mpeg']['audio']['bitrate_mode']);
	}

	if (((isset($ThisFileInfo['id3v2']) && ($ThisFileInfo['avdataoffset'] > $ThisFileInfo['id3v2']['headerlength'])) || (!isset($ThisFileInfo['id3v2']) && ($ThisFileInfo['avdataoffset'] > 0)))) {

		$ThisFileInfo['warning'] .= "\n".'Unknown data before synch ';
		if (isset($ThisFileInfo['id3v2']['headerlength'])) {
			$ThisFileInfo['warning'] .= '(ID3v2 header ends at '.$ThisFileInfo['id3v2']['headerlength'].', then '.($ThisFileInfo['avdataoffset'] - $ThisFileInfo['id3v2']['headerlength']).' bytes garbage, ';
		} else {
			$ThisFileInfo['warning'] .= '(should be at beginning of file, ';
		}
		$ThisFileInfo['warning'] .= 'synch detected at '.$ThisFileInfo['avdataoffset'].')';
		if ($ThisFileInfo['audio']['bitrate_mode'] == 'cbr') {
			if (!empty($ThisFileInfo['id3v2']['headerlength']) && (($ThisFileInfo['avdataoffset'] - $ThisFileInfo['id3v2']['headerlength']) == $ThisFileInfo['mpeg']['audio']['framelength'])) {
				$ThisFileInfo['warning'] .= '. This is a known problem with some versions of LAME (3.91, 3.92) DLL in CBR mode.';
				$ThisFileInfo['audio']['codec'] = 'LAME';
			} elseif (empty($ThisFileInfo['id3v2']['headerlength']) && ($ThisFileInfo['avdataoffset'] == $ThisFileInfo['mpeg']['audio']['framelength'])) {
				$ThisFileInfo['warning'] .= '. This is a known problem with some versions of LAME (3.91, 3.92) DLL in CBR mode.';
				$ThisFileInfo['audio']['codec'] = 'LAME';
			}
		}

	}

	if (isset($ThisFileInfo['mpeg']['audio']['layer']) && ($ThisFileInfo['mpeg']['audio']['layer'] == 'II')) {
		$ThisFileInfo['audio']['dataformat'] = 'mp2';
	} elseif (isset($ThisFileInfo['mpeg']['audio']['layer']) && ($ThisFileInfo['mpeg']['audio']['layer'] == 'I')) {
		$ThisFileInfo['audio']['dataformat'] = 'mp1';
	}
	if ($ThisFileInfo['fileformat'] == 'mp3') {
		switch ($ThisFileInfo['audio']['dataformat']) {
			case 'mp1':
			case 'mp2':
			case 'mp3':
				$ThisFileInfo['fileformat'] = $ThisFileInfo['audio']['dataformat'];
				break;

			default:
				$ThisFileInfo['warning'] .= "\n".'Expecting [audio][dataformat] to be mp1/mp2/mp3 when fileformat == mp3, [audio][dataformat] actually "'.$ThisFileInfo['audio']['dataformat'].'"';
				break;
		}
	}

	if (empty($ThisFileInfo['fileformat'])) {
		$ThisFileInfo['error'] .= "\n".'Synch not found';
		unset($ThisFileInfo['fileformat']);
		unset($ThisFileInfo['audio']['bitrate_mode']);
		unset($ThisFileInfo['avdataoffset']);
		unset($ThisFileInfo['avdataend']);
		return false;
	}

	$ThisFileInfo['mime_type']         = 'audio/mpeg';
	$ThisFileInfo['audio']['lossless'] = false;

	// Calculate playtime
	if (!isset($ThisFileInfo['playtime_seconds']) && isset($ThisFileInfo['audio']['bitrate']) && ($ThisFileInfo['audio']['bitrate'] > 0)) {
		$ThisFileInfo['playtime_seconds'] = ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']) * 8 / $ThisFileInfo['audio']['bitrate'];
	}

	if (isset($ThisFileInfo['mpeg']['audio']['LAME'])) {
		$ThisFileInfo['audio']['codec'] = 'LAME';
		if (!empty($ThisFileInfo['mpeg']['audio']['LAME']['long_version'])) {
			$ThisFileInfo['audio']['encoder'] = trim($ThisFileInfo['mpeg']['audio']['LAME']['long_version']);
		}
	}

	return true;
}


function decodeMPEGaudioHeader($fd, $offset, &$ThisFileInfo, $recursivesearch=true, $ScanAsCBR=false, $FastMPEGheaderScan=false, $allowBitrateMode15=false) {
	static $MPEGaudioVersionLookup;
	static $MPEGaudioLayerLookup;
	static $MPEGaudioBitrateLookup;
	static $MPEGaudioFrequencyLookup;
	static $MPEGaudioChannelModeLookup;
	static $MPEGaudioModeExtensionLookup;
	static $MPEGaudioEmphasisLookup;
	if (empty($MPEGaudioVersionLookup)) {
		$MPEGaudioVersionLookup       = MPEGaudioVersionArray();
		$MPEGaudioLayerLookup         = MPEGaudioLayerArray();
		$MPEGaudioBitrateLookup       = MPEGaudioBitrateArray();
		$MPEGaudioFrequencyLookup     = MPEGaudioFrequencyArray();
		$MPEGaudioChannelModeLookup   = MPEGaudioChannelModeArray();
		$MPEGaudioModeExtensionLookup = MPEGaudioModeExtensionArray();
		$MPEGaudioEmphasisLookup      = MPEGaudioEmphasisArray();
	}

	if ($offset >= $ThisFileInfo['avdataend']) {
		$ThisFileInfo['error'] .= "\n".'end of file encounter looking for MPEG synch';
		return false;
	}
	fseek($fd, $offset, SEEK_SET);
	$headerstring = fread($fd, 1441); // worse-case max length = 32kHz @ 320kbps layer 3 = 1441 bytes/frame

	// MP3 audio frame structure:
	// $aa $aa $aa $aa [$bb $bb] $cc...
	// where $aa..$aa is the four-byte mpeg-audio header (below)
	// $bb $bb is the optional 2-byte CRC
	// and $cc... is the audio data

	$head4 = substr($headerstring, 0, 4);

	static $MPEGaudioHeaderDecodeCache = array();
	if (isset($MPEGaudioHeaderDecodeCache[$head4])) {
		$MPEGheaderRawArray = $MPEGaudioHeaderDecodeCache[$head4];
	} else {
		$MPEGheaderRawArray = MPEGaudioHeaderDecode($head4);
		$MPEGaudioHeaderDecodeCache[$head4] = $MPEGheaderRawArray;
	}

	static $MPEGaudioHeaderValidCache = array();

	// Not in cache
	if (!isset($MPEGaudioHeaderValidCache[$head4])) {
		$MPEGaudioHeaderValidCache[$head4] = MPEGaudioHeaderValid($MPEGheaderRawArray);
	}

	if ($MPEGaudioHeaderValidCache[$head4]) {
		$ThisFileInfo['mpeg']['audio']['raw'] = $MPEGheaderRawArray;
	} else {
		$ThisFileInfo['error'] .= "\n".'Invalid MPEG audio header at offset '.$offset;
		return false;
	}

	if (!$FastMPEGheaderScan) {

		$ThisFileInfo['mpeg']['audio']['version']       = $MPEGaudioVersionLookup[$ThisFileInfo['mpeg']['audio']['raw']['version']];
		$ThisFileInfo['mpeg']['audio']['layer']         = $MPEGaudioLayerLookup[$ThisFileInfo['mpeg']['audio']['raw']['layer']];

		$ThisFileInfo['mpeg']['audio']['channelmode']   = $MPEGaudioChannelModeLookup[$ThisFileInfo['mpeg']['audio']['raw']['channelmode']];
		$ThisFileInfo['mpeg']['audio']['channels']      = (($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') ? 1 : 2);
		$ThisFileInfo['mpeg']['audio']['sample_rate']   = $MPEGaudioFrequencyLookup[$ThisFileInfo['mpeg']['audio']['version']][$ThisFileInfo['mpeg']['audio']['raw']['sample_rate']];
		$ThisFileInfo['mpeg']['audio']['protection']    = !$ThisFileInfo['mpeg']['audio']['raw']['protection'];
		$ThisFileInfo['mpeg']['audio']['private']       = (bool) $ThisFileInfo['mpeg']['audio']['raw']['private'];
		$ThisFileInfo['mpeg']['audio']['modeextension'] = $MPEGaudioModeExtensionLookup[$ThisFileInfo['mpeg']['audio']['layer']][$ThisFileInfo['mpeg']['audio']['raw']['modeextension']];
		$ThisFileInfo['mpeg']['audio']['copyright']     = (bool) $ThisFileInfo['mpeg']['audio']['raw']['copyright'];
		$ThisFileInfo['mpeg']['audio']['original']      = (bool) $ThisFileInfo['mpeg']['audio']['raw']['original'];
		$ThisFileInfo['mpeg']['audio']['emphasis']      = $MPEGaudioEmphasisLookup[$ThisFileInfo['mpeg']['audio']['raw']['emphasis']];

		$ThisFileInfo['audio']['channels']    = $ThisFileInfo['mpeg']['audio']['channels'];
		$ThisFileInfo['audio']['sample_rate'] = $ThisFileInfo['mpeg']['audio']['sample_rate'];

		if ($ThisFileInfo['mpeg']['audio']['protection']) {
			$ThisFileInfo['mpeg']['audio']['crc'] = BigEndian2Int(substr($headerstring, 4, 2));
		}

	}

	if ($ThisFileInfo['mpeg']['audio']['raw']['bitrate'] == 15) {
		// http://www.hydrogenaudio.org/?act=ST&f=16&t=9682&st=0
		$ThisFileInfo['warning'] .= "\n".'Invalid bitrate index (15), this is a known bug in free-format MP3s encoded by LAME v3.90 - 3.93.1';
		if ($allowBitrateMode15) {
			$ThisFileInfo['mpeg']['audio']['raw']['bitrate'] = 0;
		} else {
			return false;
		}
	}
	$ThisFileInfo['mpeg']['audio']['padding'] = (bool) $ThisFileInfo['mpeg']['audio']['raw']['padding'];
	$ThisFileInfo['mpeg']['audio']['bitrate'] = $MPEGaudioBitrateLookup[$ThisFileInfo['mpeg']['audio']['version']][$ThisFileInfo['mpeg']['audio']['layer']][$ThisFileInfo['mpeg']['audio']['raw']['bitrate']];

	if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') && ($offset == $ThisFileInfo['avdataoffset'])) {
		// only skip multiple frame check if free-format bitstream found at beginning of file
		// otherwise is quite possibly simply corrupted data
		$recursivesearch = false;
	}

	// For Layer II there are some combinations of bitrate and mode which are not allowed.
	if (!$FastMPEGheaderScan && ($ThisFileInfo['mpeg']['audio']['layer'] == 'II')) {

		$ThisFileInfo['audio']['dataformat'] = 'mp2';
		switch ($ThisFileInfo['mpeg']['audio']['channelmode']) {

			case 'mono':
				if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') || ($ThisFileInfo['mpeg']['audio']['bitrate'] <= 192)) {
					// these are ok
				} else {
					$ThisFileInfo['error'] .= "\n".$ThisFileInfo['mpeg']['audio']['bitrate'].'kbps not allowed in Layer II, '.$ThisFileInfo['mpeg']['audio']['channelmode'].'.';
					return false;
				}
				break;

			case 'stereo':
			case 'joint stereo':
			case 'dual channel':
				if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') || ($ThisFileInfo['mpeg']['audio']['bitrate'] == 64) || ($ThisFileInfo['mpeg']['audio']['bitrate'] >= 96)) {
					// these are ok
				} else {
					$ThisFileInfo['error'] .= "\n".$ThisFileInfo['mpeg']['audio']['bitrate'].'kbps not allowed in Layer II, '.$ThisFileInfo['mpeg']['audio']['channelmode'].'.';
					return false;
				}
				break;

		}

	}


	if ($ThisFileInfo['audio']['sample_rate'] > 0) {
		$ThisFileInfo['mpeg']['audio']['framelength'] = MPEGaudioFrameLength($ThisFileInfo['mpeg']['audio']['bitrate'], $ThisFileInfo['mpeg']['audio']['version'], $ThisFileInfo['mpeg']['audio']['layer'], (int) $ThisFileInfo['mpeg']['audio']['padding'], $ThisFileInfo['audio']['sample_rate']);
	}

	$nextframetestoffset = $offset + 1;
	if ($ThisFileInfo['mpeg']['audio']['bitrate'] != 'free') {

		$ThisFileInfo['audio']['bitrate'] = 1000 * $ThisFileInfo['mpeg']['audio']['bitrate'];

		if (!empty($ThisFileInfo['mpeg']['audio']['framelength'])) {
			$nextframetestoffset = $offset + $ThisFileInfo['mpeg']['audio']['framelength'];
		} else {
			$ThisFileInfo['error'] .= "\n".'Frame at offset('.$offset.') is has an invalid frame length.';
			return false;
		}

	}

	$ExpectedNumberOfAudioBytes = 0;

	////////////////////////////////////////////////////////////////////////////////////
	// Variable-bitrate headers

	if (!$FastMPEGheaderScan) {
		if (substr($headerstring, 4 + 32, 4) == 'VBRI') {
			// Fraunhofer VBR header is hardcoded 'VBRI' at offset 0x24 (36)
			// specs taken from http://minnie.tuhs.org/pipermail/mp3encoder/2001-January/001800.html

			$ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'vbr';
			$ThisFileInfo['mpeg']['audio']['VBR_method']   = 'Fraunhofer';
			$ThisFileInfo['audio']['codec']                = 'Fraunhofer';

			$SideInfoData = substr($headerstring, 4 + 2, 32);

			$FraunhoferVBROffset = 36;

			$ThisFileInfo['mpeg']['audio']['VBR_encoder_version']     = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset +  4, 2));
			$ThisFileInfo['mpeg']['audio']['VBR_encoder_delay']       = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset +  6, 2));
			$ThisFileInfo['mpeg']['audio']['VBR_quality']             = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset +  8, 2));
			$ThisFileInfo['mpeg']['audio']['VBR_bytes']               = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 10, 4));
			$ThisFileInfo['mpeg']['audio']['VBR_frames']              = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 14, 4));
			$ThisFileInfo['mpeg']['audio']['VBR_seek_offsets']        = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 18, 2));
			//$ThisFileInfo['mpeg']['audio']['reserved']              = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 20, 4)); // hardcoded $00 $01 $00 $02  - purpose unknown
			$ThisFileInfo['mpeg']['audio']['VBR_seek_offsets_stride'] = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset + 24, 2));

			$ExpectedNumberOfAudioBytes = $ThisFileInfo['mpeg']['audio']['VBR_bytes'];

			$previousbyteoffset = $offset;
			for ($i = 0; $i < $ThisFileInfo['mpeg']['audio']['VBR_seek_offsets']; $i++) {
				$Fraunhofer_OffsetN = BigEndian2Int(substr($headerstring, $FraunhoferVBROffset, 2));
				$FraunhoferVBROffset += 2;
				$ThisFileInfo['mpeg']['audio']['VBR_offsets_relative'][$i] = $Fraunhofer_OffsetN;
				$ThisFileInfo['mpeg']['audio']['VBR_offsets_absolute'][$i] = $Fraunhofer_OffsetN + $previousbyteoffset;
				$previousbyteoffset += $Fraunhofer_OffsetN;
			}


		} else {

			// Xing VBR header is hardcoded 'Xing' at a offset 0x0D (13), 0x15 (21) or 0x24 (36)
			// depending on MPEG layer and number of channels

			if ($ThisFileInfo['mpeg']['audio']['version'] == '1') {
				if ($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') {
					// MPEG-1 (mono)
					$VBRidOffset  = 4 + 17; // 0x15
					$SideInfoData = substr($headerstring, 4 + 2, 17);
				} else {
					// MPEG-1 (stereo, joint-stereo, dual-channel)
					$VBRidOffset = 4 + 32; // 0x24
					$SideInfoData = substr($headerstring, 4 + 2, 32);
				}
			} else { // 2 or 2.5
				if ($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') {
					// MPEG-2, MPEG-2.5 (mono)
					$VBRidOffset = 4 + 9;  // 0x0D
					$SideInfoData = substr($headerstring, 4 + 2, 9);
				} else {
					// MPEG-2, MPEG-2.5 (stereo, joint-stereo, dual-channel)
					$VBRidOffset = 4 + 17; // 0x15
					$SideInfoData = substr($headerstring, 4 + 2, 17);
				}
			}

			if ((substr($headerstring, $VBRidOffset, strlen('Xing')) == 'Xing') || (substr($headerstring, $VBRidOffset, strlen('Info')) == 'Info')) {
				// 'Xing' is traditional Xing VBR frame
				// 'Info' is LAME-encoded CBR (This was done to avoid CBR files to be recognized as traditional Xing VBR files by some decoders.)

				$ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'vbr';
				$ThisFileInfo['mpeg']['audio']['VBR_method']   = 'Xing';

				$ThisFileInfo['mpeg']['audio']['xing_flags_raw'] = BigEndian2Int(substr($headerstring, $VBRidOffset + 4, 4));

				$ThisFileInfo['mpeg']['audio']['xing_flags']['frames']    = (bool) ($ThisFileInfo['mpeg']['audio']['xing_flags_raw'] & 0x00000001);
				$ThisFileInfo['mpeg']['audio']['xing_flags']['bytes']     = (bool) ($ThisFileInfo['mpeg']['audio']['xing_flags_raw'] & 0x00000002);
				$ThisFileInfo['mpeg']['audio']['xing_flags']['toc']       = (bool) ($ThisFileInfo['mpeg']['audio']['xing_flags_raw'] & 0x00000004);
				$ThisFileInfo['mpeg']['audio']['xing_flags']['vbr_scale'] = (bool) ($ThisFileInfo['mpeg']['audio']['xing_flags_raw'] & 0x00000008);

				if ($ThisFileInfo['mpeg']['audio']['xing_flags']['frames']) {
					$ThisFileInfo['mpeg']['audio']['VBR_frames'] = BigEndian2Int(substr($headerstring, $VBRidOffset +  8, 4));
				}
				if ($ThisFileInfo['mpeg']['audio']['xing_flags']['bytes']) {
					$ThisFileInfo['mpeg']['audio']['VBR_bytes']  = BigEndian2Int(substr($headerstring, $VBRidOffset + 12, 4));
				}

				if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') && !empty($ThisFileInfo['mpeg']['audio']['VBR_frames']) && !empty($ThisFileInfo['mpeg']['audio']['VBR_bytes'])) {
					$framelengthfloat = $ThisFileInfo['mpeg']['audio']['VBR_bytes'] / $ThisFileInfo['mpeg']['audio']['VBR_frames'];
					if ($ThisFileInfo['mpeg']['audio']['layer'] == 'I') {
						// BitRate = (((FrameLengthInBytes / 4) - Padding) * SampleRate) / 12
						$ThisFileInfo['audio']['bitrate'] = ((($framelengthfloat / 4) - intval($ThisFileInfo['mpeg']['audio']['padding'])) * $ThisFileInfo['mpeg']['audio']['sample_rate']) / 12;
					} else {
						// Bitrate = ((FrameLengthInBytes - Padding) * SampleRate) / 144
						$ThisFileInfo['audio']['bitrate'] = (($framelengthfloat - intval($ThisFileInfo['mpeg']['audio']['padding'])) * $ThisFileInfo['mpeg']['audio']['sample_rate']) / 144;
					}
					$ThisFileInfo['mpeg']['audio']['framelength'] = floor($framelengthfloat);
				}

				if ($ThisFileInfo['mpeg']['audio']['xing_flags']['toc']) {
					$LAMEtocData = substr($headerstring, $VBRidOffset + 16, 100);
					for ($i = 0; $i < 100; $i++) {
						$ThisFileInfo['mpeg']['audio']['toc'][$i] = ord($LAMEtocData{$i});
					}
				}
				if ($ThisFileInfo['mpeg']['audio']['xing_flags']['vbr_scale']) {
					$ThisFileInfo['mpeg']['audio']['VBR_scale'] = BigEndian2Int(substr($headerstring, $VBRidOffset + 116, 4));
				}

				// http://gabriel.mp3-tech.org/mp3infotag.html
				if (substr($headerstring, $VBRidOffset + 120, 4) == 'LAME') {
					$ThisFileInfo['mpeg']['audio']['LAME']['long_version']  = substr($headerstring, $VBRidOffset + 120, 20);
					$ThisFileInfo['mpeg']['audio']['LAME']['short_version'] = substr($ThisFileInfo['mpeg']['audio']['LAME']['long_version'], 0, 9);
					$ThisFileInfo['mpeg']['audio']['LAME']['long_version']  = rtrim($ThisFileInfo['mpeg']['audio']['LAME']['long_version'], "\x55\xAA");

					if ($ThisFileInfo['mpeg']['audio']['LAME']['short_version'] >= 'LAME3.90.') {

						// It the LAME tag was only introduced in LAME v3.90
						// http://www.hydrogenaudio.org/?act=ST&f=15&t=9933

						// Offsets of various bytes in http://gabriel.mp3-tech.org/mp3infotag.html
						// are assuming a 'Xing' identifier offset of 0x24, which is the case for
						// MPEG-1 non-mono, but not for other combinations
						$LAMEtagOffsetContant = $VBRidOffset - 0x24;

						// byte $9B  VBR Quality
						// This field is there to indicate a quality level, although the scale was not precised in the original Xing specifications.
						// Actually overwrites original Xing bytes
						unset($ThisFileInfo['mpeg']['audio']['VBR_scale']);
						$ThisFileInfo['mpeg']['audio']['LAME']['vbr_quality'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0x9B, 1));

						// bytes $9C-$A4  Encoder short VersionString
						$ThisFileInfo['mpeg']['audio']['LAME']['short_version'] = substr($headerstring, $LAMEtagOffsetContant + 0x9C, 9);
						$ThisFileInfo['mpeg']['audio']['LAME']['long_version']  = $ThisFileInfo['mpeg']['audio']['LAME']['short_version'];

						// byte $A5  Info Tag revision + VBR method
						$LAMEtagRevisionVBRmethod = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA5, 1));

						$ThisFileInfo['mpeg']['audio']['LAME']['tag_revision']      = ($LAMEtagRevisionVBRmethod & 0xF0) >> 4;
						$ThisFileInfo['mpeg']['audio']['LAME']['raw']['vbr_method'] =  $LAMEtagRevisionVBRmethod & 0x0F;
						$ThisFileInfo['mpeg']['audio']['LAME']['vbr_method']        = LAMEvbrMethodLookup($ThisFileInfo['mpeg']['audio']['LAME']['raw']['vbr_method']);

						// byte $A6  Lowpass filter value
						$ThisFileInfo['mpeg']['audio']['LAME']['lowpass_frequency'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xA6, 1)) * 100;

						// bytes $A7-$AE  Replay Gain
						// http://privatewww.essex.ac.uk/~djmrob/replaygain/rg_data_format.html
						// bytes $A7-$AA : 32 bit floating point "Peak signal amplitude"
						$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] = BigEndian2Float(substr($headerstring, $LAMEtagOffsetContant + 0xA7, 4));
						$ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio']      =   BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAB, 2));
						$ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] =   BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAD, 2));

						if ($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] == 0) {
							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] = false;
						}

						if ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] != 0) {
							require_once(GETID3_INCLUDEPATH.'getid3.rgad.php');

							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['name']        = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] & 0xE000) >> 13;
							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['originator']  = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] & 0x1C00) >> 10;
							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['sign_bit']    = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] & 0x0200) >> 9;
							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['gain_adjust'] =  $ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_radio'] & 0x01FF;
							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['name']       = RGADnameLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['name']);
							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['originator'] = RGADoriginatorLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['originator']);
							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['gain_db']    = RGADadjustmentLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['gain_adjust'], $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['raw']['sign_bit']);

							if ($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] !== false) {
								$ThisFileInfo['replay_gain']['radio']['peak']   = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'];
							}
							$ThisFileInfo['replay_gain']['radio']['originator'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['originator'];
							$ThisFileInfo['replay_gain']['radio']['adjustment'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['radio']['gain_db'];
						}
						if ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] != 0) {
							require_once(GETID3_INCLUDEPATH.'getid3.rgad.php');

							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['name']        = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] & 0xE000) >> 13;
							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['originator']  = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] & 0x1C00) >> 10;
							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['sign_bit']    = ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] & 0x0200) >> 9;
							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['gain_adjust'] = $ThisFileInfo['mpeg']['audio']['LAME']['raw']['RGAD_audiophile'] & 0x01FF;
							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['name']       = RGADnameLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['name']);
							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['originator'] = RGADoriginatorLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['originator']);
							$ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['gain_db']    = RGADadjustmentLookup($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['gain_adjust'], $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['raw']['sign_bit']);

							if ($ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'] !== false) {
								$ThisFileInfo['replay_gain']['audiophile']['peak']   = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['peak_amplitude'];
							}
							$ThisFileInfo['replay_gain']['audiophile']['originator'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['originator'];
							$ThisFileInfo['replay_gain']['audiophile']['adjustment'] = $ThisFileInfo['mpeg']['audio']['LAME']['RGAD']['audiophile']['gain_db'];
						}


						// byte $AF  Encoding flags + ATH Type
						$EncodingFlagsATHtype = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xAF, 1));
						$ThisFileInfo['mpeg']['audio']['LAME']['encoding_flags']['nspsytune']   = (bool) ($EncodingFlagsATHtype & 0x10);
						$ThisFileInfo['mpeg']['audio']['LAME']['encoding_flags']['nssafejoint'] = (bool) ($EncodingFlagsATHtype & 0x20);
						$ThisFileInfo['mpeg']['audio']['LAME']['encoding_flags']['nogap_next']  = (bool) ($EncodingFlagsATHtype & 0x40);
						$ThisFileInfo['mpeg']['audio']['LAME']['encoding_flags']['nogap_prev']  = (bool) ($EncodingFlagsATHtype & 0x80);
						$ThisFileInfo['mpeg']['audio']['LAME']['ath_type']                      =         $EncodingFlagsATHtype & 0x0F;

						// byte $B0  if ABR {specified bitrate} else {minimal bitrate}
						$ABRbitrateMinBitrate = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB0, 1));
						if ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['vbr_method'] == 2) { // Average BitRate (ABR)
							$ThisFileInfo['mpeg']['audio']['LAME']['bitrate_abr'] = $ABRbitrateMinBitrate;
						} elseif ($ABRbitrateMinBitrate > 0) { // Variable BitRate (VBR) - minimum bitrate
							$ThisFileInfo['mpeg']['audio']['LAME']['bitrate_min'] = $ABRbitrateMinBitrate;
						}

						// bytes $B1-$B3  Encoder delays
						$EncoderDelays = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB1, 3));
						$ThisFileInfo['mpeg']['audio']['LAME']['encoder_delay'] = ($EncoderDelays & 0xFFF000) >> 12;
						$ThisFileInfo['mpeg']['audio']['LAME']['end_padding']   =  $EncoderDelays & 0x000FFF;

						// byte $B4  Misc
						$MiscByte = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB4, 1));
						$ThisFileInfo['mpeg']['audio']['LAME']['raw']['noise_shaping']       = ($MiscByte & 0x03);
						$ThisFileInfo['mpeg']['audio']['LAME']['raw']['stereo_mode']         = ($MiscByte & 0x1C) >> 2;
						$ThisFileInfo['mpeg']['audio']['LAME']['raw']['not_optimal_quality'] = ($MiscByte & 0x20) >> 5;
						$ThisFileInfo['mpeg']['audio']['LAME']['raw']['source_sample_freq']  = ($MiscByte & 0xC0) >> 6;
						$ThisFileInfo['mpeg']['audio']['LAME']['noise_shaping']       = $ThisFileInfo['mpeg']['audio']['LAME']['raw']['noise_shaping'];
						$ThisFileInfo['mpeg']['audio']['LAME']['stereo_mode']         = LAMEmiscStereoModeLookup($ThisFileInfo['mpeg']['audio']['LAME']['raw']['stereo_mode']);
						$ThisFileInfo['mpeg']['audio']['LAME']['not_optimal_quality'] = (bool) $ThisFileInfo['mpeg']['audio']['LAME']['raw']['not_optimal_quality'];
						$ThisFileInfo['mpeg']['audio']['LAME']['source_sample_freq']  = LAMEmiscSourceSampleFrequencyLookup($ThisFileInfo['mpeg']['audio']['LAME']['raw']['source_sample_freq']);

						// byte $B5  MP3 Gain
						$ThisFileInfo['mpeg']['audio']['LAME']['raw']['mp3_gain'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB5, 1), false, true);
						$ThisFileInfo['mpeg']['audio']['LAME']['mp3_gain_db']     = 1.5 * $ThisFileInfo['mpeg']['audio']['LAME']['raw']['mp3_gain'];
						$ThisFileInfo['mpeg']['audio']['LAME']['mp3_gain_factor'] = pow(2, ($ThisFileInfo['mpeg']['audio']['LAME']['mp3_gain_db'] / 6));

						// bytes $B6-$B7  Preset and surround info
						$PresetSurroundBytes = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB6, 2));
						// Reserved                                                    = ($PresetSurroundBytes & 0xC000);
						$ThisFileInfo['mpeg']['audio']['LAME']['raw']['surround_info'] = ($PresetSurroundBytes & 0x3800);
						$ThisFileInfo['mpeg']['audio']['LAME']['surround_info']        = LAMEsurroundInfoLookup($ThisFileInfo['mpeg']['audio']['LAME']['raw']['surround_info']);
						$ThisFileInfo['mpeg']['audio']['LAME']['preset_used_id']       = ($PresetSurroundBytes & 0x07FF);

						// bytes $B8-$BB  MusicLength
						$ThisFileInfo['mpeg']['audio']['LAME']['audio_bytes'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xB8, 4));
						$ExpectedNumberOfAudioBytes = (($ThisFileInfo['mpeg']['audio']['LAME']['audio_bytes'] > 0) ? $ThisFileInfo['mpeg']['audio']['LAME']['audio_bytes'] : $ThisFileInfo['mpeg']['audio']['VBR_bytes']);

						// bytes $BC-$BD  MusicCRC
						$ThisFileInfo['mpeg']['audio']['LAME']['music_crc']    = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBC, 2));

						// bytes $BE-$BF  CRC-16 of Info Tag
						$ThisFileInfo['mpeg']['audio']['LAME']['lame_tag_crc'] = BigEndian2Int(substr($headerstring, $LAMEtagOffsetContant + 0xBE, 2));


						// LAME CBR
						if ($ThisFileInfo['mpeg']['audio']['LAME']['raw']['vbr_method'] == 1) {

							$ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'cbr';
							if (empty($ThisFileInfo['mpeg']['audio']['bitrate']) || ($ThisFileInfo['mpeg']['audio']['LAME']['bitrate_min'] != 255)) {
								$ThisFileInfo['mpeg']['audio']['bitrate'] = $ThisFileInfo['mpeg']['audio']['LAME']['bitrate_min'];
							}

						}

					}
				}

			} else {

				// not Fraunhofer or Xing VBR methods, most likely CBR (but could be VBR with no header)
				$ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'cbr';
				if ($recursivesearch) {
					$ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'vbr';
					if (RecursiveFrameScanning($fd, $ThisFileInfo, $offset, $nextframetestoffset, true)) {
						$recursivesearch = false;
						$ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'cbr';
					}
					if ($ThisFileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr') {
						$ThisFileInfo['warning'] .= "\n".'VBR file with no VBR header. Bitrate values calculated from actual frame bitrates.';
					}
				}
			}
		}
	}

	if (($ExpectedNumberOfAudioBytes > 0) && ($ExpectedNumberOfAudioBytes != ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']))) {
		if (($ExpectedNumberOfAudioBytes - ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset'])) == 1) {
			$ThisFileInfo['warning'] .= "\n".'Last byte of data truncated (this is a known bug in Meracl ID3 Tag Writer before v1.3.5)';
		} elseif ($ExpectedNumberOfAudioBytes > ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset'])) {
			$ThisFileInfo['warning'] .= "\n".'Probable truncated file: expecting '.$ExpectedNumberOfAudioBytes.' bytes of audio data, only found '.($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']).' (short by '.($ExpectedNumberOfAudioBytes - ($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset'])).' bytes)';
		} else {
			$ThisFileInfo['warning'] .= "\n".'Too much data in file: expecting '.$ExpectedNumberOfAudioBytes.' bytes of audio data, found '.($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']).' ('.(($ThisFileInfo['avdataend'] - $ThisFileInfo['avdataoffset']) - $ExpectedNumberOfAudioBytes).' bytes too many)';
		}
	}

	if (($ThisFileInfo['mpeg']['audio']['bitrate'] == 'free') && empty($ThisFileInfo['audio']['bitrate'])) {
		if (($offset == $ThisFileInfo['avdataoffset']) && empty($ThisFileInfo['mpeg']['audio']['VBR_frames'])) {
			$framebytelength = FreeFormatFrameLength($fd, $offset, $ThisFileInfo, true);
			if ($framebytelength > 0) {
				$ThisFileInfo['mpeg']['audio']['framelength'] = $framebytelength;
				if ($ThisFileInfo['mpeg']['audio']['layer'] == 'I') {
					// BitRate = (((FrameLengthInBytes / 4) - Padding) * SampleRate) / 12
					$ThisFileInfo['audio']['bitrate'] = ((($framebytelength / 4) - intval($ThisFileInfo['mpeg']['audio']['padding'])) * $ThisFileInfo['mpeg']['audio']['sample_rate']) / 12;
				} else {
					// Bitrate = ((FrameLengthInBytes - Padding) * SampleRate) / 144
					$ThisFileInfo['audio']['bitrate'] = (($framebytelength - intval($ThisFileInfo['mpeg']['audio']['padding'])) * $ThisFileInfo['mpeg']['audio']['sample_rate']) / 144;
				}
			} else {
				$ThisFileInfo['error'] .= "\n".'Error calculating frame length of free-format MP3 without Xing/LAME header';
			}
		}
	}

	if (($ThisFileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr') && isset($ThisFileInfo['mpeg']['audio']['VBR_frames']) && ($ThisFileInfo['mpeg']['audio']['VBR_frames'] > 1)) {
		$ThisFileInfo['mpeg']['audio']['VBR_frames']--; // don't count the Xing / VBRI frame
		if (($ThisFileInfo['mpeg']['audio']['version'] == '1') && ($ThisFileInfo['mpeg']['audio']['layer'] == 'I')) {
			$ThisFileInfo['mpeg']['audio']['VBR_bitrate'] = ((($ThisFileInfo['mpeg']['audio']['VBR_bytes'] / $ThisFileInfo['mpeg']['audio']['VBR_frames']) * 8) * ($ThisFileInfo['audio']['sample_rate'] / 384)) / 1000;
		} elseif ((($ThisFileInfo['mpeg']['audio']['version'] == '2') || ($ThisFileInfo['mpeg']['audio']['version'] == '2.5')) && ($ThisFileInfo['mpeg']['audio']['layer'] == 'III')) {
			$ThisFileInfo['mpeg']['audio']['VBR_bitrate'] = ((($ThisFileInfo['mpeg']['audio']['VBR_bytes'] / $ThisFileInfo['mpeg']['audio']['VBR_frames']) * 8) * ($ThisFileInfo['audio']['sample_rate'] / 576)) / 1000;
		} else {
			$ThisFileInfo['mpeg']['audio']['VBR_bitrate'] = ((($ThisFileInfo['mpeg']['audio']['VBR_bytes'] / $ThisFileInfo['mpeg']['audio']['VBR_frames']) * 8) * ($ThisFileInfo['audio']['sample_rate'] / 1152)) / 1000;
		}
		if ($ThisFileInfo['mpeg']['audio']['VBR_bitrate'] > 0) {
			$ThisFileInfo['audio']['bitrate']         = 1000 * $ThisFileInfo['mpeg']['audio']['VBR_bitrate'];
			$ThisFileInfo['mpeg']['audio']['bitrate'] = $ThisFileInfo['mpeg']['audio']['VBR_bitrate']; // to avoid confusion
		}
	}

	// End variable-bitrate headers
	////////////////////////////////////////////////////////////////////////////////////

	if ($recursivesearch) {

		if (!RecursiveFrameScanning($fd, $ThisFileInfo, $offset, $nextframetestoffset, $ScanAsCBR)) {
			return false;
		}

	}


	//if (false) {
	//	// experimental side info parsing section - not returning anything useful yet
    //
	//	$SideInfoBitstream = BigEndian2Bin($SideInfoData);
	//	$SideInfoOffset = 0;
    //
	//	if ($ThisFileInfo['mpeg']['audio']['version'] == '1') {
	//		if ($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') {
	//			// MPEG-1 (mono)
	//			$ThisFileInfo['mpeg']['audio']['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 9);
	//			$SideInfoOffset += 9;
	//			$SideInfoOffset += 5;
	//		} else {
	//			// MPEG-1 (stereo, joint-stereo, dual-channel)
	//			$ThisFileInfo['mpeg']['audio']['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 9);
	//			$SideInfoOffset += 9;
	//			$SideInfoOffset += 3;
	//		}
	//	} else { // 2 or 2.5
	//		if ($ThisFileInfo['mpeg']['audio']['channelmode'] == 'mono') {
	//			// MPEG-2, MPEG-2.5 (mono)
	//			$ThisFileInfo['mpeg']['audio']['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 8);
	//			$SideInfoOffset += 8;
	//			$SideInfoOffset += 1;
	//		} else {
	//			// MPEG-2, MPEG-2.5 (stereo, joint-stereo, dual-channel)
	//			$ThisFileInfo['mpeg']['audio']['side_info']['main_data_begin'] = substr($SideInfoBitstream, $SideInfoOffset, 8);
	//			$SideInfoOffset += 8;
	//			$SideInfoOffset += 2;
	//		}
	//	}
    //
	//	if ($ThisFileInfo['mpeg']['audio']['version'] == '1') {
	//		for ($channel = 0; $channel < $ThisFileInfo['audio']['channels']; $channel++) {
	//			for ($scfsi_band = 0; $scfsi_band < 4; $scfsi_band++) {
	//				$ThisFileInfo['mpeg']['audio']['scfsi'][$channel][$scfsi_band] = substr($SideInfoBitstream, $SideInfoOffset, 1);
	//				$SideInfoOffset += 2;
	//			}
	//		}
	//	}
	//	for ($granule = 0; $granule < (($ThisFileInfo['mpeg']['audio']['version'] == '1') ? 2 : 1); $granule++) {
	//		for ($channel = 0; $channel < $ThisFileInfo['audio']['channels']; $channel++) {
	//			$ThisFileInfo['mpeg']['audio']['part2_3_length'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 12);
	//			$SideInfoOffset += 12;
	//			$ThisFileInfo['mpeg']['audio']['big_values'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 9);
	//			$SideInfoOffset += 9;
	//			$ThisFileInfo['mpeg']['audio']['global_gain'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 8);
	//			$SideInfoOffset += 8;
	//			if ($ThisFileInfo['mpeg']['audio']['version'] == '1') {
	//				$ThisFileInfo['mpeg']['audio']['scalefac_compress'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 4);
	//				$SideInfoOffset += 4;
	//			} else {
	//				$ThisFileInfo['mpeg']['audio']['scalefac_compress'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 9);
	//				$SideInfoOffset += 9;
	//			}
	//			$ThisFileInfo['mpeg']['audio']['window_switching_flag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
	//			$SideInfoOffset += 1;
    //
	//			if ($ThisFileInfo['mpeg']['audio']['window_switching_flag'][$granule][$channel] == '1') {
    //
	//				$ThisFileInfo['mpeg']['audio']['block_type'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 2);
	//				$SideInfoOffset += 2;
	//				$ThisFileInfo['mpeg']['audio']['mixed_block_flag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
	//				$SideInfoOffset += 1;
    //
	//				for ($region = 0; $region < 2; $region++) {
	//					$ThisFileInfo['mpeg']['audio']['table_select'][$granule][$channel][$region] = substr($SideInfoBitstream, $SideInfoOffset, 5);
	//					$SideInfoOffset += 5;
	//				}
	//				$ThisFileInfo['mpeg']['audio']['table_select'][$granule][$channel][2] = 0;
    //
	//				for ($window = 0; $window < 3; $window++) {
	//					$ThisFileInfo['mpeg']['audio']['subblock_gain'][$granule][$channel][$window] = substr($SideInfoBitstream, $SideInfoOffset, 3);
	//					$SideInfoOffset += 3;
	//				}
    //
	//			} else {
    //
	//				for ($region = 0; $region < 3; $region++) {
	//					$ThisFileInfo['mpeg']['audio']['table_select'][$granule][$channel][$region] = substr($SideInfoBitstream, $SideInfoOffset, 5);
	//					$SideInfoOffset += 5;
	//				}
    //
	//				$ThisFileInfo['mpeg']['audio']['region0_count'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 4);
	//				$SideInfoOffset += 4;
	//				$ThisFileInfo['mpeg']['audio']['region1_count'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 3);
	//				$SideInfoOffset += 3;
	//				$ThisFileInfo['mpeg']['audio']['block_type'][$granule][$channel] = 0;
	//			}
    //
	//			if ($ThisFileInfo['mpeg']['audio']['version'] == '1') {
	//				$ThisFileInfo['mpeg']['audio']['preflag'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
	//				$SideInfoOffset += 1;
	//			}
	//			$ThisFileInfo['mpeg']['audio']['scalefac_scale'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
	//			$SideInfoOffset += 1;
	//			$ThisFileInfo['mpeg']['audio']['count1table_select'][$granule][$channel] = substr($SideInfoBitstream, $SideInfoOffset, 1);
	//			$SideInfoOffset += 1;
	//		}
	//	}
	//}

	return true;
}

function RecursiveFrameScanning(&$fd, &$ThisFileInfo, &$offset, &$nextframetestoffset, $ScanAsCBR) {
	for ($i = 0; $i < MPEG_VALID_CHECK_FRAMES; $i++) {
		// check next MPEG_VALID_CHECK_FRAMES frames for validity, to make sure we haven't run across a false synch
		if (($nextframetestoffset + 4) >= $ThisFileInfo['avdataend']) {
			// end of file
			return true;
		}

		$nextframetestarray = array('error'=>'', 'warning'=>'', 'avdataend'=>$ThisFileInfo['avdataend'], 'avdataoffset'=>$ThisFileInfo['avdataoffset']);
		if (decodeMPEGaudioHeader($fd, $nextframetestoffset, $nextframetestarray, false)) {
			if ($ScanAsCBR) {
				// force CBR mode, used for trying to pick out invalid audio streams with
				// valid(?) VBR headers, or VBR streams with no VBR header
				if (!isset($nextframetestarray['mpeg']['audio']['bitrate']) || !isset($ThisFileInfo['mpeg']['audio']['bitrate']) || ($nextframetestarray['mpeg']['audio']['bitrate'] != $ThisFileInfo['mpeg']['audio']['bitrate'])) {
					return false;
				}
			}


			// next frame is OK, get ready to check the one after that
			if (isset($nextframetestarray['mpeg']['audio']['framelength']) && ($nextframetestarray['mpeg']['audio']['framelength'] > 0)) {
				$nextframetestoffset += $nextframetestarray['mpeg']['audio']['framelength'];
			} else {
				$ThisFileInfo['error'] .= "\n".'Frame at offset ('.$offset.') is has an invalid frame length.';
				return false;
			}

		} else {

			// next frame is not valid, note the error and fail, so scanning can contiue for a valid frame sequence
			$ThisFileInfo['error'] .= "\n".'Frame at offset ('.$offset.') is valid, but the next one at ('.$nextframetestoffset.') is not.';

			return false;
		}
	}
	return true;
}

function FreeFormatFrameLength($fd, $offset, &$ThisFileInfo, $deepscan=false) {
	fseek($fd, $offset, SEEK_SET);
	$MPEGaudioData = fread($fd, 32768);

	$SyncPattern1 = substr($MPEGaudioData, 0, 4);
	// may be different pattern due to padding
	$SyncPattern2 = $SyncPattern1{0}.$SyncPattern1{1}.chr(ord($SyncPattern1{2}) | 0x02).$SyncPattern1{3};
	if ($SyncPattern2 === $SyncPattern1) {
		$SyncPattern2 = $SyncPattern1{0}.$SyncPattern1{1}.chr(ord($SyncPattern1{2}) & 0xFD).$SyncPattern1{3};
	}

	$framelength = false;
	$framelength1 = strpos($MPEGaudioData, $SyncPattern1, 4);
	$framelength2 = strpos($MPEGaudioData, $SyncPattern2, 4);
	if ($framelength1 > 4) {
		$framelength = $framelength1;
	}
	if (($framelength2 > 4) && ($framelength2 < $framelength1)) {
		$framelength = $framelength2;
	}
	if (!$framelength) {

		// LAME 3.88 has a different value for modeextension on the first frame vs the rest
		$framelength1 = strpos($MPEGaudioData, substr($SyncPattern1, 0, 3), 4);
		$framelength2 = strpos($MPEGaudioData, substr($SyncPattern2, 0, 3), 4);

		if ($framelength1 > 4) {
			$framelength = $framelength1;
		}
		if (($framelength2 > 4) && ($framelength2 < $framelength1)) {
			$framelength = $framelength2;
		}
		if (!$framelength) {
			$ThisFileInfo['error'] .= "\n".'Cannot find next free-format synch pattern ('.PrintHexBytes($SyncPattern1).' or '.PrintHexBytes($SyncPattern2).') after offset '.$offset;
			return false;
		} else {
			$ThisFileInfo['warning'] .= "\n".'ModeExtension varies between first frame and other frames (known free-format issue in LAME 3.88)';
			$ThisFileInfo['audio']['codec']   = 'LAME';
			$ThisFileInfo['audio']['encoder'] = 'LAME3.88';
			$SyncPattern1 = substr($SyncPattern1, 0, 3);
			$SyncPattern2 = substr($SyncPattern2, 0, 3);
		}
	}

	if ($deepscan) {

		$ActualFrameLengthValues = array();
		$nextoffset = $offset + $framelength;
		while ($nextoffset < ($ThisFileInfo['avdataend'] - 6)) {
			fseek($fd, $nextoffset - 1, SEEK_SET);
			$NextSyncPattern = fread($fd, 6);
			if ((substr($NextSyncPattern, 1, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 1, strlen($SyncPattern2)) == $SyncPattern2)) {
				// good - found where expected
				$ActualFrameLengthValues[] = $framelength;
			} elseif ((substr($NextSyncPattern, 0, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 0, strlen($SyncPattern2)) == $SyncPattern2)) {
				// ok - found one byte earlier than expected (last frame wasn't padded, first frame was)
				$ActualFrameLengthValues[] = ($framelength - 1);
				$nextoffset--;
			} elseif ((substr($NextSyncPattern, 2, strlen($SyncPattern1)) == $SyncPattern1) || (substr($NextSyncPattern, 2, strlen($SyncPattern2)) == $SyncPattern2)) {
				// ok - found one byte later than expected (last frame was padded, first frame wasn't)
				$ActualFrameLengthValues[] = ($framelength + 1);
				$nextoffset++;
			} else {
				$ThisFileInfo['error'] .= "\n".'Did not find expected free-format sync pattern at offset '.$nextoffset;
				return false;
			}
			$nextoffset += $framelength;
		}
		if (count($ActualFrameLengthValues) > 0) {
			$framelength = round(array_sum($ActualFrameLengthValues) / count($ActualFrameLengthValues));
		}
	}
	return $framelength;
}


function getOnlyMPEGaudioInfo($fd, &$ThisFileInfo, $avdataoffset, $BitrateHistogram=false) {
	// looks for synch, decodes MPEG audio header

	fseek($fd, $avdataoffset, SEEK_SET);
	$header = '';
	$SynchSeekOffset = 0;

	if (!defined('CONST_FF')) {
		define('CONST_FF', chr(0xFF));
		define('CONST_E0', chr(0xE0));
	}

	static $MPEGaudioVersionLookup;
	static $MPEGaudioLayerLookup;
	static $MPEGaudioBitrateLookup;
	if (empty($MPEGaudioVersionLookup)) {
		$MPEGaudioVersionLookup = MPEGaudioVersionArray();
		$MPEGaudioLayerLookup   = MPEGaudioLayerArray();
		$MPEGaudioBitrateLookup = MPEGaudioBitrateArray();
	}
	static $MPEGaudioHeaderValidCache = array();

	$header_len = strlen($header) - round(FREAD_BUFFER_SIZE / 2);
	while (true) {

		if (($SynchSeekOffset > $header_len) && (($avdataoffset + $SynchSeekOffset)  < $ThisFileInfo['avdataend']) && !feof($fd)) {

			if ($SynchSeekOffset > 131072) {
				// if a synch's not found within the first 128k bytes, then give up
				$ThisFileInfo['error'] .= "\n".'could not find valid MPEG synch within the first 131072 bytes';
				if (isset($ThisFileInfo['audio']['bitrate'])) {
					unset($ThisFileInfo['audio']['bitrate']);
				}
				if (isset($ThisFileInfo['mpeg']['audio'])) {
					unset($ThisFileInfo['mpeg']['audio']);
				}
				if (isset($ThisFileInfo['mpeg']) && (!is_array($ThisFileInfo['mpeg']) || (count($ThisFileInfo['mpeg']) == 0))) {
					unset($ThisFileInfo['mpeg']);
				}
				return false;

			} elseif ($header .= fread($fd, FREAD_BUFFER_SIZE)) {

				// great
				$header_len = strlen($header) - round(FREAD_BUFFER_SIZE / 2);

			} else {

				$ThisFileInfo['error'] .= "\n".'could not find valid MPEG synch before end of file';
				if (isset($ThisFileInfo['audio']['bitrate'])) {
					unset($ThisFileInfo['audio']['bitrate']);
				}
				if (isset($ThisFileInfo['mpeg']['audio'])) {
					unset($ThisFileInfo['mpeg']['audio']);
				}
				if (isset($ThisFileInfo['mpeg']) && (!is_array($ThisFileInfo['mpeg']) || (count($ThisFileInfo['mpeg']) == 0))) {
					unset($ThisFileInfo['mpeg']);
				}
				return false;

			}
		}

		if (($SynchSeekOffset + 1) >= strlen($header)) {
			$ThisFileInfo['error'] .= "\n".'could not find valid MPEG synch before end of file';
			return false;
		}

		if ($header{$SynchSeekOffset} == CONST_FF) {
			if ($header{($SynchSeekOffset + 1)} > CONST_E0) {
				$head4 = substr($header, $SynchSeekOffset, 4);
				if (!isset($MPEGaudioHeaderValidCache[$head4])) {
					$MPEGaudioHeaderValidCache[$head4] = MPEGaudioHeaderBytesValid($head4);
				}
				if ($MPEGaudioHeaderValidCache[$head4]) { // synch detected
					if (!isset($FirstFrameThisfileInfo) && !isset($ThisFileInfo['mpeg']['audio'])) {
						$FirstFrameThisfileInfo = $ThisFileInfo;
						$FirstFrameAVDataOffset = $avdataoffset + $SynchSeekOffset;
						if (!decodeMPEGaudioHeader($fd, $avdataoffset + $SynchSeekOffset, $FirstFrameThisfileInfo, false)) {
							// if this is the first valid MPEG-audio frame, save it in case it's a VBR header frame and there's
							// garbage between this frame and a valid sequence of MPEG-audio frames, to be restored below
							unset($FirstFrameThisfileInfo);
						}
					}
					$dummy = $ThisFileInfo; // only overwrite real data if valid header found

					if (decodeMPEGaudioHeader($fd, $avdataoffset + $SynchSeekOffset, $dummy, true)) {

						$ThisFileInfo = $dummy;
						$ThisFileInfo['avdataoffset'] = $avdataoffset + $SynchSeekOffset;
						switch ($ThisFileInfo['fileformat']) {
							case '':
							case 'id3':
							case 'ape':
							case 'mp3':
								$ThisFileInfo['fileformat']          = 'mp3';
								$ThisFileInfo['audio']['dataformat'] = 'mp3';
						}
						if (isset($FirstFrameThisfileInfo['mpeg']['audio']['bitrate_mode']) && ($FirstFrameThisfileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr')) {
							if (!CloseMatch($ThisFileInfo['audio']['bitrate'], $FirstFrameThisfileInfo['audio']['bitrate'], 1)) {
								// If there is garbage data between a valid VBR header frame and a sequence
								// of valid MPEG-audio frames the VBR data is no longer discarded.
								$ThisFileInfo = $FirstFrameThisfileInfo;
								$ThisFileInfo['avdataoffset']        = $FirstFrameAVDataOffset;
								$ThisFileInfo['fileformat']          = 'mp3';
								$ThisFileInfo['audio']['dataformat'] = 'mp3';
								$dummy                               = $ThisFileInfo;
								unset($dummy['mpeg']['audio']);
								$GarbageOffsetStart = $FirstFrameAVDataOffset + $FirstFrameThisfileInfo['mpeg']['audio']['framelength'];
								$GarbageOffsetEnd   = $avdataoffset + $SynchSeekOffset;
								if (decodeMPEGaudioHeader($fd, $GarbageOffsetEnd, $dummy, true, true)) {

									$ThisFileInfo = $dummy;
									$ThisFileInfo['avdataoffset'] = $GarbageOffsetEnd;
									$ThisFileInfo['warning'] .= "\n".'apparently-valid VBR header not used because could not find '.MPEG_VALID_CHECK_FRAMES.' consecutive MPEG-audio frames immediately after VBR header (garbage data for '.($GarbageOffsetEnd - $GarbageOffsetStart).' bytes between '.$GarbageOffsetStart.' and '.$GarbageOffsetEnd.'), but did find valid CBR stream starting at '.$GarbageOffsetEnd;

								} else {

									$ThisFileInfo['warning'] .= "\n".'using data from VBR header even though could not find '.MPEG_VALID_CHECK_FRAMES.' consecutive MPEG-audio frames immediately after VBR header (garbage data for '.($GarbageOffsetEnd - $GarbageOffsetStart).' bytes between '.$GarbageOffsetStart.' and '.$GarbageOffsetEnd.')';

								}
							}
						}

						if (isset($ThisFileInfo['mpeg']['audio']['bitrate_mode']) && ($ThisFileInfo['mpeg']['audio']['bitrate_mode'] == 'vbr') && !isset($ThisFileInfo['mpeg']['audio']['VBR_method'])) {
							// VBR file with no VBR header
							$BitrateHistogram = true;
						}
						if ($BitrateHistogram) {

							$ThisFileInfo['mpeg']['audio']['stereo_distribution']  = array('stereo'=>0, 'joint stereo'=>0, 'dual channel'=>0, 'mono'=>0);
							$ThisFileInfo['mpeg']['audio']['version_distribution'] = array('1'=>0, '2'=>0, '2.5'=>0);

							if ($ThisFileInfo['mpeg']['audio']['version'] == '1') {
								if ($ThisFileInfo['mpeg']['audio']['layer'] == 'III') {
									$ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32=>0, 40=>0, 48=>0, 56=>0, 64=>0, 80=>0, 96=>0, 112=>0, 128=>0, 160=>0, 192=>0, 224=>0, 256=>0, 320=>0);
								} elseif ($ThisFileInfo['mpeg']['audio']['layer'] == 'II') {
									$ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32=>0, 48=>0, 56=>0, 64=>0, 80=>0, 96=>0, 112=>0, 128=>0, 160=>0, 192=>0, 224=>0, 256=>0, 320=>0, 384=>0);
								} elseif ($ThisFileInfo['mpeg']['audio']['layer'] == 'I') {
									$ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32=>0, 64=>0, 96=>0, 128=>0, 160=>0, 192=>0, 224=>0, 256=>0, 288=>0, 320=>0, 352=>0, 384=>0, 416=>0, 448=>0);
								}
							} elseif ($ThisFileInfo['mpeg']['audio']['layer'] == 'I') {
								$ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 32=>0, 48=>0, 56=>0, 64=>0, 80=>0, 96=>0, 112=>0, 128=>0, 144=>0, 160=>0, 176=>0, 192=>0, 224=>0, 256=>0);
							} else {
								$ThisFileInfo['mpeg']['audio']['bitrate_distribution'] = array('free'=>0, 8=>0, 16=>0, 24=>0, 32=>0, 40=>0, 48=>0, 56=>0, 64=>0, 80=>0, 96=>0, 112=>0, 128=>0, 144=>0, 160=>0);
							}

							$dummy = array('error'=>$ThisFileInfo['error'], 'warning'=>$ThisFileInfo['warning'], 'avdataend'=>$ThisFileInfo['avdataend'], 'avdataoffset'=>$ThisFileInfo['avdataoffset']);
							$synchstartoffset  = $ThisFileInfo['avdataoffset'];

							$FastMode = false;
							while ($synchstartoffset < ($ThisFileInfo['avdataend'] - 12)) {
								if (decodeMPEGaudioHeader($fd, $synchstartoffset, $dummy, false, false, $FastMode, true)) {
									$thisframebitrate = $MPEGaudioBitrateLookup[$MPEGaudioVersionLookup[$dummy['mpeg']['audio']['raw']['version']]][$MPEGaudioLayerLookup[$dummy['mpeg']['audio']['raw']['layer']]][$dummy['mpeg']['audio']['raw']['bitrate']];

									safe_inc($ThisFileInfo['mpeg']['audio']['bitrate_distribution'][$thisframebitrate]);
									$ThisFileInfo['mpeg']['audio']['stereo_distribution'][$dummy['mpeg']['audio']['channelmode']]++;
									$ThisFileInfo['mpeg']['audio']['version_distribution'][$dummy['mpeg']['audio']['version']]++;
									if (empty($dummy['mpeg']['audio']['framelength'])) {
										$ThisFileInfo['warning'] .= "\n".'Invalid/missing framelength at '.$synchstartoffset.' in histogram analysis - aborting';
										$synchstartoffset++;
										$ThisFileInfo['avdataoffset'] = $synchstartoffset;
										// return false;
									} else {
										$synchstartoffset += $dummy['mpeg']['audio']['framelength'];
									}
								} else {
									//$ThisFileInfo['warning'] .= "\n".'Invalid frame header at '.$synchstartoffset;
									$synchstartoffset++;
									$ThisFileInfo['avdataoffset'] = $synchstartoffset;
								}
								$FastMode = true;
							}
							$bittotal     = 0;
							$framecounter = 0;
							foreach ($ThisFileInfo['mpeg']['audio']['bitrate_distribution'] as $bitratevalue => $bitratecount) {
								$framecounter += $bitratecount;
								if ($bitratevalue != 'free') {
									$bittotal += ($bitratevalue * $bitratecount);
								}
							}
							if ($framecounter == 0) {
								$ThisFileInfo['error'] .= "\n".'Corrupt MP3 file: framecounter == zero';
								return false;
							}
							$ThisFileInfo['mpeg']['audio']['frame_count'] = $framecounter;
							$ThisFileInfo['mpeg']['audio']['bitrate']     = 1000 * ($bittotal / $framecounter);

							$ThisFileInfo['audio']['bitrate'] = $ThisFileInfo['mpeg']['audio']['bitrate'];


							// Definitively set VBR vs CBR, even if the Xing/LAME/VBRI header says differently
							$distinct_bitrates = 0;
							foreach ($ThisFileInfo['mpeg']['audio']['bitrate_distribution'] as $bitrate_value => $bitrate_count) {
								if ($bitrate_count > 0) {
									$distinct_bitrates++;
								}
							}
							if ($distinct_bitrates > 1) {
								$ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'vbr';
							} else {
								$ThisFileInfo['mpeg']['audio']['bitrate_mode'] = 'cbr';
							}
							$ThisFileInfo['audio']['bitrate_mode'] = $ThisFileInfo['mpeg']['audio']['bitrate_mode'];

						}

						break; // exit while()
					}
				}
			}
		}

		$SynchSeekOffset++;
		if (($avdataoffset + $SynchSeekOffset) >= $ThisFileInfo['avdataend']) {
			// end of file/data

			if (empty($ThisFileInfo['mpeg']['audio'])) {

				$ThisFileInfo['error'] .= "\n".'could not find valid MPEG synch before end of file';
				if (isset($ThisFileInfo['audio']['bitrate'])) {
					unset($ThisFileInfo['audio']['bitrate']);
				}
				if (isset($ThisFileInfo['mpeg']['audio'])) {
					unset($ThisFileInfo['mpeg']['audio']);
				}
				if (isset($ThisFileInfo['mpeg']) && (!is_array($ThisFileInfo['mpeg']) || empty($ThisFileInfo['mpeg']))) {
					unset($ThisFileInfo['mpeg']);
				}
				return false;

			}
			break;
		}

	}
	$ThisFileInfo['audio']['bits_per_sample'] = 16;
	$ThisFileInfo['audio']['channels']        = $ThisFileInfo['mpeg']['audio']['channels'];
	$ThisFileInfo['audio']['channelmode']     = $ThisFileInfo['mpeg']['audio']['channelmode'];
	$ThisFileInfo['audio']['sample_rate']     = $ThisFileInfo['mpeg']['audio']['sample_rate'];
	return true;
}


function MPEGaudioVersionArray() {
	static $MPEGaudioVersion = array('2.5', false, '2', '1');
	return $MPEGaudioVersion;
}

function MPEGaudioLayerArray() {
	static $MPEGaudioLayer = array(false, 'III', 'II', 'I');
	return $MPEGaudioLayer;
}

function MPEGaudioBitrateArray() {
	static $MPEGaudioBitrate;
	if (empty($MPEGaudioBitrate)) {
		$MPEGaudioBitrate['1']['I']     = array('free', 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448);
		$MPEGaudioBitrate['1']['II']    = array('free', 32, 48, 56,  64,  80,  96, 112, 128, 160, 192, 224, 256, 320, 384);
		$MPEGaudioBitrate['1']['III']   = array('free', 32, 40, 48,  56,  64,  80,  96, 112, 128, 160, 192, 224, 256, 320);
		$MPEGaudioBitrate['2']['I']     = array('free', 32, 48, 56,  64,  80,  96, 112, 128, 144, 160, 176, 192, 224, 256);
		$MPEGaudioBitrate['2']['II']    = array('free',  8, 16, 24,  32,  40,  48,  56,  64,  80,  96, 112, 128, 144, 160);
		$MPEGaudioBitrate['2']['III']   = $MPEGaudioBitrate['2']['II'];
		$MPEGaudioBitrate['2.5']['I']   = $MPEGaudioBitrate['2']['I'];
		$MPEGaudioBitrate['2.5']['II']  = $MPEGaudioBitrate['2']['II'];
		$MPEGaudioBitrate['2.5']['III'] = $MPEGaudioBitrate['2']['III'];
	}
	return $MPEGaudioBitrate;
}

function MPEGaudioFrequencyArray() {
	static $MPEGaudioFrequency;
	if (empty($MPEGaudioFrequency)) {
		$MPEGaudioFrequency['1']   = array(44100, 48000, 32000);
		$MPEGaudioFrequency['2']   = array(22050, 24000, 16000);
		$MPEGaudioFrequency['2.5'] = array(11025, 12000,  8000);
	}
	return $MPEGaudioFrequency;
}

function MPEGaudioChannelModeArray() {
	static $MPEGaudioChannelMode = array('stereo', 'joint stereo', 'dual channel', 'mono');
	return $MPEGaudioChannelMode;
}

function MPEGaudioModeExtensionArray() {
	static $MPEGaudioModeExtension;
	if (empty($MPEGaudioModeExtension)) {
		$MPEGaudioModeExtension['I']   = array('4-31', '8-31', '12-31', '16-31');
		$MPEGaudioModeExtension['II']  = array('4-31', '8-31', '12-31', '16-31');
		$MPEGaudioModeExtension['III'] = array('', 'IS', 'MS', 'IS+MS');
	}
	return $MPEGaudioModeExtension;
}

function MPEGaudioEmphasisArray() {
	static $MPEGaudioEmphasis = array('none', '50/15ms', false, 'CCIT J.17');
	return $MPEGaudioEmphasis;
}


function MPEGaudioHeaderBytesValid($head4) {
	return MPEGaudioHeaderValid(MPEGaudioHeaderDecode($head4));
}

function MPEGaudioHeaderValid($rawarray, $echoerrors=false) {
	if (($rawarray['synch'] & 0x0FFE) != 0x0FFE) {
		return false;
	}

	static $MPEGaudioVersionLookup;
	static $MPEGaudioLayerLookup;
	static $MPEGaudioBitrateLookup;
	static $MPEGaudioFrequencyLookup;
	static $MPEGaudioChannelModeLookup;
	static $MPEGaudioModeExtensionLookup;
	static $MPEGaudioEmphasisLookup;
	if (empty($MPEGaudioVersionLookup)) {
		$MPEGaudioVersionLookup       = MPEGaudioVersionArray();
		$MPEGaudioLayerLookup         = MPEGaudioLayerArray();
		$MPEGaudioBitrateLookup       = MPEGaudioBitrateArray();
		$MPEGaudioFrequencyLookup     = MPEGaudioFrequencyArray();
		$MPEGaudioChannelModeLookup   = MPEGaudioChannelModeArray();
		$MPEGaudioModeExtensionLookup = MPEGaudioModeExtensionArray();
		$MPEGaudioEmphasisLookup      = MPEGaudioEmphasisArray();
	}

	if (isset($MPEGaudioVersionLookup[$rawarray['version']])) {
		$decodedVersion = $MPEGaudioVersionLookup[$rawarray['version']];
	} else {
		if ($echoerrors) {
			echo "\n".'invalid Version ('.$rawarray['version'].')';
		}
		return false;
	}
	if (isset($MPEGaudioLayerLookup[$rawarray['layer']])) {
		$decodedLayer = $MPEGaudioLayerLookup[$rawarray['layer']];
	} else {
		if ($echoerrors) {
			echo "\n".'invalid Layer ('.$rawarray['layer'].')';
		}
		return false;
	}
	if (!isset($MPEGaudioBitrateLookup[$decodedVersion][$decodedLayer][$rawarray['bitrate']])) {
		if ($echoerrors) {
			echo "\n".'invalid Bitrate ('.$rawarray['bitrate'].')';
		}
		if ($rawarray['bitrate'] == 15) {
			// known issue in LAME 3.90 - 3.93.1 where free-format has bitrate ID of 15 instead of 0
			// let it go through here otherwise file will not be identified
		} else {
			return false;
		}
	}
	if (!isset($MPEGaudioFrequencyLookup[$decodedVersion][$rawarray['sample_rate']])) {
		if ($echoerrors) {
			echo "\n".'invalid Frequency ('.$rawarray['sample_rate'].')';
		}
		return false;
	}
	if (!isset($MPEGaudioChannelModeLookup[$rawarray['channelmode']])) {
		if ($echoerrors) {
			echo "\n".'invalid ChannelMode ('.$rawarray['channelmode'].')';
		}
		return false;
	}
	if (!isset($MPEGaudioModeExtensionLookup[$decodedLayer][$rawarray['modeextension']])) {
		if ($echoerrors) {
			echo "\n".'invalid Mode Extension ('.$rawarray['modeextension'].')';
		}
		return false;
	}
	if (!isset($MPEGaudioEmphasisLookup[$rawarray['emphasis']])) {
		if ($echoerrors) {
			echo "\n".'invalid Emphasis ('.$rawarray['emphasis'].')';
		}
		return false;
	}
	// These are just either set or not set, you can't mess that up :)
	// $rawarray['protection'];
	// $rawarray['padding'];
	// $rawarray['private'];
	// $rawarray['copyright'];
	// $rawarray['original'];

	return true;
}

function MPEGaudioHeaderDecode($Header4Bytes) {
	// AAAA AAAA  AAAB BCCD  EEEE FFGH  IIJJ KLMM
	// A - Frame sync (all bits set)
	// B - MPEG Audio version ID
	// C - Layer description
	// D - Protection bit
	// E - Bitrate index
	// F - Sampling rate frequency index
	// G - Padding bit
	// H - Private bit
	// I - Channel Mode
	// J - Mode extension (Only if Joint stereo)
	// K - Copyright
	// L - Original
	// M - Emphasis

	if (strlen($Header4Bytes) != 4) {
		return false;
	}

	$MPEGrawHeader['synch']         = (BigEndian2Int(substr($Header4Bytes, 0, 2)) & 0xFFE0) >> 4;
	$MPEGrawHeader['version']       = (ord($Header4Bytes{1}) & 0x18) >> 3; //    BB
	$MPEGrawHeader['layer']         = (ord($Header4Bytes{1}) & 0x06) >> 1; //      CC
	$MPEGrawHeader['protection']    = (ord($Header4Bytes{1}) & 0x01);      //        D
	$MPEGrawHeader['bitrate']       = (ord($Header4Bytes{2}) & 0xF0) >> 4; // EEEE
	$MPEGrawHeader['sample_rate']   = (ord($Header4Bytes{2}) & 0x0C) >> 2; //     FF
	$MPEGrawHeader['padding']       = (ord($Header4Bytes{2}) & 0x02) >> 1; //       G
	$MPEGrawHeader['private']       = (ord($Header4Bytes{2}) & 0x01);      //        H
	$MPEGrawHeader['channelmode']   = (ord($Header4Bytes{3}) & 0xC0) >> 6; // II
	$MPEGrawHeader['modeextension'] = (ord($Header4Bytes{3}) & 0x30) >> 4; //   JJ
	$MPEGrawHeader['copyright']     = (ord($Header4Bytes{3}) & 0x08) >> 3; //     K
	$MPEGrawHeader['original']      = (ord($Header4Bytes{3}) & 0x04) >> 2; //      L
	$MPEGrawHeader['emphasis']      = (ord($Header4Bytes{3}) & 0x03);      //       MM

	return $MPEGrawHeader;
}

function MPEGaudioFrameLength(&$bitrate, &$version, &$layer, $padding, &$samplerate) {
	static $AudioFrameLengthCache = array();

	if (!isset($AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate])) {
		$AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate] = false;
		if ($bitrate != 'free') {

			if ($version == '1') {

				if ($layer == 'I') {

					// For Layer I slot is 32 bits long
					$FrameLengthCoefficient = 48;
					$FrameLengthPadding     = ($padding ? 4 : 0);

				} else { // Layer II / III

					// for Layer II and Layer III slot is 8 bits long.
					$FrameLengthCoefficient = 144;
					$FrameLengthPadding     = ($padding ? 1 : 0);

				}

			} else { // MPEG-2 / MPEG-2.5

				if ($layer == 'I') {

					// For Layer I slot is 32 bits long
					$FrameLengthCoefficient = 24;
					$FrameLengthPadding     = ($padding ? 4 : 0);

				} else { // Layer II / III

					// for Layer II and Layer III slot is 8 bits long.
					$FrameLengthCoefficient = 72;
					$FrameLengthPadding     = ($padding ? 1 : 0);

				}

			}

			// FrameLengthInBytes = ((Coefficient * BitRate) / SampleRate) + Padding
			// http://66.96.216.160/cgi-bin/YaBB.pl?board=c&action=display&num=1018474068
			// -> [Finding the next frame synch] on www.r3mix.net forums if the above link goes dead
			if ($samplerate > 0) {
				$AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate] = (int) floor(($FrameLengthCoefficient * 1000 * $bitrate) / $samplerate) + $FrameLengthPadding;
			}
		}
	}
	return $AudioFrameLengthCache[$bitrate][$version][$layer][$padding][$samplerate];
}

function LAMEvbrMethodLookup($VBRmethodID) {
	static $LAMEvbrMethodLookup = array();
	if (empty($LAMEvbrMethodLookup)) {
		$LAMEvbrMethodLookup[0x00] = 'unknown';
		$LAMEvbrMethodLookup[0x01] = 'cbr';
		$LAMEvbrMethodLookup[0x02] = 'abr';
		$LAMEvbrMethodLookup[0x03] = 'vbr-old / vbr-rh';
		$LAMEvbrMethodLookup[0x04] = 'vbr-mtrh';
		$LAMEvbrMethodLookup[0x05] = 'vbr-new / vbr-mt';
	}
	return (isset($LAMEvbrMethodLookup[$VBRmethodID]) ? $LAMEvbrMethodLookup[$VBRmethodID] : '');
}

function LAMEmiscStereoModeLookup($StereoModeID) {
	static $LAMEmiscStereoModeLookup = array();
	if (empty($LAMEmiscStereoModeLookup)) {
		$LAMEmiscStereoModeLookup[0] = 'mono';
		$LAMEmiscStereoModeLookup[1] = 'stereo';
		$LAMEmiscStereoModeLookup[2] = 'dual';
		$LAMEmiscStereoModeLookup[3] = 'joint';
		$LAMEmiscStereoModeLookup[4] = 'forced';
		$LAMEmiscStereoModeLookup[5] = 'auto';
		$LAMEmiscStereoModeLookup[6] = 'intensity';
		$LAMEmiscStereoModeLookup[7] = 'other';
	}
	return (isset($LAMEmiscStereoModeLookup[$StereoModeID]) ? $LAMEmiscStereoModeLookup[$StereoModeID] : '');
}

function LAMEmiscSourceSampleFrequencyLookup($SourceSampleFrequencyID) {
	static $LAMEmiscSourceSampleFrequencyLookup = array();
	if (empty($LAMEmiscSourceSampleFrequencyLookup)) {
		$LAMEmiscSourceSampleFrequencyLookup[0] = '<= 32 kHz';
		$LAMEmiscSourceSampleFrequencyLookup[1] = '44.1 kHz';
		$LAMEmiscSourceSampleFrequencyLookup[2] = '48 kHz';
		$LAMEmiscSourceSampleFrequencyLookup[3] = '> 48kHz';
	}
	return (isset($LAMEmiscSourceSampleFrequencyLookup[$SourceSampleFrequencyID]) ? $LAMEmiscSourceSampleFrequencyLookup[$SourceSampleFrequencyID] : '');
}

function LAMEsurroundInfoLookup($SurroundInfoID) {
	static $LAMEsurroundInfoLookup = array();
	if (empty($LAMEsurroundInfoLookup)) {
		$LAMEsurroundInfoLookup[0] = 'no surround info';
		$LAMEsurroundInfoLookup[1] = 'DPL encoding';
		$LAMEsurroundInfoLookup[2] = 'DPL2 encoding';
		$LAMEsurroundInfoLookup[3] = 'Ambisonic encoding';
	}
	return (isset($LAMEsurroundInfoLookup[$SurroundInfoID]) ? $LAMEsurroundInfoLookup[$SurroundInfoID] : 'reserved');
}

?>

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us