summaryrefslogtreecommitdiffstats
path: root/mm-video/vidc/vdec/test/omx_vdec_test.cpp
blob: 14e445a5ce341ea1b3b3363b724b61d7275599a1 (plain)
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
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
/*--------------------------------------------------------------------------
Copyright (c) 2010-2012, Code Aurora Forum. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of Code Aurora nor
      the names of its contributors may be used to endorse or promote
      products derived from this software without specific prior written
      permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------*/
/*
    An Open max test application ....
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <time.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#include "OMX_QCOMExtns.h"
#include <sys/time.h>

#include <linux/android_pmem.h>

#ifdef _ANDROID_
#include <binder/MemoryHeapBase.h>

extern "C"{
#include<utils/Log.h>
}
#define LOG_TAG "OMX-VDEC-TEST"
#define DEBUG_PRINT
#define DEBUG_PRINT_ERROR ALOGE

//#define __DEBUG_DIVX__ // Define this macro to print (through logcat)
                         // the kind of frames packed per buffer and
                         // timestamps adjustments for divx.

//#define TEST_TS_FROM_SEI // Define this macro to calculate the timestamps
                           // from the SEI and VUI data for H264

#else
#include <glib.h>
#define strlcpy g_strlcpy

#define ALOGE(fmt, args...) fprintf(stderr, fmt, ##args)
#define DEBUG_PRINT printf
#define DEBUG_PRINT_ERROR printf
#endif /* _ANDROID_ */

#include "OMX_Core.h"
#include "OMX_Component.h"
#include "OMX_QCOMExtns.h"
extern "C" {
#include "queue.h"
}

#include <inttypes.h>
#include <linux/msm_mdp.h>
#include <linux/fb.h>

/************************************************************************/
/*              #DEFINES                            */
/************************************************************************/
#define DELAY 66
#define false 0
#define true 1
#define VOP_START_CODE 0x000001B6
#define SHORT_HEADER_START_CODE 0x00008000
#define MPEG2_FRAME_START_CODE 0x00000100
#define MPEG2_SEQ_START_CODE 0x000001B3
#define VC1_START_CODE  0x00000100
#define VC1_FRAME_START_CODE  0x0000010D
#define VC1_FRAME_FIELD_CODE  0x0000010C
#define VC1_SEQUENCE_START_CODE 0x0000010F
#define VC1_ENTRY_POINT_START_CODE 0x0000010E
#define NUMBER_OF_ARBITRARYBYTES_READ  (4 * 1024)
#define VC1_SEQ_LAYER_SIZE_WITHOUT_STRUCTC 32
#define VC1_SEQ_LAYER_SIZE_V1_WITHOUT_STRUCTC 16
static int previous_vc1_au = 0;
#define CONFIG_VERSION_SIZE(param) \
    param.nVersion.nVersion = CURRENT_OMX_SPEC_VERSION;\
    param.nSize = sizeof(param);

#define FAILED(result) (result != OMX_ErrorNone)

#define SUCCEEDED(result) (result == OMX_ErrorNone)
#define SWAPBYTES(ptrA, ptrB) { char t = *ptrA; *ptrA = *ptrB; *ptrB = t;}
#define SIZE_NAL_FIELD_MAX  4
#define MDP_DEINTERLACE 0x80000000

#define ALLOCATE_BUFFER 0

#ifdef MAX_RES_720P
#define PMEM_DEVICE "/dev/pmem_adsp"
#elif MAX_RES_1080P_EBI
#define PMEM_DEVICE "/dev/pmem_adsp"
#elif MAX_RES_1080P
#define PMEM_DEVICE "/dev/pmem_smipool"
#endif

//#define USE_EXTERN_PMEM_BUF

/************************************************************************/
/*              GLOBAL DECLARATIONS                     */
/************************************************************************/
#ifdef _ANDROID_
using namespace android;
#endif

typedef enum {
  CODEC_FORMAT_H264 = 1,
  CODEC_FORMAT_MP4,
  CODEC_FORMAT_H263,
  CODEC_FORMAT_VC1,
  CODEC_FORMAT_DIVX,
  CODEC_FORMAT_MPEG2,
  CODEC_FORMAT_MAX = CODEC_FORMAT_MPEG2
} codec_format;

typedef enum {
  FILE_TYPE_DAT_PER_AU = 1,
  FILE_TYPE_ARBITRARY_BYTES,
  FILE_TYPE_COMMON_CODEC_MAX,

  FILE_TYPE_START_OF_H264_SPECIFIC = 10,
  FILE_TYPE_264_NAL_SIZE_LENGTH = FILE_TYPE_START_OF_H264_SPECIFIC,

  FILE_TYPE_START_OF_MP4_SPECIFIC = 20,
  FILE_TYPE_PICTURE_START_CODE = FILE_TYPE_START_OF_MP4_SPECIFIC,

  FILE_TYPE_START_OF_VC1_SPECIFIC = 30,
  FILE_TYPE_RCV = FILE_TYPE_START_OF_VC1_SPECIFIC,
  FILE_TYPE_VC1,

  FILE_TYPE_START_OF_DIVX_SPECIFIC = 40,
  FILE_TYPE_DIVX_4_5_6 = FILE_TYPE_START_OF_DIVX_SPECIFIC,
  FILE_TYPE_DIVX_311,

  FILE_TYPE_START_OF_MPEG2_SPECIFIC = 50,
  FILE_TYPE_MPEG2_START_CODE = FILE_TYPE_START_OF_MPEG2_SPECIFIC

} file_type;

typedef enum {
  GOOD_STATE = 0,
  PORT_SETTING_CHANGE_STATE,
  ERROR_STATE
} test_status;

typedef enum {
  FREE_HANDLE_AT_LOADED = 1,
  FREE_HANDLE_AT_IDLE,
  FREE_HANDLE_AT_EXECUTING,
  FREE_HANDLE_AT_PAUSE
} freeHandle_test;

struct temp_egl {
    int pmem_fd;
    int offset;
};

static int (*Read_Buffer)(OMX_BUFFERHEADERTYPE  *pBufHdr );

int inputBufferFileFd;

FILE * outputBufferFile;
FILE * seqFile;
int takeYuvLog = 0;
int displayYuv = 0;
int displayWindow = 0;
int realtime_display = 0;

Queue *etb_queue = NULL;
Queue *fbd_queue = NULL;

pthread_t ebd_thread_id;
pthread_t fbd_thread_id;
void* ebd_thread(void*);
void* fbd_thread(void*);

pthread_mutex_t etb_lock;
pthread_mutex_t fbd_lock;
pthread_mutex_t lock;
pthread_cond_t cond;
pthread_mutex_t eos_lock;
pthread_cond_t eos_cond;
pthread_mutex_t enable_lock;

sem_t etb_sem;
sem_t fbd_sem;
sem_t seq_sem;
sem_t in_flush_sem, out_flush_sem;

OMX_PARAM_PORTDEFINITIONTYPE portFmt;
OMX_PORT_PARAM_TYPE portParam;
OMX_ERRORTYPE error;
OMX_COLOR_FORMATTYPE color_fmt;
static bool input_use_buffer = false,output_use_buffer = false;
QOMX_VIDEO_DECODER_PICTURE_ORDER picture_order;

#ifdef MAX_RES_1080P
unsigned int color_fmt_type = 1;
#else
unsigned int color_fmt_type = 0;
#endif

#define CLR_KEY  0xe8fd
#define COLOR_BLACK_RGBA_8888 0x00000000
#define FRAMEBUFFER_32

static int fb_fd = -1;
static struct fb_var_screeninfo vinfo;
static struct fb_fix_screeninfo finfo;
static struct mdp_overlay overlay, *overlayp;
static struct msmfb_overlay_data ov_front;
static int vid_buf_front_id;
static char tempbuf[16];
int overlay_fb(struct OMX_BUFFERHEADERTYPE *pBufHdr);
void overlay_set();
void overlay_unset();
void render_fb(struct OMX_BUFFERHEADERTYPE *pBufHdr);
int disable_output_port();
int enable_output_port();
int output_port_reconfig();
void free_output_buffers();
int open_display();
void close_display();
/************************************************************************/
/*              GLOBAL INIT                 */
/************************************************************************/
int input_buf_cnt = 0;
int height =0, width =0;
int sliceheight = 0, stride = 0;
int used_ip_buf_cnt = 0;
unsigned free_op_buf_cnt = 0;
volatile int event_is_done = 0;
int ebd_cnt= 0, fbd_cnt = 0;
int bInputEosReached = 0;
int bOutputEosReached = 0;
char in_filename[512];
char seq_file_name[512];
unsigned char seq_enabled = 0;
bool anti_flickering = true;
unsigned char flush_input_progress = 0, flush_output_progress = 0;
unsigned cmd_data = ~(unsigned)0, etb_count = 0;

char curr_seq_command[100];
OMX_S64 timeStampLfile = 0;
int fps = 30;
unsigned int timestampInterval = 33333;
codec_format  codec_format_option;
file_type     file_type_option;
freeHandle_test freeHandle_option;
int nalSize = 0;
int sent_disabled = 0;
int waitForPortSettingsChanged = 1;
test_status currentStatus = GOOD_STATE;
struct timeval t_start = {0, 0}, t_end = {0, 0};

//* OMX Spec Version supported by the wrappers. Version = 1.1 */
const OMX_U32 CURRENT_OMX_SPEC_VERSION = 0x00000101;
OMX_COMPONENTTYPE* dec_handle = 0;

OMX_BUFFERHEADERTYPE  **pInputBufHdrs = NULL;
OMX_BUFFERHEADERTYPE  **pOutYUVBufHdrs= NULL;

static OMX_BOOL use_external_pmem_buf = OMX_FALSE;

int rcv_v1=0;
static struct temp_egl **p_eglHeaders = NULL;
static unsigned use_buf_virt_addr[32];

OMX_QCOM_PLATFORM_PRIVATE_LIST      *pPlatformList = NULL;
OMX_QCOM_PLATFORM_PRIVATE_ENTRY     *pPlatformEntry = NULL;
OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *pPMEMInfo = NULL;


static int bHdrflag = 0;

/* Performance related variable*/
//QPERF_INIT(render_fb);
//QPERF_INIT(client_decode);

/************************************************************************/
/*              GLOBAL FUNC DECL                        */
/************************************************************************/
int Init_Decoder();
int Play_Decoder();
int run_tests();

/**************************************************************************/
/*              STATIC DECLARATIONS                       */
/**************************************************************************/
static int video_playback_count = 1;
static int open_video_file ();
static int Read_Buffer_From_DAT_File(OMX_BUFFERHEADERTYPE  *pBufHdr );
static int Read_Buffer_ArbitraryBytes(OMX_BUFFERHEADERTYPE  *pBufHdr);
static int Read_Buffer_From_Vop_Start_Code_File(OMX_BUFFERHEADERTYPE  *pBufHdr);
static int Read_Buffer_From_Mpeg2_Start_Code(OMX_BUFFERHEADERTYPE  *pBufHdr);
static int Read_Buffer_From_Size_Nal(OMX_BUFFERHEADERTYPE  *pBufHdr);
static int Read_Buffer_From_RCV_File_Seq_Layer(OMX_BUFFERHEADERTYPE  *pBufHdr);
static int Read_Buffer_From_RCV_File(OMX_BUFFERHEADERTYPE  *pBufHdr);
static int Read_Buffer_From_VC1_File(OMX_BUFFERHEADERTYPE  *pBufHdr);
static int Read_Buffer_From_DivX_4_5_6_File(OMX_BUFFERHEADERTYPE  *pBufHdr);
static int Read_Buffer_From_DivX_311_File(OMX_BUFFERHEADERTYPE  *pBufHdr);

static OMX_ERRORTYPE Allocate_Buffer ( OMX_COMPONENTTYPE *dec_handle,
                                       OMX_BUFFERHEADERTYPE  ***pBufHdrs,
                                       OMX_U32 nPortIndex,
                                       long bufCntMin, long bufSize);

static OMX_ERRORTYPE use_input_buffer(OMX_COMPONENTTYPE      *dec_handle,
                                OMX_BUFFERHEADERTYPE ***bufferHdr,
                                OMX_U32              nPortIndex,
                                OMX_U32              bufSize,
                                long                 bufcnt);

static OMX_ERRORTYPE use_output_buffer(OMX_COMPONENTTYPE      *dec_handle,
                                OMX_BUFFERHEADERTYPE ***bufferHdr,
                                OMX_U32              nPortIndex,
                                OMX_U32              bufSize,
                                long                 bufcnt);

static OMX_ERRORTYPE use_output_buffer_multiple_fd(OMX_COMPONENTTYPE      *dec_handle,
                                                   OMX_BUFFERHEADERTYPE ***bufferHdr,
                                                   OMX_U32              nPortIndex,
                                                   OMX_U32              bufSize,
                                                   long                 bufcnt);

static OMX_ERRORTYPE EventHandler(OMX_IN OMX_HANDLETYPE hComponent,
                                  OMX_IN OMX_PTR pAppData,
                                  OMX_IN OMX_EVENTTYPE eEvent,
                                  OMX_IN OMX_U32 nData1, OMX_IN OMX_U32 nData2,
                                  OMX_IN OMX_PTR pEventData);
static OMX_ERRORTYPE EmptyBufferDone(OMX_IN OMX_HANDLETYPE hComponent,
                                     OMX_IN OMX_PTR pAppData,
                                     OMX_IN OMX_BUFFERHEADERTYPE* pBuffer);
static OMX_ERRORTYPE FillBufferDone(OMX_OUT OMX_HANDLETYPE hComponent,
                                    OMX_OUT OMX_PTR pAppData,
                                    OMX_OUT OMX_BUFFERHEADERTYPE* pBuffer);

static void do_freeHandle_and_clean_up(bool isDueToError);

#ifndef USE_ION
static bool align_pmem_buffers(int pmem_fd, OMX_U32 buffer_size,
                                  OMX_U32 alignment);
#endif
void getFreePmem();
static  int clip2(int x)
    {
        x = x -1;
        x = x | x >> 1;
        x = x | x >> 2;
        x = x | x >> 4;
        x = x | x >> 16;
        x = x + 1;
        return x;
    }
void wait_for_event(void)
{
    DEBUG_PRINT("Waiting for event\n");
    pthread_mutex_lock(&lock);
    while (event_is_done == 0) {
        pthread_cond_wait(&cond, &lock);
    }
    event_is_done = 0;
    pthread_mutex_unlock(&lock);
    DEBUG_PRINT("Running .... get the event\n");
}

void event_complete(void )
{
    pthread_mutex_lock(&lock);
    if (event_is_done == 0) {
        event_is_done = 1;
        pthread_cond_broadcast(&cond);
    }
    pthread_mutex_unlock(&lock);
}
int get_next_command(FILE *seq_file)
{
    int i = -1;
    do{
        i++;
        if(fread(&curr_seq_command[i], 1, 1, seq_file) != 1)
            return -1;
    }while(curr_seq_command[i] != '\n');
    curr_seq_command[i] = 0;
    printf("\n cmd_str = %s", curr_seq_command);
    return 0;
}

int process_current_command(const char *seq_command)
{
    char *data_str = NULL;
    unsigned int data = 0, bufCnt = 0, i = 0;
    int frameSize;

    if(strstr(seq_command, "pause") == seq_command)
    {
        printf("\n\n $$$$$   PAUSE    $$$$$");
        data_str = (char*)seq_command + strlen("pause") + 1;
        data = atoi(data_str);
        printf("\n After frame number %u", data);
        cmd_data = data;
        sem_wait(&seq_sem);
        if (!bOutputEosReached && !bInputEosReached)
        {
            printf("\n Sending PAUSE cmd to OMX compt");
            OMX_SendCommand(dec_handle, OMX_CommandStateSet, OMX_StatePause,0);
            wait_for_event();
            printf("\n EventHandler for PAUSE DONE");
        }
        else
            seq_enabled = 0;
    }
    else if(strstr(seq_command, "sleep") == seq_command)
    {
        printf("\n\n $$$$$   SLEEP    $$$$$");
        data_str = (char*)seq_command + strlen("sleep") + 1;
        data = atoi(data_str);
        printf("\n Sleep Time = %u ms", data);
        usleep(data*1000);
    }
    else if(strstr(seq_command, "resume") == seq_command)
    {
        printf("\n\n $$$$$   RESUME    $$$$$");
        printf("\n Immediate effect");
        printf("\n Sending RESUME cmd to OMX compt");
        OMX_SendCommand(dec_handle, OMX_CommandStateSet, OMX_StateExecuting,0);
        wait_for_event();
        printf("\n EventHandler for RESUME DONE");
    }
    else if(strstr(seq_command, "flush") == seq_command)
    {
        printf("\n\n $$$$$   FLUSH    $$$$$");
        data_str = (char*)seq_command + strlen("flush") + 1;
        data = atoi(data_str);
        printf("\n After frame number %u", data);
        if (previous_vc1_au)
        {
            printf("\n Flush not allowed on Field boundary");
            return 0;
        }
        cmd_data = data;
        sem_wait(&seq_sem);
        if (!bOutputEosReached && !bInputEosReached)
        {
            printf("\n Sending FLUSH cmd to OMX compt");
            flush_input_progress = 1;
            flush_output_progress = 1;
            OMX_SendCommand(dec_handle, OMX_CommandFlush, OMX_ALL, 0);
            wait_for_event();
            printf("\n EventHandler for FLUSH DONE");
            printf("\n Post EBD_thread flush sem");
            sem_post(&in_flush_sem);
            printf("\n Post FBD_thread flush sem");
            sem_post(&out_flush_sem);
        }
        else
            seq_enabled = 0;
    }
    else if(strstr(seq_command, "disable_op") == seq_command)
    {
        printf("\n\n $$$$$   DISABLE OP PORT    $$$$$");
        data_str = (char*)seq_command + strlen("disable_op") + 1;
        data = atoi(data_str);
        printf("\n After frame number %u", data);
        cmd_data = data;
        sem_wait(&seq_sem);
        printf("\n Sending DISABLE OP cmd to OMX compt");
        if (disable_output_port() != 0)
        {
            printf("\n ERROR: While DISABLE OP...");
            do_freeHandle_and_clean_up(true);
            return -1;
        }
        else
            printf("\n EventHandler for DISABLE OP");
    }
    else if(strstr(seq_command, "enable_op") == seq_command)
    {
        printf("\n\n $$$$$   ENABLE OP PORT    $$$$$");
        data_str = (char*)seq_command + strlen("enable_op") + 1;
        printf("\n Sending ENABLE OP cmd to OMX compt");
        if (enable_output_port() != 0)
        {
            printf("\n ERROR: While ENABLE OP...");
            do_freeHandle_and_clean_up(true);
            return -1;
        }
        else
            printf("\n EventHandler for ENABLE OP");
    }
    else
    {
        printf("\n\n $$$$$   INVALID CMD    $$$$$");
        printf("\n seq_command[%s] is invalid", seq_command);
        seq_enabled = 0;
    }
    return 0;
}

void PrintFramePackArrangement(OMX_QCOM_FRAME_PACK_ARRANGEMENT framePackingArrangement)
{
   printf("id (%d)\n",
          framePackingArrangement.id);
   printf("cancel_flag (%d)\n",
          framePackingArrangement.cancel_flag);
   printf("type (%d)\n",
          framePackingArrangement.type);
   printf("quincunx_sampling_flag (%d)\n",
          framePackingArrangement.quincunx_sampling_flag);
   printf("content_interpretation_type (%d)\n",
          framePackingArrangement.content_interpretation_type);
   printf("spatial_flipping_flag (%d)\n",
          framePackingArrangement.spatial_flipping_flag);
   printf("frame0_flipped_flag (%d)\n",
          framePackingArrangement.frame0_flipped_flag);
   printf("field_views_flag (%d)\n",
          framePackingArrangement.field_views_flag);
   printf("current_frame_is_frame0_flag (%d)\n",
          framePackingArrangement.current_frame_is_frame0_flag);
   printf("frame0_self_contained_flag (%d)\n",
          framePackingArrangement.frame0_self_contained_flag);
   printf("frame1_self_contained_flag (%d)\n",
          framePackingArrangement.frame1_self_contained_flag);
   printf("frame0_grid_position_x (%d)\n",
          framePackingArrangement.frame0_grid_position_x);
   printf("frame0_grid_position_y (%d)\n",
          framePackingArrangement.frame0_grid_position_y);
   printf("frame1_grid_position_x (%d)\n",
          framePackingArrangement.frame1_grid_position_x);
   printf("frame1_grid_position_y (%d)\n",
          framePackingArrangement.frame1_grid_position_y);
   printf("reserved_byte (%d)\n",
          framePackingArrangement.reserved_byte);
   printf("repetition_period (%d)\n",
          framePackingArrangement.repetition_period);
   printf("extension_flag (%d)\n",
          framePackingArrangement.extension_flag);
}
void* ebd_thread(void* pArg)
{
  while(currentStatus != ERROR_STATE)
  {
    int readBytes =0;
    OMX_BUFFERHEADERTYPE* pBuffer = NULL;

    if(flush_input_progress)
    {
        DEBUG_PRINT("\n EBD_thread flush wait start");
        sem_wait(&in_flush_sem);
        DEBUG_PRINT("\n EBD_thread flush wait complete");
    }

    sem_wait(&etb_sem);
    pthread_mutex_lock(&etb_lock);
    pBuffer = (OMX_BUFFERHEADERTYPE *) pop(etb_queue);
    pthread_mutex_unlock(&etb_lock);
    if(pBuffer == NULL)
    {
      DEBUG_PRINT_ERROR("Error - No etb pBuffer to dequeue\n");
      continue;
    }

    pBuffer->nOffset = 0;
    if((readBytes = Read_Buffer(pBuffer)) > 0) {
        pBuffer->nFilledLen = readBytes;
        DEBUG_PRINT("%s: Timestamp sent(%lld)", __FUNCTION__, pBuffer->nTimeStamp);
        OMX_EmptyThisBuffer(dec_handle,pBuffer);
        etb_count++;
    }
    else
    {
        pBuffer->nFlags |= OMX_BUFFERFLAG_EOS;
        bInputEosReached = true;
        pBuffer->nFilledLen = readBytes;
        DEBUG_PRINT("%s: Timestamp sent(%lld)", __FUNCTION__, pBuffer->nTimeStamp);
        OMX_EmptyThisBuffer(dec_handle,pBuffer);
        DEBUG_PRINT("EBD::Either EOS or Some Error while reading file\n");
        etb_count++;
        break;
    }
  }
  return NULL;
}

void* fbd_thread(void* pArg)
{
  long unsigned act_time = 0, display_time = 0, render_time = 5e3, lipsync = 15e3;
  struct timeval t_avsync = {0, 0}, base_avsync = {0, 0};
  float total_time = 0;
  int canDisplay = 1, contigous_drop_frame = 0, bytes_written = 0, ret = 0;
  OMX_S64 base_timestamp = 0, lastTimestamp = 0;
  OMX_BUFFERHEADERTYPE *pBuffer = NULL, *pPrevBuff = NULL;
  pthread_mutex_lock(&eos_lock);

  DEBUG_PRINT("First Inside %s\n", __FUNCTION__);
  while(currentStatus != ERROR_STATE && !bOutputEosReached)
  {
    pthread_mutex_unlock(&eos_lock);
    DEBUG_PRINT("Inside %s\n", __FUNCTION__);
    if(flush_output_progress)
    {
        DEBUG_PRINT("\n FBD_thread flush wait start");
        sem_wait(&out_flush_sem);
        DEBUG_PRINT("\n FBD_thread flush wait complete");
    }
    sem_wait(&fbd_sem);
    pthread_mutex_lock(&enable_lock);
    if (sent_disabled)
    {
      pthread_mutex_unlock(&enable_lock);
      pthread_mutex_lock(&fbd_lock);
      if (free_op_buf_cnt == portFmt.nBufferCountActual)
        free_output_buffers();
      pthread_mutex_unlock(&fbd_lock);
      pthread_mutex_lock(&eos_lock);
      continue;
    }
    pthread_mutex_unlock(&enable_lock);
    if (anti_flickering)
      pPrevBuff = pBuffer;
    pthread_mutex_lock(&fbd_lock);
    pBuffer = (OMX_BUFFERHEADERTYPE *)pop(fbd_queue);
    pthread_mutex_unlock(&fbd_lock);
    if (pBuffer == NULL)
    {
      if (anti_flickering)
        pBuffer = pPrevBuff;
      DEBUG_PRINT("Error - No pBuffer to dequeue\n");
      pthread_mutex_lock(&eos_lock);
      continue;
    }
    else if (pBuffer->nFilledLen > 0)
    {
        if (!fbd_cnt)
        {
            gettimeofday(&t_start, NULL);
        }
      fbd_cnt++;
      DEBUG_PRINT("%s: fbd_cnt(%d) Buf(%p) Timestamp(%lld)",
        __FUNCTION__, fbd_cnt, pBuffer, pBuffer->nTimeStamp);
      canDisplay = 1;
      if (realtime_display)
      {
        if (pBuffer->nTimeStamp != (lastTimestamp + timestampInterval))
        {
            DEBUG_PRINT("Unexpected timestamp[%lld]! Expected[%lld]\n",
                pBuffer->nTimeStamp, lastTimestamp + timestampInterval);
        }
        lastTimestamp = pBuffer->nTimeStamp;
        gettimeofday(&t_avsync, NULL);
        if (!base_avsync.tv_sec && !base_avsync.tv_usec)
        {
          display_time = 0;
          base_avsync = t_avsync;
          base_timestamp = pBuffer->nTimeStamp;
          DEBUG_PRINT("base_avsync Sec(%lu) uSec(%lu) base_timestamp(%lld)",
              base_avsync.tv_sec, base_avsync.tv_usec, base_timestamp);
        }
        else
        {
          act_time = (t_avsync.tv_sec - base_avsync.tv_sec) * 1e6
                     + t_avsync.tv_usec - base_avsync.tv_usec;
          display_time = pBuffer->nTimeStamp - base_timestamp;
          DEBUG_PRINT("%s: act_time(%lu) display_time(%lu)",
              __FUNCTION__, act_time, display_time);
               //Frame rcvd on time
          if (((act_time + render_time) >= (display_time - lipsync) &&
               (act_time + render_time) <= (display_time + lipsync)) ||
               //Display late frame
               (contigous_drop_frame > 5))
              display_time = 0;
          else if ((act_time + render_time) < (display_time - lipsync))
              //Delaying early frame
              display_time -= (lipsync + act_time + render_time);
          else
          {
              //Dropping late frame
              canDisplay = 0;
              contigous_drop_frame++;
          }
        }
      }
      if (displayYuv && canDisplay)
      {
          if (display_time)
              usleep(display_time);
          ret = overlay_fb(pBuffer);
          if (ret != 0)
          {
            printf("\nERROR in overlay_fb, disabling display!");
            close_display();
            displayYuv = 0;
          }
          usleep(render_time);
          contigous_drop_frame = 0;
      }

      if (takeYuvLog)
      {
          bytes_written = fwrite((const char *)pBuffer->pBuffer,
                                  pBuffer->nFilledLen,1,outputBufferFile);
          if (bytes_written < 0) {
              DEBUG_PRINT("\nFillBufferDone: Failed to write to the file\n");
          }
          else {
              DEBUG_PRINT("\nFillBufferDone: Wrote %d YUV bytes to the file\n",
                            bytes_written);
          }
      }
      if (pBuffer->nFlags & OMX_BUFFERFLAG_EXTRADATA)
      {
        OMX_OTHER_EXTRADATATYPE *pExtra;
        DEBUG_PRINT(">> BUFFER WITH EXTRA DATA RCVD <<<");
        pExtra = (OMX_OTHER_EXTRADATATYPE *)
                 ((unsigned)(pBuffer->pBuffer + pBuffer->nOffset +
                  pBuffer->nFilledLen + 3)&(~3));
        while(pExtra &&
              (OMX_U8*)pExtra < (pBuffer->pBuffer + pBuffer->nAllocLen) &&
              pExtra->eType != OMX_ExtraDataNone )
        {
          DEBUG_PRINT("ExtraData : pBuf(%p) BufTS(%lld) Type(%x) DataSz(%u)",
               pBuffer, pBuffer->nTimeStamp, pExtra->eType, pExtra->nDataSize);
          switch (pExtra->eType)
          {
            case OMX_ExtraDataInterlaceFormat:
            {
              OMX_STREAMINTERLACEFORMAT *pInterlaceFormat = (OMX_STREAMINTERLACEFORMAT *)pExtra->data;
              DEBUG_PRINT("OMX_ExtraDataInterlaceFormat: Buf(%p) TSmp(%lld) IntPtr(%p) Fmt(%x)",
                pBuffer->pBuffer, pBuffer->nTimeStamp,
                pInterlaceFormat, pInterlaceFormat->nInterlaceFormats);
              break;
            }
            case OMX_ExtraDataFrameInfo:
            {
              OMX_QCOM_EXTRADATA_FRAMEINFO *frame_info = (OMX_QCOM_EXTRADATA_FRAMEINFO *)pExtra->data;
              DEBUG_PRINT("OMX_ExtraDataFrameInfo: Buf(%p) TSmp(%lld) PicType(%u) IntT(%u) ConMB(%u)",
                pBuffer->pBuffer, pBuffer->nTimeStamp, frame_info->ePicType,
                frame_info->interlaceType, frame_info->nConcealedMacroblocks);
              DEBUG_PRINT(" FrmRate(%u), AspRatioX(%u), AspRatioY(%u) ",
                frame_info->nFrameRate, frame_info->aspectRatio.aspectRatioX,
                frame_info->aspectRatio.aspectRatioY);
              DEBUG_PRINT("PANSCAN numWindows(%d)", frame_info->panScan.numWindows);
              for (int i = 0; i < frame_info->panScan.numWindows; i++)
              {
                DEBUG_PRINT("WINDOW Lft(%d) Tp(%d) Rgt(%d) Bttm(%d)",
                  frame_info->panScan.window[i].x,
                  frame_info->panScan.window[i].y,
                  frame_info->panScan.window[i].dx,
                  frame_info->panScan.window[i].dy);
              }
              break;
            }
            break;
            case OMX_ExtraDataConcealMB:
            {
              OMX_U8 data = 0, *data_ptr = (OMX_U8 *)pExtra->data;
              OMX_U32 concealMBnum = 0, bytes_cnt = 0;
              while (bytes_cnt < pExtra->nDataSize)
              {
                data = *data_ptr;
                while (data)
                {
                  concealMBnum += (data&0x01);
                  data >>= 1;
                }
                data_ptr++;
                bytes_cnt++;
              }
              DEBUG_PRINT("OMX_ExtraDataConcealMB: Buf(%p) TSmp(%lld) ConcealMB(%u)",
                pBuffer->pBuffer, pBuffer->nTimeStamp, concealMBnum);
            }
            break;
            default:
              DEBUG_PRINT_ERROR("Unknown Extrata!");
          }
          if (pExtra->nSize < (pBuffer->nAllocLen - (OMX_U32)pExtra))
            pExtra = (OMX_OTHER_EXTRADATATYPE *) (((OMX_U8 *) pExtra) + pExtra->nSize);
          else
          {
            DEBUG_PRINT_ERROR("ERROR: Extradata pointer overflow buffer(%p) extra(%p)",
              pBuffer, pExtra);
            pExtra = NULL;
          }
        }
      }
    }
    if(pBuffer->nFlags & QOMX_VIDEO_BUFFERFLAG_EOSEQ)
    {
        DEBUG_PRINT("\n");
        DEBUG_PRINT("***************************************************\n");
        DEBUG_PRINT("FillBufferDone: End Of Sequence Received\n");
        DEBUG_PRINT("***************************************************\n");
    }
    if(pBuffer->nFlags & OMX_BUFFERFLAG_DATACORRUPT)
    {
      DEBUG_PRINT("\n");
      DEBUG_PRINT("***************************************************\n");
      DEBUG_PRINT("FillBufferDone: OMX_BUFFERFLAG_DATACORRUPT Received\n");
      DEBUG_PRINT("***************************************************\n");
    }
    /********************************************************************/
    /* De-Initializing the open max and relasing the buffers and */
    /* closing the files.*/
    /********************************************************************/
    if (pBuffer->nFlags & OMX_BUFFERFLAG_EOS )
    {
      OMX_QCOM_FRAME_PACK_ARRANGEMENT framePackingArrangement;
      OMX_GetConfig(dec_handle,
                   (OMX_INDEXTYPE)OMX_QcomIndexConfigVideoFramePackingArrangement,
                    &framePackingArrangement);
      PrintFramePackArrangement(framePackingArrangement);

      gettimeofday(&t_end, NULL);
      total_time = ((float) ((t_end.tv_sec - t_start.tv_sec) * 1e6
                     + t_end.tv_usec - t_start.tv_usec))/ 1e6;
      //total frames is fbd_cnt - 1 since the start time is
      //recorded after the first frame is decoded.
      printf("\nAvg decoding frame rate=%f\n", (fbd_cnt - 1)/total_time);

      DEBUG_PRINT("***************************************************\n");
      DEBUG_PRINT("FillBufferDone: End Of Stream Reached\n");
      DEBUG_PRINT("***************************************************\n");
      pthread_mutex_lock(&eos_lock);
      bOutputEosReached = true;
      break;
    }

    pthread_mutex_lock(&enable_lock);
    if (flush_output_progress || sent_disabled)
    {
        pBuffer->nFilledLen = 0;
        pBuffer->nFlags &= ~OMX_BUFFERFLAG_EXTRADATA;
        pthread_mutex_lock(&fbd_lock);
        if ( pPrevBuff != NULL ) {
            push(fbd_queue, (void *)pPrevBuff);
            pPrevBuff = NULL;
        }
        if(push(fbd_queue, (void *)pBuffer) < 0)
        {
          DEBUG_PRINT_ERROR("Error in enqueueing fbd_data\n");
        }
        else
          sem_post(&fbd_sem);
        pthread_mutex_unlock(&fbd_lock);
    }
    else
    {
        if (!anti_flickering)
          pPrevBuff = pBuffer;
        if (pPrevBuff)
        {
          pthread_mutex_lock(&fbd_lock);
          pthread_mutex_lock(&eos_lock);
          if (!bOutputEosReached)
          {
              if ( OMX_FillThisBuffer(dec_handle, pPrevBuff) == OMX_ErrorNone ) {
                  free_op_buf_cnt--;
              }
          }
          pthread_mutex_unlock(&eos_lock);
          pthread_mutex_unlock(&fbd_lock);
        }
    }
    pthread_mutex_unlock(&enable_lock);
    if(cmd_data <= fbd_cnt)
    {
      sem_post(&seq_sem);
      printf("\n Posted seq_sem Frm(%d) Req(%d)", fbd_cnt, cmd_data);
      cmd_data = ~(unsigned)0;
    }
    pthread_mutex_lock(&eos_lock);
  }
  if(seq_enabled)
  {
      seq_enabled = 0;
      sem_post(&seq_sem);
      printf("\n Posted seq_sem in EOS \n");
  }
  pthread_cond_broadcast(&eos_cond);
  pthread_mutex_unlock(&eos_lock);
  return NULL;
}

OMX_ERRORTYPE EventHandler(OMX_IN OMX_HANDLETYPE hComponent,
                           OMX_IN OMX_PTR pAppData,
                           OMX_IN OMX_EVENTTYPE eEvent,
                           OMX_IN OMX_U32 nData1, OMX_IN OMX_U32 nData2,
                           OMX_IN OMX_PTR pEventData)
{
    DEBUG_PRINT("Function %s \n", __FUNCTION__);

    switch(eEvent) {
        case OMX_EventCmdComplete:
            DEBUG_PRINT("\n OMX_EventCmdComplete \n");
            if(OMX_CommandPortDisable == (OMX_COMMANDTYPE)nData1)
            {
                DEBUG_PRINT("*********************************************\n");
                DEBUG_PRINT("Recieved DISABLE Event Command Complete[%d]\n",nData2);
                DEBUG_PRINT("*********************************************\n");
            }
            else if(OMX_CommandPortEnable == (OMX_COMMANDTYPE)nData1)
            {
                DEBUG_PRINT("*********************************************\n");
                DEBUG_PRINT("Recieved ENABLE Event Command Complete[%d]\n",nData2);
                DEBUG_PRINT("*********************************************\n");
                if (currentStatus == PORT_SETTING_CHANGE_STATE)
                  currentStatus = GOOD_STATE;
                pthread_mutex_lock(&enable_lock);
                sent_disabled = 0;
                pthread_mutex_unlock(&enable_lock);
            }
            else if(OMX_CommandFlush == (OMX_COMMANDTYPE)nData1)
            {
                DEBUG_PRINT("*********************************************\n");
                DEBUG_PRINT("Received FLUSH Event Command Complete[%d]\n",nData2);
                DEBUG_PRINT("*********************************************\n");
                if (nData2 == 0)
                    flush_input_progress = 0;
                else if (nData2 == 1)
                    flush_output_progress = 0;
            }
            if (!flush_input_progress && !flush_output_progress)
                event_complete();
            break;

        case OMX_EventError:
            printf("*********************************************\n");
            printf("Received OMX_EventError Event Command !\n");
            printf("*********************************************\n");
            currentStatus = ERROR_STATE;
            if (OMX_ErrorInvalidState == (OMX_ERRORTYPE)nData1 ||
                OMX_ErrorHardware == (OMX_ERRORTYPE)nData1)
            {
              printf("Invalid State or hardware error \n");
              if(event_is_done == 0)
              {
                DEBUG_PRINT("Event error in the middle of Decode \n");
                pthread_mutex_lock(&eos_lock);
                bOutputEosReached = true;
                pthread_mutex_unlock(&eos_lock);
                if(seq_enabled)
                {
                    seq_enabled = 0;
                    sem_post(&seq_sem);
                    printf("\n Posted seq_sem in ERROR");
                }
              }
            }
            if (waitForPortSettingsChanged)
            {
	            waitForPortSettingsChanged = 0;
	            event_complete();
            }
            break;
        case OMX_EventPortSettingsChanged:
            DEBUG_PRINT("OMX_EventPortSettingsChanged port[%d]\n", nData1);
            currentStatus = PORT_SETTING_CHANGE_STATE;
            if (waitForPortSettingsChanged)
            {
	            waitForPortSettingsChanged = 0;
	            event_complete();
            }
            else
            {
                pthread_mutex_lock(&eos_lock);
                pthread_cond_broadcast(&eos_cond);
                pthread_mutex_unlock(&eos_lock);
            }
            break;

        case OMX_EventBufferFlag:
            DEBUG_PRINT("OMX_EventBufferFlag port[%d] flags[%x]\n", nData1, nData2);
            if (nData1 == 1 && (nData2 & OMX_BUFFERFLAG_EOS)) {
                pthread_mutex_lock(&eos_lock);
                bOutputEosReached = true;
                pthread_mutex_unlock(&eos_lock);
                if(seq_enabled)
                {
                    seq_enabled = 0;
                    sem_post(&seq_sem);
                    printf("\n Posted seq_sem in OMX_EventBufferFlag");
                }
            }
            else
            {
                DEBUG_PRINT_ERROR("OMX_EventBufferFlag Event not handled\n");
            }
            break;
        case OMX_EventIndexsettingChanged:
            DEBUG_PRINT("OMX_EventIndexSettingChanged Interlace mode[%x]\n", nData1);
            break;
        default:
            DEBUG_PRINT_ERROR("ERROR - Unknown Event \n");
            break;
    }
    return OMX_ErrorNone;
}

OMX_ERRORTYPE EmptyBufferDone(OMX_IN OMX_HANDLETYPE hComponent,
                              OMX_IN OMX_PTR pAppData,
                              OMX_IN OMX_BUFFERHEADERTYPE* pBuffer)
{
    int readBytes =0; int bufCnt=0;
    OMX_ERRORTYPE result;

    DEBUG_PRINT("Function %s cnt[%d]\n", __FUNCTION__, ebd_cnt);
    ebd_cnt++;


    if(bInputEosReached) {
        DEBUG_PRINT("*****EBD:Input EoS Reached************\n");
        return OMX_ErrorNone;
    }

    pthread_mutex_lock(&etb_lock);
    if(push(etb_queue, (void *) pBuffer) < 0)
    {
       DEBUG_PRINT_ERROR("Error in enqueue  ebd data\n");
       return OMX_ErrorUndefined;
    }
    pthread_mutex_unlock(&etb_lock);
    sem_post(&etb_sem);

    return OMX_ErrorNone;
}

OMX_ERRORTYPE FillBufferDone(OMX_OUT OMX_HANDLETYPE hComponent,
                             OMX_OUT OMX_PTR pAppData,
                             OMX_OUT OMX_BUFFERHEADERTYPE* pBuffer)
{
    DEBUG_PRINT("Inside %s callback_count[%d] \n", __FUNCTION__, fbd_cnt);

    /* Test app will assume there is a dynamic port setting
     * In case that there is no dynamic port setting, OMX will not call event cb,
     * instead OMX will send empty this buffer directly and we need to clear an event here
     */
    if(waitForPortSettingsChanged)
    {
      waitForPortSettingsChanged = 0;
      if(displayYuv)
        overlay_set();
      event_complete();
    }

    pthread_mutex_lock(&fbd_lock);
    free_op_buf_cnt++;
    if(push(fbd_queue, (void *)pBuffer) < 0)
    {
      pthread_mutex_unlock(&fbd_lock);
      DEBUG_PRINT_ERROR("Error in enqueueing fbd_data\n");
      return OMX_ErrorUndefined;
    }
    pthread_mutex_unlock(&fbd_lock);
    sem_post(&fbd_sem);

    return OMX_ErrorNone;
}

int main(int argc, char **argv)
{
    int i=0;
    int bufCnt=0;
    int num=0;
    int outputOption = 0;
    int test_option = 0;
    int pic_order = 0;
    OMX_ERRORTYPE result;
    sliceheight = height = 144;
    stride = width = 176;

    if (argc < 2)
    {
      printf("To use it: ./mm-vdec-omx-test <clip location> \n");
      printf("Command line argument is also available\n");
      return -1;
    }

    strlcpy(in_filename, argv[1], strlen(argv[1])+1);
    if(argc > 2)
    {
      codec_format_option = (codec_format)atoi(argv[2]);
      // file_type, out_op, tst_op, nal_sz, disp_win, rt_dis, (fps), color, pic_order
      int param[9] = {2, 1, 1, 0, 0, 0, 0xFF, 0xFF, 0xFF};
      int next_arg = 3, idx = 0;
      while (argc > next_arg && idx < 9)
      {
        if (strlen(argv[next_arg]) > 2)
        {
          strlcpy(seq_file_name, argv[next_arg],strlen(argv[next_arg]) + 1);
          next_arg = argc;
        }
        else
          param[idx++] = atoi(argv[next_arg++]);
      }
      idx = 0;
      file_type_option = (file_type)param[idx++];
      if (codec_format_option == CODEC_FORMAT_H264 && file_type_option == 3)
      {
        nalSize = param[idx++];
        if (nalSize != 2 && nalSize != 4)
        {
          printf("Error - Can't pass NAL length size = %d\n", nalSize);
          return -1;
        }
      }
      outputOption = param[idx++];
      test_option = param[idx++];
      displayWindow = param[idx++];
      if (displayWindow > 0)
        printf("Only entire display window supported! Ignoring value\n");
      realtime_display = param[idx++];
      if (realtime_display)
      {
        takeYuvLog = 0;
        if(param[idx] != 0xFF)
        {
          fps = param[idx++];
          timestampInterval = 1e6 / fps;
        }
      }
      color_fmt_type = (param[idx] != 0xFF)? param[idx++] : color_fmt_type;
      pic_order = (param[idx] != 0xFF)? param[idx++] : 0;
      printf("Executing DynPortReconfig QCIF 144 x 176 \n");
    }
    else
    {
      printf("Command line argument is available\n");
      printf("To use it: ./mm-vdec-omx-test <clip location> <codec_type> \n");
      printf("           <input_type: 1. per AU(.dat), 2. arbitrary, 3.per NAL/frame>\n");
      printf("           <output_type> <test_case> <size_nal if H264>\n\n\n");
      printf(" *********************************************\n");
      printf(" ENTER THE TEST CASE YOU WOULD LIKE TO EXECUTE\n");
      printf(" *********************************************\n");
      printf(" 1--> H264\n");
      printf(" 2--> MP4\n");
      printf(" 3--> H263\n");
      printf(" 4--> VC1\n");
      printf(" 5--> DivX\n");
      printf(" 6--> MPEG2\n");
      fflush(stdin);
      fgets(tempbuf,sizeof(tempbuf),stdin);
      sscanf(tempbuf,"%d",&codec_format_option);
      fflush(stdin);
      if (codec_format_option > CODEC_FORMAT_MAX)
      {
          printf(" Wrong test case...[%d] \n", codec_format_option);
          return -1;
      }
      printf(" *********************************************\n");
      printf(" ENTER THE TEST CASE YOU WOULD LIKE TO EXECUTE\n");
      printf(" *********************************************\n");
      printf(" 1--> PER ACCESS UNIT CLIP (.dat). Clip only available for H264 and Mpeg4\n");
      printf(" 2--> ARBITRARY BYTES (need .264/.264c/.m4v/.263/.rcv/.vc1/.m2v)\n");
      if (codec_format_option == CODEC_FORMAT_H264)
      {
        printf(" 3--> NAL LENGTH SIZE CLIP (.264c)\n");
      }
      else if ( (codec_format_option == CODEC_FORMAT_MP4) || (codec_format_option == CODEC_FORMAT_H263) )
      {
        printf(" 3--> MP4 VOP or H263 P0 SHORT HEADER START CODE CLIP (.m4v or .263)\n");
      }
      else if (codec_format_option == CODEC_FORMAT_VC1)
      {
        printf(" 3--> VC1 clip Simple/Main Profile (.rcv)\n");
        printf(" 4--> VC1 clip Advance Profile (.vc1)\n");
      }
      else if (codec_format_option == CODEC_FORMAT_DIVX)
      {
          printf(" 3--> DivX 4, 5, 6 clip (.cmp)\n");
#ifdef MAX_RES_1080P
          printf(" 4--> DivX 3.11 clip \n");
#endif
      }
      else if (codec_format_option == CODEC_FORMAT_MPEG2)
      {
        printf(" 3--> MPEG2 START CODE CLIP (.m2v)\n");
      }

      fflush(stdin);
      fgets(tempbuf,sizeof(tempbuf),stdin);
      sscanf(tempbuf,"%d",&file_type_option);
      fflush(stdin);
      if (codec_format_option == CODEC_FORMAT_H264 && file_type_option == 3)
      {
        printf(" Enter Nal length size [2 or 4] \n");
        fgets(tempbuf,sizeof(tempbuf),stdin);
        sscanf(tempbuf,"%d",&nalSize);
        if (nalSize != 2 && nalSize != 4)
        {
          printf("Error - Can't pass NAL length size = %d\n", nalSize);
          return -1;
        }
      }

      printf(" *********************************************\n");
      printf(" Output buffer option:\n");
      printf(" *********************************************\n");
      printf(" 0 --> No display and no YUV log\n");
      printf(" 1 --> Diplay YUV\n");
      printf(" 2 --> Take YUV log\n");
      printf(" 3 --> Display YUV and take YUV log\n");
      fflush(stdin);
      fgets(tempbuf,sizeof(tempbuf),stdin);
      sscanf(tempbuf,"%d",&outputOption);
      fflush(stdin);

      printf(" *********************************************\n");
      printf(" ENTER THE TEST CASE YOU WOULD LIKE TO EXECUTE\n");
      printf(" *********************************************\n");
      printf(" 1 --> Play the clip till the end\n");
      printf(" 2 --> Run compliance test. Do NOT expect any display for most option. \n");
      printf("       Please only see \"TEST SUCCESSFULL\" to indicate test pass\n");
      fflush(stdin);
      fgets(tempbuf,sizeof(tempbuf),stdin);
      sscanf(tempbuf,"%d",&test_option);
      fflush(stdin);

      if (outputOption == 1 || outputOption == 3)
      {
          printf(" *********************************************\n");
          printf(" ENTER THE PORTION OF DISPLAY TO USE\n");
          printf(" *********************************************\n");
          printf(" 0 --> Entire Screen\n");
          printf(" 1 --> 1/4 th of the screen starting from top left corner to middle \n");
          printf(" 2 --> 1/4 th of the screen starting from middle to top right corner \n");
          printf(" 3 --> 1/4 th of the screen starting from middle to bottom left \n");
          printf(" 4 --> 1/4 th of the screen starting from middle to bottom right \n");
          printf("       Please only see \"TEST SUCCESSFULL\" to indidcate test pass\n");
          fflush(stdin);
          fgets(tempbuf,sizeof(tempbuf),stdin);
          sscanf(tempbuf,"%d",&displayWindow);
          fflush(stdin);
          if(displayWindow > 0)
          {
              printf(" Curently display window 0 only supported; ignoring other values\n");
              displayWindow = 0;
          }
      }

      if (outputOption == 1 || outputOption == 3)
      {
          printf(" *********************************************\n");
          printf(" DO YOU WANT TEST APP TO RENDER in Real time \n");
          printf(" 0 --> NO\n 1 --> YES\n");
          printf(" Warning: For H264, it require one NAL per frame clip.\n");
          printf("          For Arbitrary bytes option, Real time display is not recommended\n");
          printf(" *********************************************\n");
          fflush(stdin);
          fgets(tempbuf,sizeof(tempbuf),stdin);
          sscanf(tempbuf,"%d",&realtime_display);
          fflush(stdin);
      }


      if (realtime_display)
      {
          printf(" *********************************************\n");
          printf(" ENTER THE CLIP FPS\n");
          printf(" Exception: Timestamp extracted from clips will be used.\n");
          printf(" *********************************************\n");
          fflush(stdin);
          fgets(tempbuf,sizeof(tempbuf),stdin);
          sscanf(tempbuf,"%d",&fps);
          fflush(stdin);
          timestampInterval = 1000000/fps;
      }

      printf(" *********************************************\n");
      printf(" ENTER THE COLOR FORMAT \n");
      printf(" 0 --> Semiplanar \n 1 --> Tile Mode\n");
      printf(" *********************************************\n");
      fflush(stdin);
      fgets(tempbuf,sizeof(tempbuf),stdin);
      sscanf(tempbuf,"%d",&color_fmt_type);
      fflush(stdin);

      printf(" *********************************************\n");
      printf(" Output picture order option: \n");
      printf(" *********************************************\n");
      printf(" 0 --> Display order\n 1 --> Decode order\n");
      fflush(stdin);
      fgets(tempbuf,sizeof(tempbuf),stdin);
      sscanf(tempbuf,"%d",&pic_order);
      fflush(stdin);
    }
    if (file_type_option >= FILE_TYPE_COMMON_CODEC_MAX)
    {
      switch (codec_format_option)
      {
        case CODEC_FORMAT_H264:
          file_type_option = (file_type)(FILE_TYPE_START_OF_H264_SPECIFIC + file_type_option - FILE_TYPE_COMMON_CODEC_MAX);
          break;
        case CODEC_FORMAT_DIVX:
          file_type_option = (file_type)(FILE_TYPE_START_OF_DIVX_SPECIFIC + file_type_option - FILE_TYPE_COMMON_CODEC_MAX);
          break;
        case CODEC_FORMAT_MP4:
        case CODEC_FORMAT_H263:
          file_type_option = (file_type)(FILE_TYPE_START_OF_MP4_SPECIFIC + file_type_option - FILE_TYPE_COMMON_CODEC_MAX);
          break;
        case CODEC_FORMAT_VC1:
          file_type_option = (file_type)(FILE_TYPE_START_OF_VC1_SPECIFIC + file_type_option - FILE_TYPE_COMMON_CODEC_MAX);
          break;
        case CODEC_FORMAT_MPEG2:
          file_type_option = (file_type)(FILE_TYPE_START_OF_MPEG2_SPECIFIC + file_type_option - FILE_TYPE_COMMON_CODEC_MAX);
          break;
        default:
          printf("Error: Unknown code %d\n", codec_format_option);
      }
    }

    CONFIG_VERSION_SIZE(picture_order);
    picture_order.eOutputPictureOrder = QOMX_VIDEO_DISPLAY_ORDER;
    if (pic_order == 1)
      picture_order.eOutputPictureOrder = QOMX_VIDEO_DECODE_ORDER;

    if (outputOption == 0)
    {
      displayYuv = 0;
      takeYuvLog = 0;
      realtime_display = 0;
    }
    else if (outputOption == 1)
    {
      displayYuv = 1;
    }
    else if (outputOption == 2)
    {
      takeYuvLog = 1;
      realtime_display = 0;
    }
    else if (outputOption == 3)
    {
      displayYuv = 1;
      takeYuvLog = !realtime_display;
    }
    else
    {
      printf("Wrong option. Assume you want to see the YUV display\n");
      displayYuv = 1;
    }

    if (test_option == 2)
    {
      printf(" *********************************************\n");
      printf(" ENTER THE COMPLIANCE TEST YOU WOULD LIKE TO EXECUTE\n");
      printf(" *********************************************\n");
      printf(" 1 --> Call Free Handle at the OMX_StateLoaded\n");
      printf(" 2 --> Call Free Handle at the OMX_StateIdle\n");
      printf(" 3 --> Call Free Handle at the OMX_StateExecuting\n");
      printf(" 4 --> Call Free Handle at the OMX_StatePause\n");
      fflush(stdin);
      fgets(tempbuf,sizeof(tempbuf),stdin);
      sscanf(tempbuf,"%d",&freeHandle_option);
      fflush(stdin);
    }
    else
    {
      freeHandle_option = (freeHandle_test)0;
    }

    printf("Input values: inputfilename[%s]\n", in_filename);
    printf("*******************************************************\n");
    pthread_cond_init(&cond, 0);
    pthread_cond_init(&eos_cond, 0);
    pthread_mutex_init(&eos_lock, 0);
    pthread_mutex_init(&lock, 0);
    pthread_mutex_init(&etb_lock, 0);
    pthread_mutex_init(&fbd_lock, 0);
    pthread_mutex_init(&enable_lock, 0);
    if (-1 == sem_init(&etb_sem, 0, 0))
    {
      printf("Error - sem_init failed %d\n", errno);
    }
    if (-1 == sem_init(&fbd_sem, 0, 0))
    {
      printf("Error - sem_init failed %d\n", errno);
    }
    if (-1 == sem_init(&seq_sem, 0, 0))
    {
      printf("Error - sem_init failed %d\n", errno);
    }
    if (-1 == sem_init(&in_flush_sem, 0, 0))
    {
      printf("Error - sem_init failed %d\n", errno);
    }
    if (-1 == sem_init(&out_flush_sem, 0, 0))
    {
      printf("Error - sem_init failed %d\n", errno);
    }
    etb_queue = alloc_queue();
    if (etb_queue == NULL)
    {
      printf("\n Error in Creating etb_queue\n");
      return -1;
    }

    fbd_queue = alloc_queue();
    if (fbd_queue == NULL)
    {
      printf("\n Error in Creating fbd_queue\n");
      free_queue(etb_queue);
      return -1;
    }

    if(0 != pthread_create(&fbd_thread_id, NULL, fbd_thread, NULL))
    {
      printf("\n Error in Creating fbd_thread \n");
      free_queue(etb_queue);
      free_queue(fbd_queue);
      return -1;
    }

    if (displayYuv)
    {
      if (open_display() != 0)
      {
        printf("\n Error opening display! Video won't be displayed...");
        displayYuv = 0;
      }
    }

    run_tests();
    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&lock);
    pthread_mutex_destroy(&etb_lock);
    pthread_mutex_destroy(&fbd_lock);
    pthread_mutex_destroy(&enable_lock);
    pthread_cond_destroy(&eos_cond);
    pthread_mutex_destroy(&eos_lock);
    if (-1 == sem_destroy(&etb_sem))
    {
      DEBUG_PRINT_ERROR("Error - sem_destroy failed %d\n", errno);
    }
    if (-1 == sem_destroy(&fbd_sem))
    {
      DEBUG_PRINT_ERROR("Error - sem_destroy failed %d\n", errno);
    }
    if (-1 == sem_destroy(&seq_sem))
    {
      DEBUG_PRINT_ERROR("Error - sem_destroy failed %d\n", errno);
    }
    if (-1 == sem_destroy(&in_flush_sem))
    {
      DEBUG_PRINT_ERROR("Error - sem_destroy failed %d\n", errno);
    }
    if (-1 == sem_destroy(&out_flush_sem))
    {
      DEBUG_PRINT_ERROR("Error - sem_destroy failed %d\n", errno);
    }
    if (displayYuv)
      close_display();
    return 0;
}

int run_tests()
{
  int cmd_error = 0;
  DEBUG_PRINT("Inside %s\n", __FUNCTION__);
  waitForPortSettingsChanged = 1;

  if(file_type_option == FILE_TYPE_DAT_PER_AU) {
    Read_Buffer = Read_Buffer_From_DAT_File;
  }
  else if(file_type_option == FILE_TYPE_ARBITRARY_BYTES) {
    Read_Buffer = Read_Buffer_ArbitraryBytes;
  }
  else if(codec_format_option == CODEC_FORMAT_H264) {
    Read_Buffer = Read_Buffer_From_Size_Nal;
  }
  else if((codec_format_option == CODEC_FORMAT_H263) ||
          (codec_format_option == CODEC_FORMAT_MP4)) {
    Read_Buffer = Read_Buffer_From_Vop_Start_Code_File;
  }
  else if (codec_format_option == CODEC_FORMAT_MPEG2) {
    Read_Buffer = Read_Buffer_From_Mpeg2_Start_Code;
  }
  else if(file_type_option == FILE_TYPE_DIVX_4_5_6) {
    Read_Buffer = Read_Buffer_From_DivX_4_5_6_File;
  }
#ifdef MAX_RES_1080P
  else if(file_type_option == FILE_TYPE_DIVX_311) {
    Read_Buffer = Read_Buffer_From_DivX_311_File;
  }
#endif
  else if(file_type_option == FILE_TYPE_RCV) {
    Read_Buffer = Read_Buffer_From_RCV_File;
  }
  else if(file_type_option == FILE_TYPE_VC1) {
    Read_Buffer = Read_Buffer_From_VC1_File;
  }

  DEBUG_PRINT("file_type_option %d!\n", file_type_option);

  switch(file_type_option)
  {
    case FILE_TYPE_DAT_PER_AU:
    case FILE_TYPE_ARBITRARY_BYTES:
    case FILE_TYPE_264_NAL_SIZE_LENGTH:
    case FILE_TYPE_PICTURE_START_CODE:
    case FILE_TYPE_MPEG2_START_CODE:
    case FILE_TYPE_RCV:
    case FILE_TYPE_VC1:
    case FILE_TYPE_DIVX_4_5_6:
#ifdef MAX_RES_1080P
      case FILE_TYPE_DIVX_311:
#endif
      if(Init_Decoder()!= 0x00)
      {
        DEBUG_PRINT_ERROR("Error - Decoder Init failed\n");
        return -1;
      }
      if(Play_Decoder() != 0x00)
      {
        return -1;
      }
      break;
    default:
      DEBUG_PRINT_ERROR("Error - Invalid Entry...%d\n",file_type_option);
      break;
  }

  anti_flickering = true;
  if(strlen(seq_file_name))
  {
        seqFile = fopen (seq_file_name, "rb");
        if (seqFile == NULL)
        {
            DEBUG_PRINT_ERROR("Error - Seq file %s could NOT be opened\n",
                              seq_file_name);
            return -1;
        }
        else
        {
            DEBUG_PRINT("Seq file %s is opened \n", seq_file_name);
            seq_enabled = 1;
            anti_flickering = false;
        }
  }

  pthread_mutex_lock(&eos_lock);
  while (bOutputEosReached == false && cmd_error == 0)
  {
    if(seq_enabled)
    {
        pthread_mutex_unlock(&eos_lock);
        if(!get_next_command(seqFile))
            cmd_error = process_current_command(curr_seq_command);
        else
        {
            printf("\n Error in get_next_cmd or EOF");
            seq_enabled = 0;
        }
        pthread_mutex_lock(&eos_lock);
    }
    else
        pthread_cond_wait(&eos_cond, &eos_lock);

    if (currentStatus == PORT_SETTING_CHANGE_STATE)
    {
      pthread_mutex_unlock(&eos_lock);
      cmd_error = output_port_reconfig();
      pthread_mutex_lock(&eos_lock);
    }
  }
  pthread_mutex_unlock(&eos_lock);

  // Wait till EOS is reached...
  if(bOutputEosReached)
    do_freeHandle_and_clean_up(currentStatus == ERROR_STATE);
  return 0;
}

int Init_Decoder()
{
    DEBUG_PRINT("Inside %s \n", __FUNCTION__);
    OMX_ERRORTYPE omxresult;
    OMX_U32 total = 0;
    char vdecCompNames[50];
    typedef OMX_U8* OMX_U8_PTR;
    char *role ="video_decoder";

    static OMX_CALLBACKTYPE call_back = {&EventHandler, &EmptyBufferDone, &FillBufferDone};

    int i = 0;
    long bufCnt = 0;

    /* Init. the OpenMAX Core */
    DEBUG_PRINT("\nInitializing OpenMAX Core....\n");
    omxresult = OMX_Init();

    if(OMX_ErrorNone != omxresult) {
        DEBUG_PRINT_ERROR("\n Failed to Init OpenMAX core");
        return -1;
    }
    else {
        DEBUG_PRINT_ERROR("\nOpenMAX Core Init Done\n");
    }

    /* Query for video decoders*/
    OMX_GetComponentsOfRole(role, &total, 0);
    DEBUG_PRINT("\nTotal components of role=%s :%d", role, total);

    if(total)
    {
        /* Allocate memory for pointers to component name */
        OMX_U8** vidCompNames = (OMX_U8**)malloc((sizeof(OMX_U8*))*total);
        if (vidCompNames == NULL) {
            DEBUG_PRINT_ERROR("\nFailed to allocate vidCompNames\n");
            return -1;
        }

        for (i = 0; i < total; ++i) {
            vidCompNames[i] = (OMX_U8*)malloc(sizeof(OMX_U8)*OMX_MAX_STRINGNAME_SIZE);
            if (vidCompNames[i] == NULL) {
                DEBUG_PRINT_ERROR("\nFailed to allocate vidCompNames[%d]\n", i);
                return -1;
            }
        }
        OMX_GetComponentsOfRole(role, &total, vidCompNames);
        DEBUG_PRINT("\nComponents of Role:%s\n", role);
        for (i = 0; i < total; ++i) {
            DEBUG_PRINT("\nComponent Name [%s]\n",vidCompNames[i]);
            free(vidCompNames[i]);
        }
        free(vidCompNames);
    }
    else {
        DEBUG_PRINT_ERROR("No components found with Role:%s", role);
    }

    if (codec_format_option == CODEC_FORMAT_H264)
    {
      strlcpy(vdecCompNames, "OMX.qcom.video.decoder.avc", 27);
      //strlcpy(vdecCompNames, "OMX.SEC.qcom.video.decoder.avc", 31);
    }
    else if (codec_format_option == CODEC_FORMAT_MP4)
    {
      strlcpy(vdecCompNames, "OMX.qcom.video.decoder.mpeg4", 29);
    }
    else if (codec_format_option == CODEC_FORMAT_H263)
    {
      strlcpy(vdecCompNames, "OMX.qcom.video.decoder.h263", 28);
    }
    else if (codec_format_option == CODEC_FORMAT_VC1)
    {
      strlcpy(vdecCompNames, "OMX.qcom.video.decoder.vc1", 27);
    }
    else if (codec_format_option == CODEC_FORMAT_MPEG2)
    {
      strlcpy(vdecCompNames, "OMX.qcom.video.decoder.mpeg2", 29);
    }
    else if (file_type_option == FILE_TYPE_RCV)
    {
      strlcpy(vdecCompNames, "OMX.qcom.video.decoder.wmv", 27);
    }
    else if (file_type_option == FILE_TYPE_DIVX_4_5_6)
    {
      strlcpy(vdecCompNames, "OMX.qcom.video.decoder.divx", 28);
    }
#ifdef MAX_RES_1080P
    else if (file_type_option == FILE_TYPE_DIVX_311)
    {
      strlcpy(vdecCompNames, "OMX.qcom.video.decoder.divx311", 31);
    }
#endif
    else
    {
      DEBUG_PRINT_ERROR("Error: Unsupported codec %d\n", codec_format_option);
      return -1;
    }

    omxresult = OMX_GetHandle((OMX_HANDLETYPE*)(&dec_handle),
                              (OMX_STRING)vdecCompNames, NULL, &call_back);
    if (FAILED(omxresult)) {
        DEBUG_PRINT_ERROR("\nFailed to Load the component:%s\n", vdecCompNames);
        return -1;
    }
    else
    {
        DEBUG_PRINT("\nComponent %s is in LOADED state\n", vdecCompNames);
    }

    QOMX_VIDEO_QUERY_DECODER_INSTANCES decoder_instances;
    omxresult = OMX_GetConfig(dec_handle,
                 (OMX_INDEXTYPE)OMX_QcomIndexQueryNumberOfVideoDecInstance,
                              &decoder_instances);
    DEBUG_PRINT("\n Number of decoder instances %d",
                      decoder_instances.nNumOfInstances);

    /* Get the port information */
    CONFIG_VERSION_SIZE(portParam);
    omxresult = OMX_GetParameter(dec_handle, OMX_IndexParamVideoInit,
                                (OMX_PTR)&portParam);

    if(FAILED(omxresult)) {
        DEBUG_PRINT_ERROR("ERROR - Failed to get Port Param\n");
        return -1;
    }
    else
    {
        DEBUG_PRINT("portParam.nPorts:%d\n", portParam.nPorts);
        DEBUG_PRINT("portParam.nStartPortNumber:%d\n", portParam.nStartPortNumber);
    }

    /* Set the compression format on i/p port */
    if (codec_format_option == CODEC_FORMAT_H264)
    {
      portFmt.format.video.eCompressionFormat = OMX_VIDEO_CodingAVC;
    }
    else if (codec_format_option == CODEC_FORMAT_MP4)
    {
      portFmt.format.video.eCompressionFormat = OMX_VIDEO_CodingMPEG4;
    }
    else if (codec_format_option == CODEC_FORMAT_H263)
    {
      portFmt.format.video.eCompressionFormat = OMX_VIDEO_CodingH263;
    }
    else if (codec_format_option == CODEC_FORMAT_VC1)
    {
      portFmt.format.video.eCompressionFormat = OMX_VIDEO_CodingWMV;
    }
    else if (codec_format_option == CODEC_FORMAT_DIVX)
    {
      portFmt.format.video.eCompressionFormat =
          (OMX_VIDEO_CODINGTYPE)QOMX_VIDEO_CodingDivx;
    }
    else if (codec_format_option == CODEC_FORMAT_MPEG2)
    {
      portFmt.format.video.eCompressionFormat = OMX_VIDEO_CodingMPEG2;
    }
    else
    {
      DEBUG_PRINT_ERROR("Error: Unsupported codec %d\n", codec_format_option);
    }


    return 0;
}

int Play_Decoder()
{
    OMX_VIDEO_PARAM_PORTFORMATTYPE videoportFmt = {0};
    int i, bufCnt, index = 0;
    int frameSize=0;
    OMX_ERRORTYPE ret = OMX_ErrorNone;
    OMX_BUFFERHEADERTYPE* pBuffer = NULL;
    DEBUG_PRINT("Inside %s \n", __FUNCTION__);

    /* open the i/p and o/p files based on the video file format passed */
    if(open_video_file()) {
        DEBUG_PRINT_ERROR("Error in opening video file\n");
        return -1;
    }

    OMX_QCOM_PARAM_PORTDEFINITIONTYPE inputPortFmt;
    memset(&inputPortFmt, 0, sizeof(OMX_QCOM_PARAM_PORTDEFINITIONTYPE));
    CONFIG_VERSION_SIZE(inputPortFmt);
    inputPortFmt.nPortIndex = 0;  // input port
    switch (file_type_option)
    {
      case FILE_TYPE_DAT_PER_AU:
      case FILE_TYPE_PICTURE_START_CODE:
      case FILE_TYPE_MPEG2_START_CODE:
      case FILE_TYPE_RCV:
      case FILE_TYPE_VC1:
#ifdef MAX_RES_1080P
      case FILE_TYPE_DIVX_311:
#endif
      {
        inputPortFmt.nFramePackingFormat = OMX_QCOM_FramePacking_OnlyOneCompleteFrame;
        break;
      }

      case FILE_TYPE_ARBITRARY_BYTES:
      case FILE_TYPE_264_NAL_SIZE_LENGTH:
      case FILE_TYPE_DIVX_4_5_6:
      {
        inputPortFmt.nFramePackingFormat = OMX_QCOM_FramePacking_Arbitrary;
        break;
      }

      default:
        inputPortFmt.nFramePackingFormat = OMX_QCOM_FramePacking_Unspecified;
    }
    OMX_SetParameter(dec_handle,(OMX_INDEXTYPE)OMX_QcomIndexPortDefn,
                     (OMX_PTR)&inputPortFmt);
#ifdef USE_EXTERN_PMEM_BUF
    OMX_QCOM_PARAM_PORTDEFINITIONTYPE outPortFmt;
    memset(&outPortFmt, 0, sizeof(OMX_QCOM_PARAM_PORTDEFINITIONTYPE));
    CONFIG_VERSION_SIZE(outPortFmt);
    outPortFmt.nPortIndex = 1;  // output port
    outPortFmt.nCacheAttr = OMX_QCOM_CacheAttrNone;
    outPortFmt.nMemRegion = OMX_QCOM_MemRegionSMI;
    OMX_SetParameter(dec_handle,(OMX_INDEXTYPE)OMX_QcomIndexPortDefn,
                     (OMX_PTR)&outPortFmt);

    OMX_QCOM_PLATFORMPRIVATE_EXTN outPltPvtExtn;
    memset(&outPltPvtExtn, 0, sizeof(OMX_QCOM_PLATFORMPRIVATE_EXTN));
    CONFIG_VERSION_SIZE(outPltPvtExtn);
    outPltPvtExtn.nPortIndex = 1;  // output port
    outPltPvtExtn.type = OMX_QCOM_PLATFORM_PRIVATE_PMEM;
    OMX_SetParameter(dec_handle,(OMX_INDEXTYPE)OMX_QcomIndexPlatformPvt,
                     (OMX_PTR)&outPltPvtExtn);
    use_external_pmem_buf = OMX_TRUE;
#endif
    QOMX_ENABLETYPE extra_data;
    extra_data.bEnable = OMX_TRUE;
#if 0
    OMX_SetParameter(dec_handle,(OMX_INDEXTYPE)OMX_QcomIndexParamInterlaceExtraData,
                     (OMX_PTR)&extra_data);
#endif
#if 0
    OMX_SetParameter(dec_handle,(OMX_INDEXTYPE)OMX_QcomIndexParamConcealMBMapExtraData,
                     (OMX_PTR)&extra_data);
#endif
#if 1
    OMX_SetParameter(dec_handle,(OMX_INDEXTYPE)OMX_QcomIndexParamFrameInfoExtraData,
                     (OMX_PTR)&extra_data);
#endif
#ifdef TEST_TS_FROM_SEI
    OMX_SetParameter(dec_handle,(OMX_INDEXTYPE)OMX_QcomIndexParamH264TimeInfo,
                     (OMX_PTR)&extra_data);
#endif
#if 0
    extra_data.bEnable = OMX_FALSE;
    OMX_SetParameter(dec_handle,(OMX_INDEXTYPE)OMX_QcomIndexParamConcealMBMapExtraData,
                     (OMX_PTR)&extra_data);
#endif
    /* Query the decoder outport's min buf requirements */
    CONFIG_VERSION_SIZE(portFmt);

    /* Port for which the Client needs to obtain info */
    portFmt.nPortIndex = portParam.nStartPortNumber;

    OMX_GetParameter(dec_handle,OMX_IndexParamPortDefinition,&portFmt);
    DEBUG_PRINT("\nDec: Min Buffer Count %d\n", portFmt.nBufferCountMin);
    DEBUG_PRINT("\nDec: Buffer Size %d\n", portFmt.nBufferSize);

    if(OMX_DirInput != portFmt.eDir) {
        printf ("\nDec: Expect Input Port\n");
        return -1;
    }
#ifdef MAX_RES_1080P
    if( (codec_format_option == CODEC_FORMAT_DIVX) &&
        (file_type_option == FILE_TYPE_DIVX_311) ) {

            int off;

            if ( read(inputBufferFileFd, &width, 4 ) == -1 ) {
                DEBUG_PRINT_ERROR("\nFailed to read width for divx\n");
                return  -1;
            }

            DEBUG_PRINT("\nWidth for DIVX = %d\n", width);

            if ( read(inputBufferFileFd, &height, 4 ) == -1 ) {
                DEBUG_PRINT_ERROR("\nFailed to read height for divx\n");
                return  -1;
            }

            DEBUG_PRINT("\nHeight for DIVX = %u\n", height);
            sliceheight = height;
            stride = width;
    }
#endif

    bufCnt = 0;
    portFmt.format.video.nFrameHeight = height;
    portFmt.format.video.nFrameWidth  = width;
    portFmt.format.video.xFramerate = fps;
    OMX_SetParameter(dec_handle,OMX_IndexParamPortDefinition, (OMX_PTR)&portFmt);
    OMX_GetParameter(dec_handle,OMX_IndexParamPortDefinition, &portFmt);
    DEBUG_PRINT("\nDec: New Min Buffer Count %d", portFmt.nBufferCountMin);
    CONFIG_VERSION_SIZE(videoportFmt);
#ifdef MAX_RES_720P
    if(color_fmt_type == 0)
    {
        color_fmt = OMX_COLOR_FormatYUV420SemiPlanar;
    }
    else
    {
        color_fmt = (OMX_COLOR_FORMATTYPE)
           QOMX_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka;
    }
#elif _COPPER_
        color_fmt = OMX_COLOR_FormatYUV420SemiPlanar;
#else
       color_fmt = (OMX_COLOR_FORMATTYPE)
           QOMX_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka;
#endif

    while (ret == OMX_ErrorNone)
    {
        videoportFmt.nPortIndex = 1;
        videoportFmt.nIndex = index;
        ret = OMX_GetParameter(dec_handle, OMX_IndexParamVideoPortFormat,
          (OMX_PTR)&videoportFmt);

        if((ret == OMX_ErrorNone) && (videoportFmt.eColorFormat ==
           color_fmt))
        {
            DEBUG_PRINT("\n Format[%u] supported by OMX Decoder", color_fmt);
            break;
        }
        index++;
    }

    if(ret == OMX_ErrorNone)
    {
        if(OMX_SetParameter(dec_handle, OMX_IndexParamVideoPortFormat,
            (OMX_PTR)&videoportFmt) != OMX_ErrorNone)
        {
            DEBUG_PRINT_ERROR("\n Setting Tile format failed");
            return -1;
        }
    }
    else
    {
        DEBUG_PRINT_ERROR("\n Error in retrieving supported color formats");
        return -1;
    }
    picture_order.nPortIndex = 1;
    DEBUG_PRINT("\nSet picture order\n");
    if(OMX_SetParameter(dec_handle,
	   (OMX_INDEXTYPE)OMX_QcomIndexParamVideoDecoderPictureOrder,
       (OMX_PTR)&picture_order) != OMX_ErrorNone)
    {
        printf("\n ERROR: Setting picture order!");
        return -1;
    }
    DEBUG_PRINT("\nVideo format: W x H (%d x %d)",
      portFmt.format.video.nFrameWidth,
      portFmt.format.video.nFrameHeight);
    if(codec_format_option == CODEC_FORMAT_H264)
    {
        OMX_VIDEO_CONFIG_NALSIZE naluSize;
        naluSize.nNaluBytes = nalSize;
        DEBUG_PRINT("\n Nal length is %d index %d",nalSize,OMX_IndexConfigVideoNalSize);
        OMX_SetConfig(dec_handle,OMX_IndexConfigVideoNalSize,(OMX_PTR)&naluSize);
        DEBUG_PRINT("SETTING THE NAL SIZE to %d\n",naluSize.nNaluBytes);
    }
    DEBUG_PRINT("\nOMX_SendCommand Decoder -> IDLE\n");
    OMX_SendCommand(dec_handle, OMX_CommandStateSet, OMX_StateIdle,0);

    input_buf_cnt = portFmt.nBufferCountActual;
    DEBUG_PRINT("Transition to Idle State succesful...\n");

#if ALLOCATE_BUFFER
       // Allocate buffer on decoder's i/p port
       error = Allocate_Buffer(dec_handle, &pInputBufHdrs, portFmt.nPortIndex,
                               portFmt.nBufferCountActual, portFmt.nBufferSize);
       if (error != OMX_ErrorNone) {
           DEBUG_PRINT_ERROR("Error - OMX_AllocateBuffer Input buffer error\n");
           return -1;
       }
       else {
           DEBUG_PRINT("\nOMX_AllocateBuffer Input buffer success\n");
       }
#else
       // Use buffer on decoder's i/p port
          input_use_buffer = true;
          DEBUG_PRINT_ERROR("\n before OMX_UseBuffer %p", &pInputBufHdrs);
          error =  use_input_buffer(dec_handle,
                             &pInputBufHdrs,
                              portFmt.nPortIndex,
                              portFmt.nBufferSize,
                              portFmt.nBufferCountActual);
          if (error != OMX_ErrorNone) {
             DEBUG_PRINT_ERROR("ERROR - OMX_UseBuffer Input buffer failed");
             return -1;
          }
          else {
             DEBUG_PRINT("OMX_UseBuffer Input buffer success\n");
          }
#endif
       portFmt.nPortIndex = portParam.nStartPortNumber+1;
       // Port for which the Client needs to obtain info

    OMX_GetParameter(dec_handle,OMX_IndexParamPortDefinition,&portFmt);
    DEBUG_PRINT("nMin Buffer Count=%d", portFmt.nBufferCountMin);
    DEBUG_PRINT("nBuffer Size=%d", portFmt.nBufferSize);
    if(OMX_DirOutput != portFmt.eDir) {
        DEBUG_PRINT_ERROR("Error - Expect Output Port\n");
        return -1;
    }

#ifndef USE_EGL_IMAGE_TEST_APP
    if (use_external_pmem_buf)
    {
        DEBUG_PRINT_ERROR("\n Use External pmem buf: OMX_UseBuffer %p", &pInputBufHdrs);
        error =  use_output_buffer_multiple_fd(dec_handle,
                                               &pOutYUVBufHdrs,
                                               portFmt.nPortIndex,
                                               portFmt.nBufferSize,
                                               portFmt.nBufferCountActual);
    }
    else
    {
        /* Allocate buffer on decoder's o/p port */
        error = Allocate_Buffer(dec_handle, &pOutYUVBufHdrs, portFmt.nPortIndex,
                                portFmt.nBufferCountActual, portFmt.nBufferSize);
    }
    free_op_buf_cnt = portFmt.nBufferCountActual;
    if (error != OMX_ErrorNone) {
        DEBUG_PRINT_ERROR("Error - OMX_AllocateBuffer Output buffer error\n");
        return -1;
    }
    else
    {
        DEBUG_PRINT("OMX_AllocateBuffer Output buffer success\n");
    }
#else
    DEBUG_PRINT_ERROR("\n before OMX_UseBuffer %p", &pInputBufHdrs);
    error =  use_output_buffer(dec_handle,
                       &pOutYUVBufHdrs,
                        portFmt.nPortIndex,
                        portFmt.nBufferSize,
                        portFmt.nBufferCountActual);
    free_op_buf_cnt = portFmt.nBufferCountActual;
    if (error != OMX_ErrorNone) {
       DEBUG_PRINT_ERROR("ERROR - OMX_UseBuffer Input buffer failed");
       return -1;
    }
    else {
       DEBUG_PRINT("OMX_UseBuffer Input buffer success\n");
    }
#endif
    wait_for_event();
    if (currentStatus == ERROR_STATE)
    {
      do_freeHandle_and_clean_up(true);
      return -1;
    }

    if (freeHandle_option == FREE_HANDLE_AT_IDLE)
    {
      OMX_STATETYPE state = OMX_StateInvalid;
      OMX_GetState(dec_handle, &state);
      if (state == OMX_StateIdle)
      {
        DEBUG_PRINT("Decoder is in OMX_StateIdle and trying to call OMX_FreeHandle \n");
        do_freeHandle_and_clean_up(false);
      }
      else
      {
        DEBUG_PRINT_ERROR("Error - Decoder is in state %d and trying to call OMX_FreeHandle \n", state);
        do_freeHandle_and_clean_up(true);
      }
      return -1;
    }


    DEBUG_PRINT("OMX_SendCommand Decoder -> Executing\n");
    OMX_SendCommand(dec_handle, OMX_CommandStateSet, OMX_StateExecuting,0);
    wait_for_event();
    if (currentStatus == ERROR_STATE)
    {
      do_freeHandle_and_clean_up(true);
      return -1;
    }
    if (pOutYUVBufHdrs == NULL)
    {
        DEBUG_PRINT_ERROR("Error - pOutYUVBufHdrs is NULL\n");
        return -1;
    }
    for(bufCnt=0; bufCnt < portFmt.nBufferCountActual; ++bufCnt) {
        DEBUG_PRINT("OMX_FillThisBuffer on output buf no.%d\n",bufCnt);
        if (pOutYUVBufHdrs[bufCnt] == NULL)
        {
            DEBUG_PRINT_ERROR("Error - pOutYUVBufHdrs[%d] is NULL\n", bufCnt);
            return -1;
        }
        pOutYUVBufHdrs[bufCnt]->nOutputPortIndex = 1;
        pOutYUVBufHdrs[bufCnt]->nFlags &= ~OMX_BUFFERFLAG_EOS;
        ret = OMX_FillThisBuffer(dec_handle, pOutYUVBufHdrs[bufCnt]);
        if (OMX_ErrorNone != ret)
            DEBUG_PRINT_ERROR("Error - OMX_FillThisBuffer failed with result %d\n", ret);
        else
        {
            DEBUG_PRINT("OMX_FillThisBuffer success!\n");
            free_op_buf_cnt--;
        }
    }

    used_ip_buf_cnt = input_buf_cnt;

    rcv_v1 = 0;

    //QPERF_START(client_decode);
    if (codec_format_option == CODEC_FORMAT_VC1)
    {
      pInputBufHdrs[0]->nOffset = 0;
      if(file_type_option == FILE_TYPE_RCV)
      {
      frameSize = Read_Buffer_From_RCV_File_Seq_Layer(pInputBufHdrs[0]);
      pInputBufHdrs[0]->nFilledLen = frameSize;
          DEBUG_PRINT("After Read_Buffer_From_RCV_File_Seq_Layer, "
              "frameSize %d\n", frameSize);
      }
      else if(file_type_option == FILE_TYPE_VC1)
      {
          bHdrflag = 1;
          pInputBufHdrs[0]->nFilledLen = Read_Buffer(pInputBufHdrs[0]);
          bHdrflag = 0;
          DEBUG_PRINT_ERROR("After 1st Read_Buffer for VC1, "
              "pInputBufHdrs[0]->nFilledLen %d\n", pInputBufHdrs[0]->nFilledLen);
      }
      else
      {
          pInputBufHdrs[0]->nFilledLen = Read_Buffer(pInputBufHdrs[0]);
          DEBUG_PRINT("After Read_Buffer pInputBufHdrs[0]->nFilledLen %d\n",
              pInputBufHdrs[0]->nFilledLen);
      }

      pInputBufHdrs[0]->nInputPortIndex = 0;
      pInputBufHdrs[0]->nOffset = 0;
      pInputBufHdrs[0]->nFlags = 0;

      ret = OMX_EmptyThisBuffer(dec_handle, pInputBufHdrs[0]);
      if (ret != OMX_ErrorNone)
      {
          DEBUG_PRINT_ERROR("ERROR - OMX_EmptyThisBuffer failed with result %d\n", ret);
          do_freeHandle_and_clean_up(true);
          return -1;
      }
      else
      {
          etb_count++;
          DEBUG_PRINT("OMX_EmptyThisBuffer success!\n");
      }
      i = 1;
    }
    else
    {
      i = 0;
    }

    for (i; i < used_ip_buf_cnt;i++) {
      pInputBufHdrs[i]->nInputPortIndex = 0;
      pInputBufHdrs[i]->nOffset = 0;
      if((frameSize = Read_Buffer(pInputBufHdrs[i])) <= 0 ){
        DEBUG_PRINT("NO FRAME READ\n");
        pInputBufHdrs[i]->nFilledLen = frameSize;
        pInputBufHdrs[i]->nInputPortIndex = 0;
        pInputBufHdrs[i]->nFlags |= OMX_BUFFERFLAG_EOS;;
        bInputEosReached = true;

        OMX_EmptyThisBuffer(dec_handle, pInputBufHdrs[i]);
        etb_count++;
        DEBUG_PRINT("File is small::Either EOS or Some Error while reading file\n");
        break;
      }
      pInputBufHdrs[i]->nFilledLen = frameSize;
      pInputBufHdrs[i]->nInputPortIndex = 0;
      pInputBufHdrs[i]->nFlags = 0;
//pBufHdr[bufCnt]->pAppPrivate = this;
      DEBUG_PRINT("%s: Timestamp sent(%lld)", __FUNCTION__, pInputBufHdrs[i]->nTimeStamp);
      ret = OMX_EmptyThisBuffer(dec_handle, pInputBufHdrs[i]);
      if (OMX_ErrorNone != ret) {
          DEBUG_PRINT_ERROR("ERROR - OMX_EmptyThisBuffer failed with result %d\n", ret);
          do_freeHandle_and_clean_up(true);
          return -1;
      }
      else {
          DEBUG_PRINT("OMX_EmptyThisBuffer success!\n");
          etb_count++;
      }
    }

    if(0 != pthread_create(&ebd_thread_id, NULL, ebd_thread, NULL))
    {
      printf("\n Error in Creating fbd_thread \n");
      free_queue(etb_queue);
      free_queue(fbd_queue);
      return -1;
    }

    // wait for event port settings changed event
    DEBUG_PRINT("wait_for_event: dyn reconfig");
    wait_for_event();
    DEBUG_PRINT("wait_for_event: dyn reconfig rcvd, currentStatus %d\n",
                  currentStatus);
    if (currentStatus == ERROR_STATE)
    {
      printf("Error - ERROR_STATE\n");
      do_freeHandle_and_clean_up(true);
      return -1;
    }
    else if (currentStatus == PORT_SETTING_CHANGE_STATE)
    {
      if (output_port_reconfig() != 0)
        return -1;
    }

    if (freeHandle_option == FREE_HANDLE_AT_EXECUTING)
    {
      OMX_STATETYPE state = OMX_StateInvalid;
      OMX_GetState(dec_handle, &state);
      if (state == OMX_StateExecuting)
      {
        DEBUG_PRINT("Decoder is in OMX_StateExecuting and trying to call OMX_FreeHandle \n");
        do_freeHandle_and_clean_up(false);
      }
      else
      {
        DEBUG_PRINT_ERROR("Error - Decoder is in state %d and trying to call OMX_FreeHandle \n", state);
        do_freeHandle_and_clean_up(true);
      }
      return -1;
    }
    else if (freeHandle_option == FREE_HANDLE_AT_PAUSE)
    {
      OMX_SendCommand(dec_handle, OMX_CommandStateSet, OMX_StatePause,0);
      wait_for_event();

      OMX_STATETYPE state = OMX_StateInvalid;
      OMX_GetState(dec_handle, &state);
      if (state == OMX_StatePause)
      {
        DEBUG_PRINT("Decoder is in OMX_StatePause and trying to call OMX_FreeHandle \n");
        do_freeHandle_and_clean_up(false);
      }
      else
      {
        DEBUG_PRINT_ERROR("Error - Decoder is in state %d and trying to call OMX_FreeHandle \n", state);
        do_freeHandle_and_clean_up(true);
      }
      return -1;
    }

    return 0;
}

static OMX_ERRORTYPE Allocate_Buffer ( OMX_COMPONENTTYPE *dec_handle,
                                       OMX_BUFFERHEADERTYPE  ***pBufHdrs,
                                       OMX_U32 nPortIndex,
                                       long bufCntMin, long bufSize)
{
    DEBUG_PRINT("Inside %s \n", __FUNCTION__);
    OMX_ERRORTYPE error=OMX_ErrorNone;
    long bufCnt=0;

    DEBUG_PRINT("pBufHdrs = %x,bufCntMin = %d\n", pBufHdrs, bufCntMin);
    *pBufHdrs= (OMX_BUFFERHEADERTYPE **)
                   malloc(sizeof(OMX_BUFFERHEADERTYPE)*bufCntMin);

    for(bufCnt=0; bufCnt < bufCntMin; ++bufCnt) {
        DEBUG_PRINT("OMX_AllocateBuffer No %d \n", bufCnt);
        error = OMX_AllocateBuffer(dec_handle, &((*pBufHdrs)[bufCnt]),
                                   nPortIndex, NULL, bufSize);
    }

    return error;
}

static OMX_ERRORTYPE use_input_buffer ( OMX_COMPONENTTYPE *dec_handle,
                                  OMX_BUFFERHEADERTYPE  ***pBufHdrs,
                                  OMX_U32 nPortIndex,
                                  OMX_U32 bufSize,
                                  long bufCntMin)
{
    DEBUG_PRINT("Inside %s \n", __FUNCTION__);
    OMX_ERRORTYPE error=OMX_ErrorNone;
    long bufCnt=0;
    OMX_U8* pvirt = NULL;

    *pBufHdrs= (OMX_BUFFERHEADERTYPE **)
                   malloc(sizeof(OMX_BUFFERHEADERTYPE)* bufCntMin);
    if(*pBufHdrs == NULL){
        DEBUG_PRINT_ERROR("\n m_inp_heap_ptr Allocation failed ");
        return OMX_ErrorInsufficientResources;
     }

    for(bufCnt=0; bufCnt < bufCntMin; ++bufCnt) {
        // allocate input buffers
      DEBUG_PRINT("OMX_UseBuffer No %d %d \n", bufCnt, bufSize);
      pvirt = (OMX_U8*) malloc (bufSize);
      if(pvirt == NULL){
        DEBUG_PRINT_ERROR("\n pvirt Allocation failed ");
        return OMX_ErrorInsufficientResources;
     }
      error = OMX_UseBuffer(dec_handle, &((*pBufHdrs)[bufCnt]),
                              nPortIndex, NULL, bufSize, pvirt);
       }
    return error;
}

static OMX_ERRORTYPE use_output_buffer ( OMX_COMPONENTTYPE *dec_handle,
                                  OMX_BUFFERHEADERTYPE  ***pBufHdrs,
                                  OMX_U32 nPortIndex,
                                  OMX_U32 bufSize,
                                  long bufCntMin)
{
    DEBUG_PRINT("Inside %s \n", __FUNCTION__);
    OMX_ERRORTYPE error=OMX_ErrorNone;
    long bufCnt=0;
    OMX_U8* pvirt = NULL;

    *pBufHdrs= (OMX_BUFFERHEADERTYPE **)
                   malloc(sizeof(OMX_BUFFERHEADERTYPE)* bufCntMin);
    if(*pBufHdrs == NULL){
        DEBUG_PRINT_ERROR("\n m_inp_heap_ptr Allocation failed ");
        return OMX_ErrorInsufficientResources;
     }
    output_use_buffer = true;
    p_eglHeaders = (struct temp_egl **)
                    malloc(sizeof(struct temp_egl *)* bufCntMin);
    if (!p_eglHeaders){
        DEBUG_PRINT_ERROR("\n EGL allocation failed");
        return OMX_ErrorInsufficientResources;
    }

    for(bufCnt=0; bufCnt < bufCntMin; ++bufCnt) {
        // allocate input buffers
      DEBUG_PRINT("OMX_UseBuffer No %d %d \n", bufCnt, bufSize);
      p_eglHeaders[bufCnt] = (struct temp_egl*)
                         malloc(sizeof(struct temp_egl));
      if(!p_eglHeaders[bufCnt]) {
          DEBUG_PRINT_ERROR("\n EGL allocation failed");
          return OMX_ErrorInsufficientResources;
      }
      p_eglHeaders[bufCnt]->pmem_fd = open(PMEM_DEVICE,O_RDWR);
      p_eglHeaders[bufCnt]->offset = 0;
      if(p_eglHeaders[bufCnt]->pmem_fd < 0) {
          DEBUG_PRINT_ERROR("\n open failed %s",PMEM_DEVICE);
          return OMX_ErrorInsufficientResources;
      }

#ifndef USE_ION
      /* TBD - this commenting is dangerous */
      align_pmem_buffers(p_eglHeaders[bufCnt]->pmem_fd, bufSize,
                                  8192);
#endif
      DEBUG_PRINT_ERROR("\n allocation size %d pmem fd %d",bufSize,p_eglHeaders[bufCnt]->pmem_fd);
      pvirt = (unsigned char *)mmap(NULL,bufSize,PROT_READ|PROT_WRITE,
                      MAP_SHARED,p_eglHeaders[bufCnt]->pmem_fd,0);
      DEBUG_PRINT_ERROR("\n Virtaul Address %p Size %d",pvirt,bufSize);
      if (pvirt == MAP_FAILED) {
        DEBUG_PRINT_ERROR("\n mmap failed for buffers");
        return OMX_ErrorInsufficientResources;
      }
        use_buf_virt_addr[bufCnt] = (unsigned)pvirt;
        error = OMX_UseEGLImage(dec_handle, &((*pBufHdrs)[bufCnt]),
                              nPortIndex, pvirt,(void *)p_eglHeaders[bufCnt]);
       }
    return error;
}

static OMX_ERRORTYPE use_output_buffer_multiple_fd ( OMX_COMPONENTTYPE *dec_handle,
                                  OMX_BUFFERHEADERTYPE  ***pBufHdrs,
                                  OMX_U32 nPortIndex,
                                  OMX_U32 bufSize,
                                  long bufCntMin)
{
    DEBUG_PRINT("Inside %s \n", __FUNCTION__);
    OMX_ERRORTYPE error=OMX_ErrorNone;
    long bufCnt=0;
    OMX_U8* pvirt = NULL;

    *pBufHdrs= (OMX_BUFFERHEADERTYPE **)
                   malloc(sizeof(OMX_BUFFERHEADERTYPE)* bufCntMin);
    if(*pBufHdrs == NULL){
        DEBUG_PRINT_ERROR("\n m_inp_heap_ptr Allocation failed ");
        return OMX_ErrorInsufficientResources;
     }
    pPlatformList = (OMX_QCOM_PLATFORM_PRIVATE_LIST *)
        malloc(sizeof(OMX_QCOM_PLATFORM_PRIVATE_LIST)* bufCntMin);

    if(pPlatformList == NULL){
        DEBUG_PRINT_ERROR("\n pPlatformList Allocation failed ");
        return OMX_ErrorInsufficientResources;
     }

    pPlatformEntry = (OMX_QCOM_PLATFORM_PRIVATE_ENTRY *)
        malloc(sizeof(OMX_QCOM_PLATFORM_PRIVATE_ENTRY)* bufCntMin);

    if(pPlatformEntry == NULL){
        DEBUG_PRINT_ERROR("\n pPlatformEntry Allocation failed ");
        return OMX_ErrorInsufficientResources;
     }

    pPMEMInfo = (OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *)
        malloc(sizeof(OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO)* bufCntMin);

    if(pPMEMInfo == NULL){
        DEBUG_PRINT_ERROR("\n pPMEMInfo Allocation failed ");
        return OMX_ErrorInsufficientResources;
     }

    //output_use_buffer = true;
    for(bufCnt=0; bufCnt < bufCntMin; ++bufCnt) {
        // allocate input buffers
      DEBUG_PRINT("OMX_UseBuffer_multiple_fd No %d %d \n", bufCnt, bufSize);

      pPlatformEntry[bufCnt].type       = OMX_QCOM_PLATFORM_PRIVATE_PMEM;
      pPlatformEntry[bufCnt].entry      = &pPMEMInfo[bufCnt];
      // Initialize the Platform List
      pPlatformList[bufCnt].nEntries    = 1;
      pPlatformList[bufCnt].entryList   = &pPlatformEntry[bufCnt];
      pPMEMInfo[bufCnt].offset          =  0;
      pPMEMInfo[bufCnt].pmem_fd = open(PMEM_DEVICE,O_RDWR);;
      if(pPMEMInfo[bufCnt].pmem_fd < 0) {
          DEBUG_PRINT_ERROR("\n open failed %s",PMEM_DEVICE);
          return OMX_ErrorInsufficientResources;
      }
#ifndef USE_ION
      /* TBD - this commenting is dangerous */
      align_pmem_buffers(pPMEMInfo[bufCnt].pmem_fd, bufSize,
                                  8192);
#endif
      DEBUG_PRINT("\n allocation size %d pmem fd 0x%x",bufSize,pPMEMInfo[bufCnt].pmem_fd);
      pvirt = (unsigned char *)mmap(NULL,bufSize,PROT_READ|PROT_WRITE,
                      MAP_SHARED,pPMEMInfo[bufCnt].pmem_fd,0);
      getFreePmem();
      DEBUG_PRINT("\n Virtaul Address %p Size %d pmem_fd=0x%x",pvirt,bufSize,pPMEMInfo[bufCnt].pmem_fd);
      if (pvirt == MAP_FAILED) {
        DEBUG_PRINT_ERROR("\n mmap failed for buffers");
        return OMX_ErrorInsufficientResources;
      }
      use_buf_virt_addr[bufCnt] = (unsigned)pvirt;
      error = OMX_UseBuffer(dec_handle, &((*pBufHdrs)[bufCnt]),
                            nPortIndex, &pPlatformList[bufCnt], bufSize, pvirt);
    }
    return error;
}
static void do_freeHandle_and_clean_up(bool isDueToError)
{
    int bufCnt = 0;
    OMX_STATETYPE state = OMX_StateInvalid;
    OMX_GetState(dec_handle, &state);
    if (state == OMX_StateExecuting || state == OMX_StatePause)
    {
      DEBUG_PRINT("Requesting transition to Idle");
      OMX_SendCommand(dec_handle, OMX_CommandStateSet, OMX_StateIdle, 0);
      wait_for_event();
    }
    OMX_GetState(dec_handle, &state);
    if (state == OMX_StateIdle)
    {
      DEBUG_PRINT("Requesting transition to Loaded");
      OMX_SendCommand(dec_handle, OMX_CommandStateSet, OMX_StateLoaded, 0);
      for(bufCnt=0; bufCnt < input_buf_cnt; ++bufCnt)
      {
         if (pInputBufHdrs[bufCnt]->pBuffer && input_use_buffer)
         {
            free(pInputBufHdrs[bufCnt]->pBuffer);
            pInputBufHdrs[bufCnt]->pBuffer = NULL;
            DEBUG_PRINT_ERROR("\nFree(pInputBufHdrs[%d]->pBuffer)",bufCnt);
         }
         OMX_FreeBuffer(dec_handle, 0, pInputBufHdrs[bufCnt]);
      }
      if (pInputBufHdrs)
      {
         free(pInputBufHdrs);
         pInputBufHdrs = NULL;
      }
      for(bufCnt = 0; bufCnt < portFmt.nBufferCountActual; ++bufCnt) {
        if (output_use_buffer && p_eglHeaders) {
            if(p_eglHeaders[bufCnt]) {
               munmap (pOutYUVBufHdrs[bufCnt]->pBuffer,
                       pOutYUVBufHdrs[bufCnt]->nAllocLen);
               close(p_eglHeaders[bufCnt]->pmem_fd);
               p_eglHeaders[bufCnt]->pmem_fd = -1;
               free(p_eglHeaders[bufCnt]);
               p_eglHeaders[bufCnt] = NULL;
            }
        }
        if (use_external_pmem_buf)
        {
            DEBUG_PRINT("Freeing in external pmem case: buffer=0x%x, pmem_fd=0x%d",
                              pOutYUVBufHdrs[bufCnt]->pBuffer,
                              pPMEMInfo[bufCnt].pmem_fd);
            if (pOutYUVBufHdrs[bufCnt]->pBuffer)
            {
                munmap (pOutYUVBufHdrs[bufCnt]->pBuffer,
                        pOutYUVBufHdrs[bufCnt]->nAllocLen);
            }
            if (&pPMEMInfo[bufCnt])
            {
                close(pPMEMInfo[bufCnt].pmem_fd);
                pPMEMInfo[bufCnt].pmem_fd = -1;
            }
        }
        OMX_FreeBuffer(dec_handle, 1, pOutYUVBufHdrs[bufCnt]);
      }
      if(p_eglHeaders) {
          free(p_eglHeaders);
          p_eglHeaders = NULL;
      }
      if (pPMEMInfo)
      {
          DEBUG_PRINT("Freeing in external pmem case:PMEM");
          free(pPMEMInfo);
          pPMEMInfo = NULL;
      }
      if (pPlatformEntry)
      {
          DEBUG_PRINT("Freeing in external pmem case:ENTRY");
          free(pPlatformEntry);
          pPlatformEntry = NULL;
      }
      if (pPlatformList)
      {
          DEBUG_PRINT("Freeing in external pmem case:LIST");
          free(pPlatformList);
          pPlatformList = NULL;
      }
      wait_for_event();
    }

    DEBUG_PRINT("[OMX Vdec Test] - Free handle decoder\n");
    OMX_ERRORTYPE result = OMX_FreeHandle(dec_handle);
    if (result != OMX_ErrorNone)
    {
       DEBUG_PRINT_ERROR("[OMX Vdec Test] - OMX_FreeHandle error. Error code: %d\n", result);
    }
    dec_handle = NULL;

    /* Deinit OpenMAX */
    DEBUG_PRINT("[OMX Vdec Test] - De-initializing OMX \n");
    OMX_Deinit();

    DEBUG_PRINT("[OMX Vdec Test] - closing all files\n");
    if(inputBufferFileFd != -1)
    {
        close(inputBufferFileFd);
        inputBufferFileFd = -1;
    }

    DEBUG_PRINT("[OMX Vdec Test] - after free inputfile\n");

    if (takeYuvLog && outputBufferFile) {
        fclose(outputBufferFile);
        outputBufferFile = NULL;
    }
    DEBUG_PRINT("[OMX Vdec Test] - after free outputfile\n");

    if(etb_queue)
    {
      free_queue(etb_queue);
      etb_queue = NULL;
    }
    DEBUG_PRINT("[OMX Vdec Test] - after free etb_queue \n");
    if(fbd_queue)
    {
      free_queue(fbd_queue);
      fbd_queue = NULL;
    }
    DEBUG_PRINT("[OMX Vdec Test] - after free iftb_queue\n");
    printf("*****************************************\n");
    if (isDueToError)
      printf("************...TEST FAILED...************\n");
    else
      printf("**********...TEST SUCCESSFULL...*********\n");
    printf("*****************************************\n");
}

static int Read_Buffer_From_DAT_File(OMX_BUFFERHEADERTYPE  *pBufHdr)
{
    long frameSize=0;
    char temp_buffer[10];
    char temp_byte;
    int bytes_read=0;
    int i=0;
    unsigned char *read_buffer=NULL;
    char c = '1'; //initialize to anything except '\0'(0)
    char inputFrameSize[12];
    int count =0; char cnt =0;
    memset(temp_buffer, 0, sizeof(temp_buffer));

    DEBUG_PRINT("Inside %s \n", __FUNCTION__);

    while (cnt < 10)
    /* Check the input file format, may result in infinite loop */
    {
        DEBUG_PRINT("loop[%d] count[%d]\n",cnt,count);
        count = read( inputBufferFileFd, &inputFrameSize[cnt], 1);
        if(inputFrameSize[cnt] == '\0' )
          break;
        cnt++;
    }
    inputFrameSize[cnt]='\0';
    frameSize = atoi(inputFrameSize);
    pBufHdr->nFilledLen = 0;

    /* get the frame length */
    lseek64(inputBufferFileFd, -1, SEEK_CUR);
    bytes_read = read(inputBufferFileFd, pBufHdr->pBuffer, frameSize);

    DEBUG_PRINT("Actual frame Size [%d] bytes_read using fread[%d]\n",
                  frameSize, bytes_read);

    if(bytes_read == 0 || bytes_read < frameSize ) {
        DEBUG_PRINT("Bytes read Zero After Read frame Size \n");
        DEBUG_PRINT("Checking VideoPlayback Count:video_playback_count is:%d\n",
                       video_playback_count);
        return 0;
    }
    pBufHdr->nTimeStamp = timeStampLfile;
    timeStampLfile += timestampInterval;
    return bytes_read;
}

static int Read_Buffer_ArbitraryBytes(OMX_BUFFERHEADERTYPE  *pBufHdr)
{
    int bytes_read=0;
    DEBUG_PRINT("Inside %s \n", __FUNCTION__);
    bytes_read = read(inputBufferFileFd, pBufHdr->pBuffer, NUMBER_OF_ARBITRARYBYTES_READ);
    if(bytes_read == 0) {
        DEBUG_PRINT("Bytes read Zero After Read frame Size \n");
        DEBUG_PRINT("Checking VideoPlayback Count:video_playback_count is:%d\n",
                      video_playback_count);
        return 0;
    }
#ifdef TEST_TS_FROM_SEI
    if (timeStampLfile == 0)
      pBufHdr->nTimeStamp = 0;
    else
      pBufHdr->nTimeStamp = LLONG_MAX;
#else
    pBufHdr->nTimeStamp = timeStampLfile;
#endif
    timeStampLfile += timestampInterval;
    return bytes_read;
}

static int Read_Buffer_From_Vop_Start_Code_File(OMX_BUFFERHEADERTYPE  *pBufHdr)
{
    unsigned int readOffset = 0;
    int bytes_read = 0;
    unsigned int code = 0;
    pBufHdr->nFilledLen = 0;
    static unsigned int header_code = 0;

    DEBUG_PRINT("Inside %s", __FUNCTION__);

    do
    {
      //Start codes are always byte aligned.
      bytes_read = read(inputBufferFileFd, &pBufHdr->pBuffer[readOffset], 1);
      if(bytes_read == 0 || bytes_read == -1)
      {
          DEBUG_PRINT("Bytes read Zero \n");
          break;
      }
      code <<= 8;
      code |= (0x000000FF & pBufHdr->pBuffer[readOffset]);
      //VOP start code comparision
      if (readOffset>3)
      {
        if(!header_code ){
          if( VOP_START_CODE == code)
          {
            header_code = VOP_START_CODE;
          }
          else if ( (0xFFFFFC00 & code) == SHORT_HEADER_START_CODE )
          {
            header_code = SHORT_HEADER_START_CODE;
          }
        }
        if ((header_code == VOP_START_CODE) && (code == VOP_START_CODE))
        {
            //Seek backwards by 4
            lseek64(inputBufferFileFd, -4, SEEK_CUR);
            readOffset-=3;
            break;
        }
        else if (( header_code == SHORT_HEADER_START_CODE ) && ( SHORT_HEADER_START_CODE == (code & 0xFFFFFC00)))
        {
            //Seek backwards by 4
            lseek64(inputBufferFileFd, -4, SEEK_CUR);
            readOffset-=3;
            break;
        }
      }
      readOffset++;
    }while (1);
    pBufHdr->nTimeStamp = timeStampLfile;
    timeStampLfile += timestampInterval;
    return readOffset;
}
static int Read_Buffer_From_Mpeg2_Start_Code(OMX_BUFFERHEADERTYPE  *pBufHdr)
{
  unsigned int readOffset = 0;
  int bytesRead = 0;
  unsigned int code = 0;
  pBufHdr->nFilledLen = 0;
  static unsigned int firstParse = true;
  unsigned int seenFrame = false;

  DEBUG_PRINT("Inside %s", __FUNCTION__);

  /* Read one byte at a time. Construct the code every byte in order to
   * compare to the start codes. Keep looping until we've read in a complete
   * frame, which can be either just a picture start code + picture, or can
   * include the sequence header as well
   */
  while (1) {
    bytesRead = read(inputBufferFileFd, &pBufHdr->pBuffer[readOffset], 1);

    /* Exit the loop if we can't read any more bytes */
    if (bytesRead == 0 || bytesRead == -1) {
      break;
    }

    /* Construct the code one byte at a time */
    code <<= 8;
    code |= (0x000000FF & pBufHdr->pBuffer[readOffset]);

    /* Can't compare the code to MPEG2 start codes until we've read the
     * first four bytes
     */
    if (readOffset >= 3) {

      /* If this is the first time we're reading from the file, then we
       * need to throw away the system start code information at the
       * beginning. We can just look for the first sequence header.
       */
      if (firstParse) {
        if (code == MPEG2_SEQ_START_CODE) {
          /* Seek back by 4 bytes and reset code so that we can skip
           * down to the common case below.
           */
          lseek(inputBufferFileFd, -4, SEEK_CUR);
          code = 0;
          readOffset -= 3;
          firstParse = false;
          continue;
        }
      }

      /* If we have already parsed a frame and we see a sequence header, then
       * the sequence header is part of the next frame so we seek back and
       * break.
       */
      if (code == MPEG2_SEQ_START_CODE) {
        if (seenFrame) {
          lseek(inputBufferFileFd, -4, SEEK_CUR);
          readOffset -= 3;
          break;
        }
        /* If we haven't seen a frame yet, then read in all the data until we
         * either see another frame start code or sequence header start code.
         */
      } else if (code == MPEG2_FRAME_START_CODE) {
        if (!seenFrame) {
          seenFrame = true;
        } else {
          lseek(inputBufferFileFd, -4, SEEK_CUR);
          readOffset -= 3;
          break;
        }
      }
    }

    readOffset++;
  }

  pBufHdr->nTimeStamp = timeStampLfile;
  timeStampLfile += timestampInterval;
  return readOffset;
}


static int Read_Buffer_From_Size_Nal(OMX_BUFFERHEADERTYPE  *pBufHdr)
{
    // NAL unit stream processing
    char temp_size[SIZE_NAL_FIELD_MAX];
    int i = 0;
    int j = 0;
    unsigned int size = 0;   // Need to make sure that uint32 has SIZE_NAL_FIELD_MAX (4) bytes
    int bytes_read = 0;

    // read the "size_nal_field"-byte size field
    bytes_read = read(inputBufferFileFd, pBufHdr->pBuffer + pBufHdr->nOffset, nalSize);
    if (bytes_read == 0 || bytes_read == -1)
    {
      DEBUG_PRINT("Failed to read frame or it might be EOF\n");
      return 0;
    }

    for (i=0; i<SIZE_NAL_FIELD_MAX-nalSize; i++)
    {
      temp_size[SIZE_NAL_FIELD_MAX - 1 - i] = 0;
    }

    /* Due to little endiannes, Reorder the size based on size_nal_field */
    for (j=0; i<SIZE_NAL_FIELD_MAX; i++, j++)
    {
      temp_size[SIZE_NAL_FIELD_MAX - 1 - i] = pBufHdr->pBuffer[pBufHdr->nOffset + j];
    }
    size = (unsigned int)(*((unsigned int *)(temp_size)));

    // now read the data
    bytes_read = read(inputBufferFileFd, pBufHdr->pBuffer + pBufHdr->nOffset + nalSize, size);
    if (bytes_read != size)
    {
      DEBUG_PRINT_ERROR("Failed to read frame\n");
    }

    pBufHdr->nTimeStamp = timeStampLfile;
    timeStampLfile += timestampInterval;

    return bytes_read + nalSize;
}

static int Read_Buffer_From_RCV_File_Seq_Layer(OMX_BUFFERHEADERTYPE  *pBufHdr)
{
    unsigned int readOffset = 0, size_struct_C = 0;
    unsigned int startcode = 0;
    pBufHdr->nFilledLen = 0;
    pBufHdr->nFlags = 0;

    DEBUG_PRINT("Inside %s \n", __FUNCTION__);

    read(inputBufferFileFd, &startcode, 4);

    /* read size of struct C as it need not be 4 always*/
    read(inputBufferFileFd, &size_struct_C, 4);

    /* reseek to beginning of sequence header */
    lseek64(inputBufferFileFd, -8, SEEK_CUR);

    if ((startcode & 0xFF000000) == 0xC5000000)
    {

      DEBUG_PRINT("Read_Buffer_From_RCV_File_Seq_Layer size_struct_C: %d\n", size_struct_C);

      readOffset = read(inputBufferFileFd, pBufHdr->pBuffer, VC1_SEQ_LAYER_SIZE_WITHOUT_STRUCTC + size_struct_C);

    }
    else if((startcode & 0xFF000000) == 0x85000000)
    {
      // .RCV V1 file

      rcv_v1 = 1;

      DEBUG_PRINT("Read_Buffer_From_RCV_File_Seq_Layer size_struct_C: %d\n", size_struct_C);

      readOffset = read(inputBufferFileFd, pBufHdr->pBuffer, VC1_SEQ_LAYER_SIZE_V1_WITHOUT_STRUCTC + size_struct_C);

    }
    else
    {
      DEBUG_PRINT_ERROR("Error: Unknown VC1 clip format %x\n", startcode);
    }

#if 0
    {
      int i=0;
      printf("Read_Buffer_From_RCV_File, length %d readOffset %d\n", readOffset, readOffset);
      for (i=0; i<36; i++)
      {
        printf("0x%.2x ", pBufHdr->pBuffer[i]);
        if (i%16 == 15) {
          printf("\n");
        }
      }
      printf("\n");
    }
#endif
    return readOffset;
}

static int Read_Buffer_From_RCV_File(OMX_BUFFERHEADERTYPE  *pBufHdr)
{
    unsigned int readOffset = 0;
    unsigned int len = 0;
    unsigned int key = 0;
    DEBUG_PRINT("Inside %s \n", __FUNCTION__);

    DEBUG_PRINT("Read_Buffer_From_RCV_File - nOffset %d\n", pBufHdr->nOffset);
    if(rcv_v1)
    {
      /* for the case of RCV V1 format, the frame header is only of 4 bytes and has
         only the frame size information */
        readOffset = read(inputBufferFileFd, &len, 4);
        DEBUG_PRINT("Read_Buffer_From_RCV_File - framesize %d %x\n", len, len);

    }
    else
    {
      /* for a regular RCV file, 3 bytes comprise the frame size and 1 byte for key*/
        readOffset = read(inputBufferFileFd, &len, 3);
        DEBUG_PRINT("Read_Buffer_From_RCV_File - framesize %d %x\n", len, len);

        readOffset = read(inputBufferFileFd, &key, 1);
      if ( (key & 0x80) == false)
      {
        DEBUG_PRINT("Read_Buffer_From_RCV_File - Non IDR frame key %x\n", key);
       }

    }

    if(!rcv_v1)
    {
      /* There is timestamp field only for regular RCV format and not for RCV V1 format*/
        readOffset = read(inputBufferFileFd, &pBufHdr->nTimeStamp, 4);
        DEBUG_PRINT("Read_Buffer_From_RCV_File - timeStamp %d\n", pBufHdr->nTimeStamp);
        pBufHdr->nTimeStamp *= 1000;
    }
    else
    {
        pBufHdr->nTimeStamp = timeStampLfile;
        timeStampLfile += timestampInterval;
    }

    if(len > pBufHdr->nAllocLen)
    {
       DEBUG_PRINT_ERROR("Error in sufficient buffer framesize %d, allocalen %d noffset %d\n",len,pBufHdr->nAllocLen, pBufHdr->nOffset);
       readOffset = read(inputBufferFileFd, pBufHdr->pBuffer+pBufHdr->nOffset,
                         pBufHdr->nAllocLen - pBufHdr->nOffset);

       loff_t off = (len - readOffset)*1LL;
       lseek64(inputBufferFileFd, off ,SEEK_CUR);
       return readOffset;
    }
    else {
        readOffset = read(inputBufferFileFd, pBufHdr->pBuffer+pBufHdr->nOffset, len);
    }
    if (readOffset != len)
    {
      DEBUG_PRINT("EOS reach or Reading error %d, %s \n", readOffset, strerror( errno ));
      return 0;
    }

#if 0
    {
      int i=0;
      printf("Read_Buffer_From_RCV_File, length %d readOffset %d\n", len, readOffset);
      for (i=0; i<64; i++)
      {
        printf("0x%.2x ", pBufHdr->pBuffer[i]);
        if (i%16 == 15) {
          printf("\n");
        }
      }
      printf("\n");
    }
#endif

    return readOffset;
}

static int Read_Buffer_From_VC1_File(OMX_BUFFERHEADERTYPE  *pBufHdr)
{
    static int timeStampLfile = 0;
    OMX_U8 *pBuffer = pBufHdr->pBuffer + pBufHdr->nOffset;
    DEBUG_PRINT("Inside %s \n", __FUNCTION__);
    unsigned int readOffset = 0;
    int bytes_read = 0;
    unsigned int code = 0, total_bytes = 0;
    int startCode_cnt = 0;
    int bSEQflag = 0;
    int bEntryflag = 0;
    unsigned int SEQbytes = 0;
    int numStartcodes = 0;

    numStartcodes = bHdrflag?1:2;

    do
    {
      if (total_bytes == pBufHdr->nAllocLen)
      {
        DEBUG_PRINT_ERROR("Buffer overflow!");
        break;
      }
      //Start codes are always byte aligned.
      bytes_read = read(inputBufferFileFd, &pBuffer[readOffset],1 );

      if(!bytes_read)
      {
          DEBUG_PRINT("\n Bytes read Zero \n");
          break;
      }
      total_bytes++;
      code <<= 8;
      code |= (0x000000FF & pBufHdr->pBuffer[readOffset]);

     if(!bSEQflag && (code == VC1_SEQUENCE_START_CODE)) {
        if(startCode_cnt) bSEQflag = 1;
      }

      if(!bEntryflag && ( code == VC1_ENTRY_POINT_START_CODE)) {
         if(startCode_cnt) bEntryflag = 1;
      }

      if(code == VC1_FRAME_START_CODE || code == VC1_FRAME_FIELD_CODE)
      {
         startCode_cnt++ ;
      }

      //VOP start code comparision
      if(startCode_cnt == numStartcodes)
      {
        if (VC1_FRAME_START_CODE == (code & 0xFFFFFFFF) ||
            VC1_FRAME_FIELD_CODE == (code & 0xFFFFFFFF))
        {
          previous_vc1_au = 0;
          if(VC1_FRAME_FIELD_CODE == (code & 0xFFFFFFFF))
          {
              previous_vc1_au = 1;
          }

          if(!bHdrflag && (bSEQflag || bEntryflag)) {
             lseek(inputBufferFileFd,-(SEQbytes+4),SEEK_CUR);
             readOffset -= (SEQbytes+3);
          }
          else {
            //Seek backwards by 4
            lseek64(inputBufferFileFd, -4, SEEK_CUR);
            readOffset-=3;
          }

          while(pBufHdr->pBuffer[readOffset-1] == 0)
            readOffset--;

          break;
        }
      }
      readOffset++;
      if(bSEQflag || bEntryflag) {
        SEQbytes++;
      }
    }while (1);

    pBufHdr->nTimeStamp = timeStampLfile;
    timeStampLfile += timestampInterval;

#if 0
    {
      int i=0;
      printf("Read_Buffer_From_VC1_File, readOffset %d\n", readOffset);
      for (i=0; i<64; i++)
      {
        printf("0x%.2x ", pBufHdr->pBuffer[i]);
        if (i%16 == 15) {
          printf("\n");
        }
      }
      printf("\n");
    }
#endif

    return readOffset;
}

static int Read_Buffer_From_DivX_4_5_6_File(OMX_BUFFERHEADERTYPE  *pBufHdr)
{
#define MAX_NO_B_FRMS 3 // Number of non-b-frames packed in each buffer
#define N_PREV_FRMS_B 1 // Number of previous non-b-frames packed
                        // with a set of consecutive b-frames
#define FRM_ARRAY_SIZE (MAX_NO_B_FRMS + N_PREV_FRMS_B)
    char *p_buffer = NULL;
    unsigned int offset_array[FRM_ARRAY_SIZE];
    int byte_cntr, pckt_end_idx;
    unsigned int read_code = 0, bytes_read, byte_pos = 0, frame_type;
    unsigned int i, b_frm_idx, b_frames_found = 0, vop_set_cntr = 0;
    bool pckt_ready = false;
#ifdef __DEBUG_DIVX__
    char pckt_type[20];
    int pckd_frms = 0;
    static unsigned long long int total_bytes = 0;
    static unsigned long long int total_frames = 0;
#endif //__DEBUG_DIVX__

    DEBUG_PRINT("Inside %s \n", __FUNCTION__);

    do {
      p_buffer = (char *)pBufHdr->pBuffer + byte_pos;

      bytes_read = read(inputBufferFileFd, p_buffer, NUMBER_OF_ARBITRARYBYTES_READ);
      byte_pos += bytes_read;
      for (byte_cntr = 0; byte_cntr < bytes_read && !pckt_ready; byte_cntr++) {
        read_code <<= 8;
        ((char*)&read_code)[0] = p_buffer[byte_cntr];
        if (read_code == VOP_START_CODE) {
          if (++byte_cntr < bytes_read) {
            frame_type = p_buffer[byte_cntr];
            frame_type &= 0x000000C0;
#ifdef __DEBUG_DIVX__
            switch (frame_type) {
              case 0x00: pckt_type[pckd_frms] = 'I'; break;
              case 0x40: pckt_type[pckd_frms] = 'P'; break;
              case 0x80: pckt_type[pckd_frms] = 'B'; break;
              default: pckt_type[pckd_frms] = 'X';
            }
            pckd_frms++;
#endif // __DEBUG_DIVX__
            offset_array[vop_set_cntr] = byte_pos - bytes_read + byte_cntr - 4;
            if (frame_type == 0x80) { // B Frame found!
              if (!b_frames_found) {
                // Try to packet N_PREV_FRMS_B previous frames
                // with the next consecutive B frames
                i = N_PREV_FRMS_B;
                while ((vop_set_cntr - i) < 0 && i > 0) i--;
                b_frm_idx = vop_set_cntr - i;
                if (b_frm_idx > 0) {
                  pckt_end_idx = b_frm_idx;
                  pckt_ready = true;
#ifdef __DEBUG_DIVX__
                  pckt_type[b_frm_idx] = '\0';
                  total_frames += b_frm_idx;
#endif //__DEBUG_DIVX__
                }
              }
              b_frames_found++;
            } else if (b_frames_found) {
              pckt_end_idx = vop_set_cntr;
              pckt_ready = true;
#ifdef __DEBUG_DIVX__
              pckt_type[pckd_frms - 1] = '\0';
              total_frames += pckd_frms - 1;
#endif //__DEBUG_DIVX__
            } else if (vop_set_cntr == (FRM_ARRAY_SIZE -1)) {
              pckt_end_idx = MAX_NO_B_FRMS;
              pckt_ready = true;
#ifdef __DEBUG_DIVX__
              pckt_type[pckt_end_idx] = '\0';
              total_frames += pckt_end_idx;
#endif //__DEBUG_DIVX__
            } else
              vop_set_cntr++;
          } else {
            // The vop start code was found in the last 4 bytes,
            // seek backwards by 4 to include this start code
            // with the next buffer.
            lseek64(inputBufferFileFd, -4, SEEK_CUR);
            byte_pos -= 4;
#ifdef __DEBUG_DIVX__
            pckd_frms--;
#endif //__DEBUG_DIVX__
          }
        }
      }
      if (pckt_ready) {
          loff_t off = (byte_pos - offset_array[pckt_end_idx]);
          if ( lseek64(inputBufferFileFd, -1LL*off , SEEK_CUR) == -1 ){
              DEBUG_PRINT_ERROR("lseek64 with offset = %lld failed with errno %d"
                                ", current position =0x%llx", -1LL*off,
                                errno, lseek64(inputBufferFileFd, 0, SEEK_CUR));
          }
      }
      else {
          char eofByte;
          int ret = read(inputBufferFileFd, &eofByte, 1 );
          if ( ret == 0 ) {
              offset_array[vop_set_cntr] = byte_pos;
              pckt_end_idx = vop_set_cntr;
              pckt_ready = true;
#ifdef __DEBUG_DIVX__
              pckt_type[pckd_frms] = '\0';
              total_frames += pckd_frms;
#endif //__DEBUG_DIVX__
          }
          else if (ret == 1){
              if ( lseek64(inputBufferFileFd, -1, SEEK_CUR ) == -1 ){
                  DEBUG_PRINT_ERROR("lseek64 failed with errno = %d, "
                                    "current fileposition = %llx",
                                    errno,
                                    lseek64(inputBufferFileFd, 0, SEEK_CUR));
              }
          }
          else {
              DEBUG_PRINT_ERROR("Error when checking for EOF");
          }
      }
    } while (!pckt_ready);
    pBufHdr->nFilledLen = offset_array[pckt_end_idx];
    pBufHdr->nTimeStamp = timeStampLfile;
    timeStampLfile += timestampInterval;
#ifdef __DEBUG_DIVX__
    total_bytes += pBufHdr->nFilledLen;
    ALOGE("[DivX] Packet: Type[%s] Size[%u] TS[%lld] TB[%llx] NFrms[%lld]\n",
      pckt_type, pBufHdr->nFilledLen, pBufHdr->nTimeStamp,
	  total_bytes, total_frames);
#endif //__DEBUG_DIVX__
    return pBufHdr->nFilledLen;
}

static int Read_Buffer_From_DivX_311_File(OMX_BUFFERHEADERTYPE  *pBufHdr)
{
    static OMX_S64 timeStampLfile = 0;
    char *p_buffer = NULL;
    bool pkt_ready = false;
    unsigned int frame_type = 0;
    unsigned int bytes_read = 0;
    unsigned int frame_size = 0;
    unsigned int num_bytes_size = 4;
    unsigned int num_bytes_frame_type = 1;
    unsigned int n_offset = pBufHdr->nOffset;

    DEBUG_PRINT("Inside %s \n", __FUNCTION__);

    pBufHdr->nTimeStamp = timeStampLfile;

    if (pBufHdr != NULL)
    {
        p_buffer = (char *)pBufHdr->pBuffer + pBufHdr->nOffset;
    }
    else
    {
        DEBUG_PRINT("\n ERROR:Read_Buffer_From_DivX_311_File: pBufHdr is NULL\n");
        return 0;
    }

    if (p_buffer == NULL)
    {
        DEBUG_PRINT("\n ERROR:Read_Buffer_From_DivX_311_File: p_bufhdr is NULL\n");
        return 0;
    }

    //Read first frame based on size
    //DivX 311 frame - 4 byte header with size followed by the frame

    bytes_read = read(inputBufferFileFd, &frame_size, num_bytes_size);

    DEBUG_PRINT("Read_Buffer_From_DivX_311_File: Frame size = %d\n", frame_size);
    n_offset += read(inputBufferFileFd, p_buffer, frame_size);

    pBufHdr->nTimeStamp = timeStampLfile;

    timeStampLfile += timestampInterval;

    //the packet is ready to be sent
    DEBUG_PRINT("\nReturning Read Buffer from Divx 311: TS=[%ld], Offset=[%d]\n",
           (long int)pBufHdr->nTimeStamp,
           n_offset );

    return n_offset;
}

static int open_video_file ()
{
    int error_code = 0;
    char outputfilename[512];
    DEBUG_PRINT("Inside %s filename=%s\n", __FUNCTION__, in_filename);

    if ( (inputBufferFileFd = open( in_filename, O_RDONLY | O_LARGEFILE) ) == -1 ){
        DEBUG_PRINT_ERROR("Error - i/p file %s could NOT be opened errno = %d\n",
                          in_filename, errno);
        error_code = -1;
    }
    else {
        DEBUG_PRINT_ERROR("i/p file %s is opened \n", in_filename);
    }

    if (takeYuvLog) {
        strlcpy(outputfilename, "yuvframes.yuv", 14);
        outputBufferFile = fopen (outputfilename, "ab");
        if (outputBufferFile == NULL)
        {
          DEBUG_PRINT_ERROR("ERROR - o/p file %s could NOT be opened\n", outputfilename);
          error_code = -1;
        }
        else
        {
          DEBUG_PRINT("O/p file %s is opened \n", outputfilename);
        }
    }
    return error_code;
}

void swap_byte(char *pByte, int nbyte)
{
  int i=0;

  for (i=0; i<nbyte/2; i++)
  {
    pByte[i] ^= pByte[nbyte-i-1];
    pByte[nbyte-i-1] ^= pByte[i];
    pByte[i] ^= pByte[nbyte-i-1];
  }
}

int drawBG(void)
{
    int result;
    int i;
#ifdef FRAMEBUFFER_32
    long * p;
#else
    short * p;
#endif
    void *fb_buf = mmap (NULL, finfo.smem_len,PROT_READ|PROT_WRITE, MAP_SHARED, fb_fd, 0);

    if (fb_buf == MAP_FAILED)
    {
        printf("ERROR: Framebuffer MMAP failed!\n");
        close(fb_fd);
        return -1;
    }

    vinfo.yoffset = 0;
    p = (long *)fb_buf;

    for (i=0; i < vinfo.xres * vinfo.yres; i++)
    {
    #ifdef FRAMEBUFFER_32
        *p++ = COLOR_BLACK_RGBA_8888;
    #else
        *p++ = CLR_KEY;
    #endif
    }

    if (ioctl(fb_fd, FBIOPAN_DISPLAY, &vinfo) < 0)
    {
        printf("ERROR: FBIOPAN_DISPLAY failed! line=%d\n", __LINE__);
        return -1;
    }

    DEBUG_PRINT("drawBG success!\n");
    return 0;
}

void overlay_set()
{
    overlayp = &overlay;
    overlayp->src.width  = stride;
    overlayp->src.height = sliceheight;
#ifdef MAX_RES_720P
    overlayp->src.format = MDP_Y_CRCB_H2V2;
    if(color_fmt == (OMX_COLOR_FORMATTYPE)QOMX_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka)
    {
        overlayp->src.format = MDP_Y_CRCB_H2V2_TILE;
    }
#endif
#ifdef MAX_RES_1080P
    overlayp->src.format = MDP_Y_CBCR_H2V2_TILE;
#endif
    overlayp->src_rect.x = 0;
    overlayp->src_rect.y = 0;
    overlayp->src_rect.w = width;
    overlayp->src_rect.h = height;

    if(width >= vinfo.xres)
    {
        overlayp->dst_rect.x = 0;
        overlayp->dst_rect.w = vinfo.xres;
    }
    else
    {
        overlayp->dst_rect.x = (vinfo.xres - width)/2;
        overlayp->dst_rect.w = width;
    }

    if(height >= vinfo.yres)
    {
        overlayp->dst_rect.h = (overlayp->dst_rect.w * height)/width;
        overlayp->dst_rect.y = 0;
        if (overlayp->dst_rect.h < vinfo.yres)
            overlayp->dst_rect.y = (vinfo.yres - overlayp->dst_rect.h)/2;
    }
    else
    {
        overlayp->dst_rect.y = (vinfo.yres - height)/2;
        overlayp->dst_rect.h = height;
    }

    overlayp->z_order = 0;
    printf("overlayp->dst_rect.x = %u \n", overlayp->dst_rect.x);
    printf("overlayp->dst_rect.y = %u \n", overlayp->dst_rect.y);
    printf("overlayp->dst_rect.w = %u \n", overlayp->dst_rect.w);
    printf("overlayp->dst_rect.h = %u \n", overlayp->dst_rect.h);

    overlayp->alpha = 0x0;
    overlayp->transp_mask = 0xFFFFFFFF;
    overlayp->flags = 0;
    overlayp->is_fg = 0;

    overlayp->id = MSMFB_NEW_REQUEST;
    vid_buf_front_id = ioctl(fb_fd, MSMFB_OVERLAY_SET, overlayp);
    if (vid_buf_front_id < 0)
    {
        printf("ERROR: MSMFB_OVERLAY_SET failed! line=%d\n", __LINE__);
    }
    vid_buf_front_id = overlayp->id;
    DEBUG_PRINT("\n vid_buf_front_id = %u", vid_buf_front_id);
    drawBG();
    displayYuv = 2;
}

int overlay_fb(struct OMX_BUFFERHEADERTYPE *pBufHdr)
{
    OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *pPMEMInfo = NULL;
    struct msmfb_overlay_data ov_front;
    memset(&ov_front, 0, sizeof(struct msmfb_overlay_data));
#if defined(_ANDROID_) && !defined(USE_EGL_IMAGE_TEST_APP) && !defined(USE_EXTERN_PMEM_BUF)
    MemoryHeapBase *vheap = NULL;
#endif

    DEBUG_PRINT("overlay_fb:");
    ov_front.id = overlayp->id;
    if (pBufHdr->pPlatformPrivate == NULL)
    {
        ALOGE("overlay_fb: pPlatformPrivate is null");
        return -1;
    }
    pPMEMInfo  = (OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *)
                ((OMX_QCOM_PLATFORM_PRIVATE_LIST *)
                    pBufHdr->pPlatformPrivate)->entryList->entry;
    if (pPMEMInfo == NULL)
    {

        ALOGE("overlay_fb: pmem_info is null");
        return -1;
    }
#if defined(_ANDROID_) && !defined(USE_EGL_IMAGE_TEST_APP) && !defined(USE_EXTERN_PMEM_BUF)
    vheap = (MemoryHeapBase*)pPMEMInfo->pmem_fd;
#endif

#if defined(_ANDROID_) && !defined(USE_EGL_IMAGE_TEST_APP) && !defined(USE_EXTERN_PMEM_BUF)
    ov_front.data.memory_id = vheap->getHeapID();
#else
    ov_front.data.memory_id = pPMEMInfo->pmem_fd;
#endif

    ov_front.data.offset = pPMEMInfo->offset;

    DEBUG_PRINT("\n ov_front.data.memory_id = %d", ov_front.data.memory_id);
    DEBUG_PRINT("\n ov_front.data.offset = %u", ov_front.data.offset);
    if (ioctl(fb_fd, MSMFB_OVERLAY_PLAY, (void*)&ov_front))
    {
        printf("\nERROR! MSMFB_OVERLAY_PLAY failed at frame (Line %d)\n",
            __LINE__);
        return -1;
    }
    DEBUG_PRINT("\nMSMFB_OVERLAY_PLAY successfull");
    return 0;
}

void overlay_unset()
{
    if (ioctl(fb_fd, MSMFB_OVERLAY_UNSET, &vid_buf_front_id))
    {
        printf("\nERROR! MSMFB_OVERLAY_UNSET failed! (Line %d)\n", __LINE__);
    }
}

void render_fb(struct OMX_BUFFERHEADERTYPE *pBufHdr)
{
    unsigned int addr = 0;
    OMX_OTHER_EXTRADATATYPE *pExtraData = 0;
    OMX_QCOM_EXTRADATA_FRAMEINFO *pExtraFrameInfo = 0;
    OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *pPMEMInfo = NULL;
    unsigned int destx, desty,destW, destH;
#if defined(_ANDROID_) && !defined(USE_EGL_IMAGE_TEST_APP) && !defined(USE_EXTERN_PMEM_BUF)
    MemoryHeapBase *vheap = NULL;
#endif

    unsigned int end = (unsigned int)(pBufHdr->pBuffer + pBufHdr->nAllocLen);

    struct mdp_blit_req *e;
    union {
        char dummy[sizeof(struct mdp_blit_req_list) +
               sizeof(struct mdp_blit_req) * 1];
        struct mdp_blit_req_list list;
    } img;

    if (fb_fd < 0)
    {
        DEBUG_PRINT_ERROR("Warning: /dev/fb0 is not opened!\n");
        return;
    }

    img.list.count = 1;
    e = &img.list.req[0];

    addr = (unsigned int)(pBufHdr->pBuffer + pBufHdr->nFilledLen);
    // align to a 4 byte boundary
    addr = (addr + 3) & (~3);

    // read to the end of existing extra data sections
    pExtraData = (OMX_OTHER_EXTRADATATYPE*)addr;

    while (addr < end && pExtraData->eType != OMX_ExtraDataFrameInfo)
    {
            addr += pExtraData->nSize;
            pExtraData = (OMX_OTHER_EXTRADATATYPE*)addr;
    }

    if (pExtraData->eType != OMX_ExtraDataFrameInfo)
    {
       DEBUG_PRINT_ERROR("pExtraData->eType %d pExtraData->nSize %d\n",pExtraData->eType,pExtraData->nSize);
    }
    pExtraFrameInfo = (OMX_QCOM_EXTRADATA_FRAMEINFO *)pExtraData->data;

   pPMEMInfo  = (OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *)
                ((OMX_QCOM_PLATFORM_PRIVATE_LIST *)
                    pBufHdr->pPlatformPrivate)->entryList->entry;
#if defined(_ANDROID_) && !defined(USE_EGL_IMAGE_TEST_APP) && !defined(USE_EXTERN_PMEM_BUF)
    vheap = (MemoryHeapBase *)pPMEMInfo->pmem_fd;
#endif


    DEBUG_PRINT_ERROR("DecWidth %d DecHeight %d\n",portFmt.format.video.nStride,portFmt.format.video.nSliceHeight);
    DEBUG_PRINT_ERROR("DispWidth %d DispHeight %d\n",portFmt.format.video.nFrameWidth,portFmt.format.video.nFrameHeight);



    e->src.width = portFmt.format.video.nStride;
    e->src.height = portFmt.format.video.nSliceHeight;
    e->src.format = MDP_Y_CBCR_H2V2;
        e->src.offset = pPMEMInfo->offset;
#if defined(_ANDROID_) && !defined(USE_EGL_IMAGE_TEST_APP) && !defined(USE_EXTERN_PMEM_BUF)
    e->src.memory_id = vheap->getHeapID();
#else
    e->src.memory_id = pPMEMInfo->pmem_fd;
#endif

    DEBUG_PRINT_ERROR("pmemOffset %d pmemID %d\n",e->src.offset,e->src.memory_id);

    e->dst.width = vinfo.xres;
    e->dst.height = vinfo.yres;
    e->dst.format = MDP_RGB_565;
    e->dst.offset = 0;
    e->dst.memory_id = fb_fd;

    e->transp_mask = 0xffffffff;
    DEBUG_PRINT("Frame interlace type %d!\n", pExtraFrameInfo->interlaceType);
    if(pExtraFrameInfo->interlaceType != OMX_QCOM_InterlaceFrameProgressive)
    {
       DEBUG_PRINT("Interlaced Frame!\n");
       e->flags = MDP_DEINTERLACE;
    }
    else
        e->flags = 0;
    e->alpha = 0xff;

    switch(displayWindow)
    {
    case 1: destx = 0;
            desty = 0;
            destW = vinfo.xres/2;
            destH = vinfo.yres/2;
            break;
    case 2: destx = vinfo.xres/2;
            desty = 0;
            destW = vinfo.xres/2;
            destH = vinfo.yres/2;
            break;

    case 3: destx = 0;
            desty = vinfo.yres/2;
            destW = vinfo.xres/2;
            destH = vinfo.yres/2;
            break;
     case 4: destx = vinfo.xres/2;
            desty = vinfo.yres/2;
            destW = vinfo.xres/2;
            destH = vinfo.yres/2;
            break;
     case 0:
     default:
            destx = 0;
            desty = 0;
            destW = vinfo.xres;
            destH = vinfo.yres;
    }


        if(portFmt.format.video.nFrameWidth < destW)
          destW = portFmt.format.video.nFrameWidth ;


        if(portFmt.format.video.nFrameHeight < destH)
           destH = portFmt.format.video.nFrameHeight;

    e->dst_rect.x = destx;
    e->dst_rect.y = desty;
    e->dst_rect.w = destW;
    e->dst_rect.h = destH;

    //e->dst_rect.w = 800;
    //e->dst_rect.h = 480;

    e->src_rect.x = 0;
    e->src_rect.y = 0;
    e->src_rect.w = portFmt.format.video.nFrameWidth;
    e->src_rect.h = portFmt.format.video.nFrameHeight;

    //e->src_rect.w = portFmt.format.video.nStride;
    //e->src_rect.h = portFmt.format.video.nSliceHeight;

    if (ioctl(fb_fd, MSMFB_BLIT, &img)) {
        DEBUG_PRINT_ERROR("MSMFB_BLIT ioctl failed!\n");
        return;
    }

    if (ioctl(fb_fd, FBIOPAN_DISPLAY, &vinfo) < 0) {
        DEBUG_PRINT_ERROR("FBIOPAN_DISPLAY failed! line=%d\n", __LINE__);
        return;
    }

    DEBUG_PRINT("render_fb complete!\n");
}

int disable_output_port()
{
    DEBUG_PRINT("DISABLING OP PORT\n");
    pthread_mutex_lock(&enable_lock);
    sent_disabled = 1;
    // Send DISABLE command
    OMX_SendCommand(dec_handle, OMX_CommandPortDisable, 1, 0);
    pthread_mutex_unlock(&enable_lock);
    // wait for Disable event to come back
    wait_for_event();
    if(p_eglHeaders) {
        free(p_eglHeaders);
        p_eglHeaders = NULL;
    }
    if (pPMEMInfo)
    {
        DEBUG_PRINT("Freeing in external pmem case:PMEM");
        free(pPMEMInfo);
        pPMEMInfo = NULL;
    }
    if (pPlatformEntry)
    {
        DEBUG_PRINT("Freeing in external pmem case:ENTRY");
        free(pPlatformEntry);
        pPlatformEntry = NULL;
    }
    if (pPlatformList)
    {
        DEBUG_PRINT("Freeing in external pmem case:LIST");
        free(pPlatformList);
        pPlatformList = NULL;
    }
    if (currentStatus == ERROR_STATE)
    {
      do_freeHandle_and_clean_up(true);
      return -1;
    }
    DEBUG_PRINT("OP PORT DISABLED!\n");
    return 0;
}

int enable_output_port()
{
    int bufCnt = 0;
    OMX_ERRORTYPE ret = OMX_ErrorNone;
    DEBUG_PRINT("ENABLING OP PORT\n");
    // Send Enable command
    OMX_SendCommand(dec_handle, OMX_CommandPortEnable, 1, 0);
#ifndef USE_EGL_IMAGE_TEST_APP
    /* Allocate buffer on decoder's o/p port */
    portFmt.nPortIndex = 1;
    if (use_external_pmem_buf)
    {
        DEBUG_PRINT("Enable op port: calling use_buffer_mult_fd\n");
        error =  use_output_buffer_multiple_fd(dec_handle,
                                               &pOutYUVBufHdrs,
                                               portFmt.nPortIndex,
                                               portFmt.nBufferSize,
                                               portFmt.nBufferCountActual);
    }
    else
    {
        error = Allocate_Buffer(dec_handle, &pOutYUVBufHdrs, portFmt.nPortIndex,
                                portFmt.nBufferCountActual, portFmt.nBufferSize);
    }
    if (error != OMX_ErrorNone) {
        DEBUG_PRINT_ERROR("Error - OMX_AllocateBuffer Output buffer error\n");
        return -1;
    }
    else
    {
        DEBUG_PRINT("OMX_AllocateBuffer Output buffer success\n");
        free_op_buf_cnt = portFmt.nBufferCountActual;
    }
#else
    error =  use_output_buffer(dec_handle,
                       &pOutYUVBufHdrs,
                        portFmt.nPortIndex,
                        portFmt.nBufferSize,
                        portFmt.nBufferCountActual);
    free_op_buf_cnt = portFmt.nBufferCountActual;
    if (error != OMX_ErrorNone) {
       DEBUG_PRINT_ERROR("ERROR - OMX_UseBuffer Input buffer failed");
       return -1;
    }
    else {
       DEBUG_PRINT("OMX_UseBuffer Input buffer success\n");
    }

#endif
    // wait for enable event to come back
    wait_for_event();
    if (currentStatus == ERROR_STATE)
    {
      do_freeHandle_and_clean_up(true);
      return -1;
    }
    if (pOutYUVBufHdrs == NULL)
    {
        DEBUG_PRINT_ERROR("Error - pOutYUVBufHdrs is NULL\n");
        return -1;
    }
    for(bufCnt=0; bufCnt < portFmt.nBufferCountActual; ++bufCnt) {
        DEBUG_PRINT("OMX_FillThisBuffer on output buf no.%d\n",bufCnt);
        if (pOutYUVBufHdrs[bufCnt] == NULL)
        {
            DEBUG_PRINT_ERROR("Error - pOutYUVBufHdrs[%d] is NULL\n", bufCnt);
            return -1;
        }
        pOutYUVBufHdrs[bufCnt]->nOutputPortIndex = 1;
        pOutYUVBufHdrs[bufCnt]->nFlags &= ~OMX_BUFFERFLAG_EOS;
        ret = OMX_FillThisBuffer(dec_handle, pOutYUVBufHdrs[bufCnt]);
        if (OMX_ErrorNone != ret) {
            DEBUG_PRINT_ERROR("ERROR - OMX_FillThisBuffer failed with result %d\n", ret);
        }
        else
        {
            DEBUG_PRINT("OMX_FillThisBuffer success!\n");
            free_op_buf_cnt--;
        }
    }
    DEBUG_PRINT("OP PORT ENABLED!\n");
    return 0;
}

int output_port_reconfig()
{
    DEBUG_PRINT("PORT_SETTING_CHANGE_STATE\n");
    if (disable_output_port() != 0)
	    return -1;

    /* Port for which the Client needs to obtain info */
    portFmt.nPortIndex = 1;
    OMX_GetParameter(dec_handle,OMX_IndexParamPortDefinition,&portFmt);
    DEBUG_PRINT("Min Buffer Count=%d", portFmt.nBufferCountMin);
    DEBUG_PRINT("Buffer Size=%d", portFmt.nBufferSize);
    if(OMX_DirOutput != portFmt.eDir) {
        DEBUG_PRINT_ERROR("Error - Expect Output Port\n");
        return -1;
    }
    height = portFmt.format.video.nFrameHeight;
    width = portFmt.format.video.nFrameWidth;
    stride = portFmt.format.video.nStride;
    sliceheight = portFmt.format.video.nSliceHeight;

    if (displayYuv == 2)
    {
      DEBUG_PRINT("Reconfiguration at middle of playback...");
      close_display();
      if (open_display() != 0)
      {
        printf("\n Error opening display! Video won't be displayed...");
        displayYuv = 0;
      }
    }

    if (displayYuv)
        overlay_set();

    if (enable_output_port() != 0)
	    return -1;
    DEBUG_PRINT("PORT_SETTING_CHANGE DONE!\n");
	return 0;
}

void free_output_buffers()
{
    int index = 0;
    OMX_BUFFERHEADERTYPE *pBuffer = (OMX_BUFFERHEADERTYPE *)pop(fbd_queue);
    while (pBuffer) {
        DEBUG_PRINT("\n pOutYUVBufHdrs %p p_eglHeaders %p output_use_buffer %d",
               pOutYUVBufHdrs,p_eglHeaders,output_use_buffer);
        if(pOutYUVBufHdrs && p_eglHeaders && output_use_buffer)
        {
           index = pBuffer - pOutYUVBufHdrs[0];
           DEBUG_PRINT("\n Index of free buffer %d",index);
           DEBUG_PRINT("\n Address freed %p size freed %d",pBuffer->pBuffer,
                  pBuffer->nAllocLen);
           munmap((void *)use_buf_virt_addr[index],pBuffer->nAllocLen);
           if(p_eglHeaders[index])
           {
               close(p_eglHeaders[index]->pmem_fd);
               free(p_eglHeaders[index]);
               p_eglHeaders[index] = NULL;
           }
        }

        if (pOutYUVBufHdrs && use_external_pmem_buf)
        {
            index = pBuffer - pOutYUVBufHdrs[0];
            DEBUG_PRINT("\n Address freed %p size freed %d,virt=0x%x,pmem_fd=0x%x",
                              pBuffer->pBuffer,
                              pBuffer->nAllocLen,
                              use_buf_virt_addr[index],
                              pPMEMInfo[index].pmem_fd);
            munmap((void *)use_buf_virt_addr[index],pBuffer->nAllocLen);
            getFreePmem();
            use_buf_virt_addr[index] = -1;
            if (&pPMEMInfo[index])
            {
                close(pPMEMInfo[index].pmem_fd);
                pPMEMInfo[index].pmem_fd = -1;
            }
        }
        DEBUG_PRINT("\n Free output buffer");
        OMX_FreeBuffer(dec_handle, 1, pBuffer);
        pBuffer = (OMX_BUFFERHEADERTYPE *)pop(fbd_queue);
    }
}

#ifndef USE_ION
static bool align_pmem_buffers(int pmem_fd, OMX_U32 buffer_size,
                                  OMX_U32 alignment)
{
  struct pmem_allocation allocation;
  allocation.size = buffer_size;
  allocation.align = clip2(alignment);

  if (allocation.align < 4096)
  {
    allocation.align = 4096;
  }
  if (ioctl(pmem_fd, PMEM_ALLOCATE_ALIGNED, &allocation) < 0)
  {
    DEBUG_PRINT_ERROR("\n Aligment failed with pmem driver");
    return false;
  }
  return true;
}
#endif

int open_display()
{
#ifdef _ANDROID_
  DEBUG_PRINT("\n Opening /dev/graphics/fb0");
  fb_fd = open("/dev/graphics/fb0", O_RDWR);
#else
  DEBUG_PRINT("\n Opening /dev/fb0");
  fb_fd = open("/dev/fb0", O_RDWR);
#endif
  if (fb_fd < 0) {
    printf("[omx_vdec_test] - ERROR - can't open framebuffer!\n");
    return -1;
  }

  DEBUG_PRINT("\n fb_fd = %d", fb_fd);
  if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &finfo) < 0)
  {
    printf("[omx_vdec_test] - ERROR - can't retrieve fscreenInfo!\n");
    close(fb_fd);
    return -1;
  }
  if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &vinfo) < 0)
  {
    printf("[omx_vdec_test] - ERROR - can't retrieve vscreenInfo!\n");
    close(fb_fd);
    return -1;
  }
  return 0;
}

void close_display()
{
  overlay_unset();
  close(fb_fd);
  fb_fd = -1;
}

void getFreePmem()
{
#ifndef USE_ION
   int ret = -1;
   /*Open pmem device and query free pmem*/
   int pmem_fd = open (PMEM_DEVICE,O_RDWR);

   if(pmem_fd < 0) {
     ALOGE("Unable to open pmem device");
     return;
   }
   struct pmem_freespace fs;
   ret = ioctl(pmem_fd, PMEM_GET_FREE_SPACE, &fs);
   if(ret) {
     ALOGE("IOCTL to query pmem free space failed");
     goto freespace_query_failed;
   }
   ALOGE("Available free space %lx largest chunk %lx\n", fs.total, fs.largest);
freespace_query_failed:
   close(pmem_fd);
#endif
}