aboutsummaryrefslogtreecommitdiff
path: root/nodes/pvmp3ffparsernode/src/pvmf_mp3ffparser_node.cpp
blob: 82660042ac5bc38528e03d4bf89e1c3bc8fda6e5 (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
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
/* ------------------------------------------------------------------
 * Copyright (C) 1998-2010 PacketVideo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 * -------------------------------------------------------------------
 */
#include "pvmf_mp3ffparser_node.h"

#define LOGINFO(m) PVLOGGER_LOGMSG(PVLOGMSG_INST_MLDBG,iLogger,PVLOGMSG_INFO,m);
#define LOGGAPLESSINFO(m) PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG,iGaplessLogger,PVLOGMSG_INFO,m);

// constructor
PVMFMP3FFParserNode::PVMFMP3FFParserNode(int32 aPriority)
        : PVMFNodeInterfaceImpl(aPriority, "PVMFMP3FFParserNode"),
        iSourceURLSet(false),
        iInitNextClip(false),
        iConfigOk(0),
        iMaxFrameSize(PVMP3FF_DEFAULT_MAX_FRAMESIZE),
        iMP3FormatBitrate(0),
        iLogger(NULL),
        iGaplessLogger(NULL),
        iSendDecodeFormatSpecificInfo(true),
        iCurrSampleDuration(0)
{
    iMetadataBuf = NULL;
    iMetadataBufSize = 0;
    iMetadataSize = 0;
    iSCSPFactory = NULL;
    iSCSP = NULL;
    iClipByteRate = 0;
    iMetadataInterval = 0;

    iNumClipsInPlayList = 0;
    iPlaybackClipIndex = -1;
    iLastPlayingClipIndex = -1;
    iClipIndexForMetadata = -1;
    iPlaylistRepositioning = false;
    iNextInitializedClipIndex = -1;
    iPlaylistExhausted = false;
    iPlaybackParserObj = NULL;
    iMetadataParserObj = NULL;


    iOutPort = NULL;
    iCPMContainer.iCPMLicenseInterface = NULL;
    iCPMContainer.iCPMLicenseInterfacePVI = NULL;
    iCPMContainer.iCPMMetaDataExtensionInterface   = NULL;
    iCPMGetMetaDataValuesCmdId = 0;
    iCPMUsageCompleteCmdId = 0;
    iCPMCloseSessionCmdId = 0;
    iCPMResetCmdId = 0;
    oWaitingOnLicense  = false;
    iAutoPaused = false;
    iDownloadProgressInterface = NULL;
    iDataStreamFactory         = NULL;
    iDataStreamInterface = NULL;
    iDataStreamReadCapacityObserver = NULL;
    iMP3ParserNodeMetadataValueCount = 0;
    iDownloadComplete = false;
    iFileSizeRecvd = false;
    iFileSize = 0;
    iCheckForMP3HeaderDuringInit = false;
    iDurationCalcAO = NULL;
    iUseCPMPluginRegistry = false;
    iIsByteSeekNotSupported = false;

    int32 err;
    OSCL_TRY(err,
             // Set the node capability data.
             // This node can support an unlimited number of ports.
             iNodeCapability.iCanSupportMultipleInputPorts = false;
             iNodeCapability.iCanSupportMultipleOutputPorts = false;
             iNodeCapability.iHasMaxNumberOfPorts = false;
             iNodeCapability.iMaxNumberOfPorts = 0;//no maximum
             iNodeCapability.iInputFormatCapability.push_back(PVMFFormatType(PVMF_MIME_MP3));
             iNodeCapability.iOutputFormatCapability.push_back(PVMFFormatType(PVMF_MIME_MP3));
             // secondry construction
             Construct();
            );

    if (err != OsclErrNone)
    {
        //if a leave happened, cleanup and re-throw the error
        iInputCommands.clear();
        iNodeCapability.iInputFormatCapability.clear();
        iNodeCapability.iOutputFormatCapability.clear();
        OSCL_CLEANUP_BASE_CLASS(PVMFNodeInterfaceImpl);
        iFileServer.Close();
        OSCL_LEAVE(err);
    }
    iMetadataVector.reserve(PVMF_MP3FFPARSER_NODE_METADATA_RESERVE);
}

// Secondary constructor
void PVMFMP3FFParserNode::Construct()
{
    iFileServer.Connect();
    iCPMContainer.Construct(PVMFSubNodeContainerBaseMp3::ECPM, this);
    //create the sub-node command queue.  Use a reserve to avoid
    //dynamic memory failure later.
    //Max depth is the max number of sub-node commands for any one node command.
    //Init command may take up to 9
    iSubNodeCmdVec.reserve(9);
    // initialize clip information vector
    iClipInfoList.reserve(PVMF_MP3_MAX_NUM_TRACKS_GAPLESS);
    iLogger = PVLogger::GetLoggerObject("PVMFMP3FFParserNode");
    iGaplessLogger = PVLogger::GetLoggerObject("sourcenode.gapless");
}

// Destructor
PVMFMP3FFParserNode::~PVMFMP3FFParserNode()
{
    if (IsAdded())
    {
        RemoveFromScheduler();
    }

    //Reset Logger
    iLogger = NULL;

    // Unbind the download progress clock
    iDownloadProgressClock.Unbind();
    // Release the download progress interface, if any
    if (iDownloadProgressInterface != NULL)
    {
        iDownloadProgressInterface->cancelResumeNotification();
        iDownloadProgressInterface->removeRef();
        iDownloadProgressInterface = NULL;
    }

    //if any CPM commands are pending, there will be a crash when they callback,
    //so panic here instead.
    if (iCPMContainer.CmdPending())
    {
        OSCL_ASSERT(0);
    }

    while (!iMetadataVector.empty())
    {
        iMetadataVector.erase(iMetadataVector.begin());
    }

    ReleaseTrack();
    // Clean up the file source
    CleanupFileSource();
    //CPM Cleanup should be done after CleanupFileSource
    iCPMContainer.Cleanup();
    // Disconnect fileserver
    iFileServer.Close();
}

PVMFStatus PVMFMP3FFParserNode::HandleExtensionAPICommands()
{
    PVMFStatus status = PVMFFailure;
    switch (iCurrentCommand.iCmd)
    {
        case PVMF_GENERIC_NODE_SET_DATASOURCE_POSITION:
            if (iPlaylistRepositioning)
            {
                iPlaylistRepositioning = false;
                status = DoSetDataSourcePositionPlaylist();
            }
            else
                status = DoSetDataSourcePosition();
            break;
        case PVMF_GENERIC_NODE_QUERY_DATASOURCE_POSITION:
            status = DoQueryDataSourcePosition();
            break;
        case PVMF_GENERIC_NODE_SET_DATASOURCE_RATE:
            status = DoSetDataSourceRate();
            break;
        case PVMF_GENERIC_NODE_GETNODEMETADATAVALUES:
            status = DoGetNodeMetadataValues();
            break;
        default: //unknown command, do an assert here
            //and complete the command with PVMFErrNotSupported
            status = PVMFErrNotSupported;
            OSCL_ASSERT(false);
            break;
    }
    return status;
}

PVMFStatus PVMFMP3FFParserNode::CancelCurrentCommand()
{
    // Cancel DoFlush here and return success.
    if (IsFlushPending())
    {
        CommandComplete(iCurrentCommand, PVMFErrCancelled);
        return PVMFSuccess;
    }

    /* The pending commands DoInit, DoReset, and DoGetMetadataValues
     * would be canceled in CPMCommandCompleted.
     * So return pending for now.
     */
    if (iCPMContainer.CancelPendingCommand())
    {
        return PVMFPending;//wait on sub-node cancel to complete.
    }
    else
    {
        CommandComplete(iCurrentCommand, PVMFErrCancelled);
        return PVMFSuccess;
    }
}

void PVMFMP3FFParserNode::CompleteInit(PVMFStatus aStatus)
{
    if (PVMF_GENERIC_NODE_INIT == iCurrentCommand.iCmd)
    {
        if (!iSubNodeCmdVec.empty())
        {
            iSubNodeCmdVec.front().iSubNodeContainer->CommandDone(aStatus, NULL, NULL);
        }
        else
        {
            CommandComplete(iCurrentCommand, aStatus);
        }
    }
    else // Either there is no current command or the current command is not init
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                        (0, "PVMFMP3FFParserNode::CompleteInit() Failure. Either there is no current command or the current command is not init"));
        OSCL_ASSERT(false);
    }
}

// CommandHandler for Reset command
PVMFStatus PVMFMP3FFParserNode::DoReset()
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::DoReset() In"));

    // Check if the node can accept the Reset command in the current state
    PVMFStatus status;

    if (iDownloadProgressInterface != NULL)
    {
        iDownloadProgressInterface->cancelResumeNotification();
    }
    if (iDurationCalcAO && iDurationCalcAO->IsBusy())
    {
        iDurationCalcAO->Cancel();
    }

    // Stop and cleanup
    ReleaseTrack();
    CleanupFileSource();
    // Cleanup CPM
    if (iCPMContainer.iCPM)
    {
        Push(iCPMContainer, PVMFSubNodeContainerBaseMp3::ECPMUsageComplete);
        Push(iCPMContainer, PVMFSubNodeContainerBaseMp3::ECPMCloseSession);
        Push(iCPMContainer, PVMFSubNodeContainerBaseMp3::ECPMReset);
        Push(iCPMContainer, PVMFSubNodeContainerBaseMp3::ECPMCleanup);
        //wait on CPM commands to execute
        status = PVMFPending;
    }
    else
    {
        status = PVMFSuccess;
    }
    return status;
}

// CommandHandler for Query Interface
PVMFStatus PVMFMP3FFParserNode::DoQueryInterface()
{
    // This node supports Query Interface from any state
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::DoQueryInterface() In"));
    PVUuid* uuid;
    PVInterface** ptr;
    iCurrentCommand.PVMFNodeCommandBase::Parse(uuid, ptr);
    PVMFStatus status;

    if (queryInterface(*uuid, *ptr))
    {
        // PVMFCPMPluginLicenseInterface is not part of this node
        if (*uuid != PVMFCPMPluginLicenseInterfaceUuid)
        {
            (*ptr)->addRef();
        }
        status = PVMFSuccess;
    }
    else
    {
        // Interface not supported
        *ptr = NULL;
        status = PVMFErrNotSupported;
    }
    return status;
}

// CommandHandler for port request

PVMFStatus PVMFMP3FFParserNode::DoRequestPort(PVMFPortInterface*&aPort)
{
    // This node supports port request from any state
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::DoRequestPort In"));
    aPort = NULL;
    // Retrieve port tag.
    int32 tag;
    OSCL_String* mimetype;
    iCurrentCommand.PVMFNodeCommandBase::Parse(tag, mimetype);

    //mimetype is not used on this node
    //validate the tag
    if (tag != PVMF_MP3FFPARSER_NODE_PORT_TYPE_SOURCE)
    {
        // Invalid port tag
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR,
                        (0, "PVMFMP3FFParserNode::DoRequestPort: Error - Invalid port tag"));
        return PVMFFailure;
    }

    //Allocate a new port
    int32 err = 0;
    OSCL_TRY(err,
             iOutPort = PVMF_BASE_NODE_NEW(PVMFMP3FFParserPort, (tag, this, 0, 0, 0,    // input queue isn't needed.
                                           DEFAULT_DATA_QUEUE_CAPACITY,
                                           DEFAULT_DATA_QUEUE_CAPACITY,
                                           DEFAULT_READY_TO_RECEIVE_THRESHOLD_PERCENT));
            );
    if (err != OsclErrNone || !iOutPort)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR,
                        (0, "PVMFMP3FFParserNode::DoRequestPort: Error - Out of memory"));
        return PVMFErrNoMemory;
    }

    OsclMemPoolResizableAllocator* trackdatamempool = NULL;
    PVMFResizableSimpleMediaMsgAlloc *mediadataimplalloc = NULL;
    PVMFMemPoolFixedChunkAllocator* mediadatamempool = NULL;
    MediaClockConverter* clockconv = NULL;
    err = 0;
    // Try block starts
    OSCL_TRY(err,
             // Instantiate the mem pool which will hold the actual track data
             trackdatamempool = PVMF_BASE_NODE_NEW(OsclMemPoolResizableAllocator,
                                                   (2 * PVMF3FF_DEFAULT_NUM_OF_FRAMES * iMaxFrameSize, 2));

             // Instantiate an allocator for the mediadata implementation,
             // have it use the mem pool defined above as its allocator
             mediadataimplalloc = PVMF_BASE_NODE_NEW(PVMFResizableSimpleMediaMsgAlloc, (trackdatamempool));

             // Instantiate another memory pool for the media data structures.
             mediadatamempool = PVMF_BASE_NODE_NEW(PVMFMemPoolFixedChunkAllocator,
                                                   ("Mp3FFPar", PVMP3FF_MEDIADATA_CHUNKS_IN_POOL,
                                                    PVMP3FF_MEDIADATA_CHUNKSIZE));
             if (iPlaybackParserObj)
{
    clockconv = PVMF_BASE_NODE_NEW(MediaClockConverter, (iPlaybackParserObj->GetTimescale()));
    }
            ); // Try block end

    if (err != OsclErrNone ||
            NULL == trackdatamempool ||
            NULL == mediadataimplalloc ||
            NULL == mediadatamempool ||
            NULL == clockconv)
    {
        if (clockconv)
        {
            OSCL_DELETE(clockconv);
        }
        if (mediadatamempool)
        {
            OSCL_DELETE(mediadatamempool);
        }
        if (mediadataimplalloc)
        {
            OSCL_DELETE(mediadataimplalloc);
        }
        if (trackdatamempool)
        {
            trackdatamempool->removeRef();
        }
        if (iOutPort)
        {
            OSCL_DELETE(iOutPort);
            iOutPort = NULL;
        }
        return PVMFErrNoMemory;
    }

    trackdatamempool->enablenullpointerreturn();
    mediadatamempool->enablenullpointerreturn();

    // Instantiate the PVMP3FFNodeTrackPortInfo object that contains the port.
    iTrack.iPort = iOutPort;
    iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_UNINITIALIZED;
    iTrack.iClockConverter = clockconv;
    iTrack.iMediaDataMemPool = mediadatamempool;
    iTrack.iTrackDataMemoryPool = trackdatamempool;
    iTrack.iMediaDataImplAlloc = mediadataimplalloc;
    iTrack.timestamp_offset = 0;

    // Return the port pointer to the caller.
    aPort = iOutPort;
    return PVMFSuccess;
}

// Called by the command handler AO to do the port release
PVMFStatus PVMFMP3FFParserNode::DoReleasePort()
{
    //This node supports release port from any state
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::DoReleasePort() In"));
    //Find the port in the port vector
    PVMFStatus status;
    PVMFPortInterface* ptr = NULL;
    iCurrentCommand.PVMFNodeCommandBase::Parse(ptr);

    PVMFMP3FFParserPort* port = (PVMFMP3FFParserPort*)ptr;

    if (iDurationCalcAO && iDurationCalcAO->IsBusy())
    {
        iDurationCalcAO->Cancel();
    }
    if (iOutPort == port)
    {
        ReleaseTrack();
        status = PVMFSuccess;
    }
    else
    {
        //port not found.
        status = PVMFFailure;
    }
    return status;
}

// Called by the command handler AO to do the node Init

PVMFStatus PVMFMP3FFParserNode::DoInit()
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::DoInit() In"));

    if (EPVMFNodeInitialized == iInterfaceState)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                        (0, "PVMFMP3FFParserNode::DoInit() already in Initialized state"));
        return PVMFSuccess;
    }

    PVMFStatus status = PVMFSuccess;
    PVMFDataStreamFactory* dsFactory = NULL;
    // Process Init according to the Node State
    if (iPlaybackClipIndex == -1)
    {
        // Instantiate the IMpeg3File object, this class represents the mp3ff library
        dsFactory = GetDataStreamFactory();
    }

    if (iUseCPMPluginRegistry)
    {
        //we need to go through the CPM sequence to check access on the file.
        if (oWaitingOnLicense == false)
        {
            Push(iCPMContainer, PVMFSubNodeContainerBaseMp3::ECPMInit);
        }
        else
        {
            Push(iCPMContainer, PVMFSubNodeContainerBaseMp3::ECPMApproveUsage);
            Push(iCPMContainer, PVMFSubNodeContainerBaseMp3::ECPMCheckUsage);
        }
        status = PVMFPending;
    }
    else
    {
        status = InitNextValidClipInPlaylist(0, dsFactory);
        if (PVMFSuccess == status)
        {
            LOGINFO((0, "PVMFMP3FFParserNode::DoInit() CheckForMP3HeaderAvailability() succeeded"));
        }
    }
    return status;
}

// CommandHandler for node Prepare
PVMFStatus PVMFMP3FFParserNode::DoPrepare()
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::DoPrepare() In"));

    if (EPVMFNodePrepared == iInterfaceState)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                        (0, "PVMFMP3FFParserNode::DoPrepare() already in Prepared state"));
        return PVMFSuccess;
    }

    // If this is an PDL session request callback from ProgressInterface when data with
    // ts TimeStamp is downloaded, DPI shall callback the node once data is downloaded
    if ((iDownloadProgressInterface != NULL) &&
            (iDownloadComplete == false))
    {
        // check for download complete
        // if download is not complete, request to be notified when data is ready
        TOsclFileOffset bytesReady = 0;
        PvmiDataStreamStatus status = iDataStreamInterface->QueryReadCapacity(iDataStreamSessionID, bytesReady);
        if (status == PVDS_END_OF_STREAM)
        {
            if (!iFileSizeRecvd)
            {
                iFileSize = (uint32)bytesReady;
                iFileSizeRecvd = true;
            }
            return PVMFSuccess;
        }
        if (bytesReady == 0)
        {

            uint32 ts = 0;
            iDownloadProgressInterface->requestResumeNotification(ts, iDownloadComplete);
            // Data is not available, autopause the track.
            iAutoPaused = true;
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG, (0, "PVMFMP3FFParserNode::DoPrepare() - Auto Pause Triggered, TS = %d", ts));
        }
    }
    return PVMFSuccess;
}

// CommandHandler for node Start
PVMFStatus PVMFMP3FFParserNode::DoStart()
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::DoStart() In"));

    if (EPVMFNodeStarted == iInterfaceState)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                        (0, "PVMFMP3FFParserNode::DoStart() already in Started state"));
        return PVMFSuccess;
    }

    // Process Start according to the Node State
    if (iInterfaceState == EPVMFNodePaused)
    {
        iAutoPaused = false;
        // If track was in Autopause state, change track state to
        // retrieve more data in case
        if (PVMP3FFNodeTrackPortInfo::TRACKSTATE_DOWNLOAD_AUTOPAUSE == iTrack.iState)
        {
            iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_GETDATA;
        }
    }
    return PVMFSuccess;
}

// CommandHandler for node Stop
PVMFStatus PVMFMP3FFParserNode::DoStop()
{

    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::DoStop() In"));

    iStreamID = 0;

    // Clear queued messages in ports
    if (iOutPort)
    {
        iOutPort->ClearMsgQueues();
    }
    // Position the parser to beginning of file
    if (iPlaybackParserObj)
    {
        iPlaybackParserObj->SeekToTimestamp(0);
    }
    // reset the track
    ResetTrack();
    iInitNextClip = false;
    iFileSizeRecvd = false;
    iDownloadComplete = false;
    if (iDurationCalcAO)
    {
        iDurationCalcAO->Cancel();
    }

    return PVMFSuccess;
}

// CommandHandler for node Flush
PVMFStatus PVMFMP3FFParserNode::DoFlush()
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::DoFlush() In"));

    // Notify all ports to suspend their input
    if (iOutPort)
    {
        iOutPort->SuspendInput();
    }


    // reset the track
    ResetTrack();
    if (iDurationCalcAO && iDurationCalcAO->IsBusy())
    {
        iDurationCalcAO->Cancel();
    }

    // Flush is asynchronous. It will remain pending until the flush completes
    return PVMFPending;
}

/**
 * CommandHandler for fetching Metadata Values
 */
PVMFStatus PVMFMP3FFParserNode::DoGetNodeMetadataValues()
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::DoGetNodeMetadataValues() In"));

    PVMFMetadataList* keylistptr_in = NULL;
    PVMFMetadataList* keylistptr = NULL;
    PVMFMetadataList completeKeyList;
    Oscl_Vector<PvmiKvp, OsclMemAllocator>* valuelistptr = NULL;
    uint32 starting_index;
    int32 max_entries;

    // Extract parameters from command structure
    iCurrentCommand.PVMFNodeCommand::Parse(keylistptr_in,
                                           valuelistptr,
                                           starting_index,
                                           max_entries);

    if (NULL == iMetadataParserObj ||
            NULL == keylistptr_in ||
            NULL == valuelistptr)
    {
        // The list pointer is invalid, or we cannot access the mp3 ff library.
        return PVMFFailure;
    }

    keylistptr = keylistptr_in;
    if (keylistptr_in->size() == 1)
    {
        if (oscl_strncmp((*keylistptr_in)[0].get_cstr(),
                         PVMF_MP3_PARSER_NODE_ALL_METADATA_KEY,
                         oscl_strlen(PVMF_MP3_PARSER_NODE_ALL_METADATA_KEY)) == 0)
        {
            //check if the user passed in "all" metadata key, in which case get the complete
            //key list from MP3 FF lib first
            int32 max = 0x7FFFFFFF;
            char* query = NULL;
            iMetadataParserObj->GetMetadataKeys(completeKeyList, 0, max, query);
            keylistptr = &completeKeyList;
        }
    }

    // The underlying mp3 ff library will fill in the values.
    PVMFStatus status = iMetadataParserObj->GetMetadataValues(*keylistptr, *valuelistptr, starting_index, max_entries);

    iMP3ParserNodeMetadataValueCount = (*valuelistptr).size();

    if (iCPMContainer.iCPMMetaDataExtensionInterface != NULL)
    {
        iCPMGetMetaDataValuesCmdId =
            (iCPMContainer.iCPMMetaDataExtensionInterface)->GetNodeMetadataValues(iCPMContainer.iSessionId,
                    (*keylistptr_in),
                    (*valuelistptr),
                    0);
        return PVMFPending;
    }
    return status;
}

// Port Processing routines

// Port Activity Handler
void PVMFMP3FFParserNode::HandlePortActivity(const PVMFPortActivity &aActivity)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::PortActivity: port=0x%x, type=%d",
                     aActivity.iPort, aActivity.iType));

    // A port has reported some activity or state change.
    // Find out whether processing event needs to be queued
    // and/or node event needs to be reported to the observer.
    switch (aActivity.iType)
    {
        case PVMF_PORT_ACTIVITY_CREATED:
            //Report port created info event to the node.
            PVMFNodeInterface::ReportInfoEvent(PVMFInfoPortCreated,
                                               (OsclAny*)aActivity.iPort);
            break;
        case PVMF_PORT_ACTIVITY_DELETED:
            //Report port deleted info event to the node.
            PVMFNodeInterface::ReportInfoEvent(PVMFInfoPortDeleted,
                                               (OsclAny*)aActivity.iPort);
            break;
        case PVMF_PORT_ACTIVITY_CONNECT:
        case PVMF_PORT_ACTIVITY_DISCONNECT:
        case PVMF_PORT_ACTIVITY_INCOMING_MSG:
            //nothing needed.
            break;
        case PVMF_PORT_ACTIVITY_OUTGOING_MSG:
            //An outgoing message was queued on this port.
            if (!aActivity.iPort->IsConnectedPortBusy())
                Reschedule();
            break;
        case PVMF_PORT_ACTIVITY_OUTGOING_QUEUE_BUSY:
            //No action is needed here, the node checks for
            //outgoing queue busy as needed during data processing.
            break;
        case PVMF_PORT_ACTIVITY_OUTGOING_QUEUE_READY:
            //Outgoing queue was previously busy, but is now ready.
            HandleOutgoingQueueReady(aActivity.iPort);
            break;
        case PVMF_PORT_ACTIVITY_CONNECTED_PORT_BUSY:
            // The connected port is busy
            // No action is needed here, the port processing code
            // checks for connected port busy during data processing.
            break;
        case PVMF_PORT_ACTIVITY_CONNECTED_PORT_READY:
            // The connected port has transitioned from Busy to Ready.
            // It's time to start processing outgoing messages again.
            if (aActivity.iPort->OutgoingMsgQueueSize() > 0)
            {
                Reschedule();
            }
            break;
        default:
            break;
    }
}

/**
 * Outgoing message handler
 */
PVMFStatus PVMFMP3FFParserNode::ProcessOutgoingMsg(PVMFPortInterface* aPort)
{
    // Called by the AO to process one message off the outgoing
    // message queue for the given port.  This routine will
    // try to send the data to the connected port.

    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::ProcessOutgoingMsg: aPort=0x%x",
                     aPort));

    PVMFStatus status = aPort->Send();
    if (status == PVMFErrBusy)
    {
        // Port was busy
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                        (0, "PVMFMP3FFParserNode::ProcessOutgoingMsg: \
                         Connected port goes into busy state"));
    }
    return status;
}

////////////////////////////////////////////////////////////////////////
/**
 * Active object implementation
 */
////////////////////////////////////////////////////////////////////////

/**
 * AO's entry point
 */
void PVMFMP3FFParserNode::Run()
{
    if (iCheckForMP3HeaderDuringInit)
    {
        // Read capacity notification was delivered
        iCheckForMP3HeaderDuringInit = false;
        IMpeg3File* parserObj = GetParserObjAtIndex(0);
        // this condition would occur only for network playback
        // PS/PD is only supported for clip index 0
        if (NULL == parserObj)
        {
            CompleteInit(PVMFFailure);
        }

        PVMFStatus cmdStatus = CheckForMP3HeaderAvailability(0);
        if (PVMFSuccess == cmdStatus)
        {
            LOGINFO((0, "PVMFMP3FFParserNode::Run() CheckForMP3HeaderAvailability() succeeded"));
            // complete init command
            CompleteInit(cmdStatus);

            iPlaybackClipIndex = iClipIndexForMetadata = 0;
            iPlaybackParserObj = iMetadataParserObj = parserObj;
        }
        else if (PVMFFailure == cmdStatus)
        {
            CompleteInit(cmdStatus);
        }
        return;
    }

    // Check InputCommandQueue, If command present
    // process commands

    if (!iInputCommands.empty())
    {
        ProcessCommand();
    }

    //Issue commands to the sub-nodes.
    if (!iCPMContainer.CmdPending() && !iSubNodeCmdVec.empty())
    {
        PVMFStatus status = iSubNodeCmdVec.front().iSubNodeContainer->IssueCommand(iSubNodeCmdVec.front().iCmd);
        if (status != PVMFPending)
        {
            iSubNodeCmdVec.front().iSubNodeContainer->CommandDone(status, NULL, NULL);
        }
    }

    if (!iOutPort)
        return;

    // Send outgoing messages
    if ((iInterfaceState == EPVMFNodeStarted || IsFlushPending()) &&
            iOutPort &&
            iOutPort->OutgoingMsgQueueSize() > 0 &&
            !iOutPort->IsConnectedPortBusy())
    {
        ProcessOutgoingMsg(iOutPort);
        // Reschedule if there is additional data to send.
        if (iOutPort->OutgoingMsgQueueSize() > 0 && !iOutPort->IsConnectedPortBusy())
        {
            Reschedule();
        }
    }

    // Create new data and send to the output queue
    if (iInterfaceState == EPVMFNodeStarted && !IsFlushPending())
    {
        if (HandleTrackState())  // Handle track state returns true if there is more data to be sent
        {
            // Reschedule if there is more data to send out
            Reschedule();
        }
    }

    // If we get here we did not process any ports or commands.
    // Check for completion of a flush command
    if (IsFlushPending() &&
            (!iOutPort || iOutPort->OutgoingMsgQueueSize() == 0))
    {
        //resume port input so the ports can be re-started.
        iOutPort->ResumeInput();
        CommandComplete(iCurrentCommand, PVMFSuccess);
    }
}

void PVMFMP3FFParserNode::PassDatastreamFactory(PVMFDataStreamFactory& aFactory,
        int32 aFactoryTag,
        const PvmfMimeString* aFactoryConfig)
{
    OSCL_UNUSED_ARG(aFactoryTag);
    OSCL_UNUSED_ARG(aFactoryConfig);

    if (iDataStreamFactory == NULL)
    {
        PVUuid uuid = PVMIDataStreamSyncInterfaceUuid;
        PVInterface* iFace = NULL;
        iDataStreamFactory = &aFactory;

        if (GetClipFormatTypeAt(0) == PVMF_MIME_DATA_SOURCE_SHOUTCAST_URL)
        {
            iSCSPFactory = PVMF_BASE_NODE_NEW(PVMFShoutcastStreamParserFactory, (&aFactory, iMetadataInterval));

            iFace = iSCSPFactory->CreatePVMFCPMPluginAccessInterface(uuid);
            if (iFace != NULL)
            {
                iSCSP = OSCL_STATIC_CAST(PVMFShoutcastStreamParser*, iFace);
                if (iMetadataBuf == NULL)
                {
                    iMetadataBuf = (uint8*)oscl_malloc(PV_SCSP_MAX_METADATA_TAG_SIZE * sizeof(uint8));
                    if (iMetadataBuf != NULL)
                    {
                        iMetadataBufSize = PV_SCSP_MAX_METADATA_TAG_SIZE;
                    }
                }
            }
        }
        else
        {
            iFace = iDataStreamFactory->CreatePVMFCPMPluginAccessInterface(uuid);
        }

        if (iFace != NULL)
        {
            iDataStreamInterface = OSCL_STATIC_CAST(PVMIDataStreamSyncInterface*, iFace);
            iDataStreamInterface->OpenSession(iDataStreamSessionID, PVDS_READ_ONLY);
        }
    }
    else
    {
        OSCL_ASSERT(false);
    }
}

void
PVMFMP3FFParserNode::PassDatastreamReadCapacityObserver(PVMFDataStreamReadCapacityObserver* aObserver)
{
    iDataStreamReadCapacityObserver = aObserver;
}

int32 PVMFMP3FFParserNode::convertSizeToTime(TOsclFileOffset aFileSize, uint32& aNPTInMS)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::ConvertSizeToTime() aFileSize=%d, aNPTInMS=%d", aFileSize, aNPTInMS));

    if (iPlaybackParserObj)
    {
        return iPlaybackParserObj->ConvertSizeToTime((uint32)aFileSize, aNPTInMS);
    }
    return -1;
}

bool PVMFMP3FFParserNode::setProtocolInfo(Oscl_Vector<PvmiKvp*, OsclMemAllocator>& aInfoKvpVec)
{
    if (aInfoKvpVec.empty())
    {
        return false;
    }
    for (uint32 j = 0; j < aInfoKvpVec.size(); j++)
    {
        if (!aInfoKvpVec[j])
        {
            return false;
        }

        if (oscl_strstr(aInfoKvpVec[j]->key, PROGRESSIVE_STREAMING_IS_BYTE_SEEK_NOT_SUPPORTED_STRING))
        {
            iIsByteSeekNotSupported = aInfoKvpVec[j]->value.bool_value; // value set only for byte-seek unsupported mode during PPB.
        }
    }


    for (uint32 i = 0; i < aInfoKvpVec.size(); i++)
    {
        if (!aInfoKvpVec[i])
        {
            return false;
        }

        if (oscl_strstr(aInfoKvpVec[i]->key, SHOUTCAST_MEDIA_DATA_LENGTH_STRING))
        {
            iMetadataInterval = aInfoKvpVec[i]->value.uint32_value;
        }
        else if (oscl_strstr(aInfoKvpVec[i]->key, SHOUTCAST_CLIP_BITRATE_STRING))
        {
            iClipByteRate = aInfoKvpVec[i]->value.uint32_value;
        }
        else if (oscl_strstr(aInfoKvpVec[i]->key, SHOUTCAST_IS_SHOUTCAST_SESSION_STRING))
        {
        }
    }
    return true;
}

void PVMFMP3FFParserNode::setFileSize(const TOsclFileOffset aFileSize)
{
    iFileSize = (uint32)aFileSize;
    iFileSizeRecvd = true;
}

void PVMFMP3FFParserNode::setDownloadProgressInterface(PVMFDownloadProgressInterface* download_progress)
{
    if (iDownloadProgressInterface)
    {
        iDownloadProgressInterface->removeRef();
    }
    iDownloadProgressInterface = download_progress;
    // get the download clock
    iDownloadProgressClock = iDownloadProgressInterface->getDownloadProgressClock();
}

void PVMFMP3FFParserNode::playResumeNotification(bool aDownloadComplete)

{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::playResumeNotification() In"));

    if (aDownloadComplete)
    {
        // DownloadProgressInterface signalled for resuming the playback
        iDownloadComplete = aDownloadComplete;

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "PVMFMP3FFParserNode::playResumeNotification Unbinding download clock"));
        iDownloadProgressClock.Unbind();
    }

    // Resume playback
    if (iAutoPaused)
    {
        iAutoPaused = false;
        switch (iTrack.iState)
        {
            case PVMP3FFNodeTrackPortInfo::TRACKSTATE_DOWNLOAD_AUTOPAUSE:
                iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_GETDATA;
                break;
            default:
                break;
        }
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "PVMFMP3FFParserNode::playResumeNotification() Sending PVMFInfoDataReady event"));
        // Reschedule AO to resume playback
        Reschedule();
    }
}

////////////////////////////////////////////////////////////////////////
// Private section
////////////////////////////////////////////////////////////////////////

// Handle Node's track state

bool PVMFMP3FFParserNode::HandleTrackState()
{
    // Flag to be active again or not
    bool ret_status = false;

    switch (iTrack.iState)
    {
        case PVMP3FFNodeTrackPortInfo::TRACKSTATE_UNINITIALIZED:
            // Node doesnt need to do any format specific initialization
            // just skip this step and set the state to GetData
            iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_GETDATA;
            // Continue on to retrieve and send the first frame
        case PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_GETDATA:
        {
            // Check if node needs to send BOS
            if (iTrack.iSendBOS)
            {
                // Send BOS downstream on all available tracks
                uint32 timestamp = iTrack.iClockConverter->get_converted_ts(COMMON_PLAYBACK_CLOCK_TIMESCALE);
                timestamp += iTrack.timestamp_offset;
                timestamp += iCurrSampleDuration;

                if (!SendBeginOfMediaStreamCommand(iTrack.iPort, iStreamID, timestamp, iTrack.iSeqNum++, iPlaybackClipIndex))
                {
                    return true;
                }
                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_NOTICE, (0, "PVMFMP3FFParserNode::HandleTrackState() BOS sent TS %d StreamID %d", timestamp, iStreamID));
                iTrack.iSendBOS = false;
            }
            // First, grab some data from the core mp3 ff parser library
            if (!RetrieveTrackData(iTrack))
            {
                // If it returns false, break out of the switch and return false,
                // this means node doesn't need to be run again in the current state.
                // unless we need to send end of track, beginning of clip and end of clip commands
                if ((iTrack.iState == PVMP3FFNodeTrackPortInfo::TRACKSTATE_SEND_ENDOFTRACK) ||
                        (iTrack.iState == PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_SENDBOC) ||
                        (iTrack.iState == PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_SENDEOC))
                {
                    Reschedule();
                }
                break;
            }
            iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_SENDDATA;
            // Continue to send data
        }
        case PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_SENDDATA:
            if (SendTrackData(iTrack))
            {
                iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_GETDATA;
                ret_status = true;
            }
            break;
        case PVMP3FFNodeTrackPortInfo::TRACKSTATE_SEND_ENDOFTRACK:
        {
            if (iPlaybackClipIndex < (int32)(iNumClipsInPlayList - 1))
            {
                iInitNextClip = true;
            }

            // lets initialize the next clip in queue.
            if (iInitNextClip)
            {
                PVMFStatus status = InitNextValidClipInPlaylist();
                if (status != PVMFSuccess)
                {
                    iInitNextClip = false;
                }
            }


            uint32 timestamp = iTrack.iClockConverter->get_converted_ts(COMMON_PLAYBACK_CLOCK_TIMESCALE);
            timestamp += iTrack.timestamp_offset;
            timestamp += iCurrSampleDuration;
            // Check if node needs to send BOS
            if (iTrack.iSendBOS)
            {
                // Send BOS downstream on all available tracks
                if (!SendBeginOfMediaStreamCommand(iTrack.iPort, iStreamID, timestamp, iTrack.iSeqNum++, iPlaybackClipIndex))
                {
                    return true;
                }
                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_NOTICE, (0, "PVMFMP3FFParserNode::HandleTrackState() BOS sent TS %d StreamID %d", timestamp, iStreamID));
                iTrack.iSendBOS = false;
            }

            if (SendEndOfTrackCommand(iTrack.iPort, iStreamID, timestamp, iTrack.iSeqNum++, iPlaybackClipIndex))
            {
                // EOS command sent successfully
                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_NOTICE, (0, "PVMFMP3FFParserNode::HandleTrackState() EOS sent TS %d StreamID %d", timestamp, iStreamID));
                iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_ENDOFTRACK;
                ReportInfoEvent(PVMFInfoEndOfData, (OsclAny*) &iPlaybackClipIndex);

                // if there are more clips to playback?
                if (iPlaybackClipIndex < (int32)(iNumClipsInPlayList - 1) && !iPlaylistExhausted && iNextInitializedClipIndex >= 0)
                {
                    // start sending out data from next clip immediately
                    IMpeg3File* parserObj = GetParserObjAtIndex(iNextInitializedClipIndex);
                    if (iNumClipsInPlayList > 1 &&
                            iNextInitializedClipIndex < (int32)iNumClipsInPlayList && // iNextInitializedClip index is within the clip list
                            NULL != parserObj) //next clip has been intialized successfully
                    {
                        iPlaybackClipIndex = iNextInitializedClipIndex; // pick up the next clip in list
                        iPlaybackParserObj = parserObj;
                        iTrack.iSendBOS = true;
                        iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_GETDATA;
                        uint32 timestamp = iTrack.iClockConverter->get_converted_ts(COMMON_PLAYBACK_CLOCK_TIMESCALE);
                        iTrack.timestamp_offset += timestamp;
                        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_NOTICE, (0, "PVMFMP3FFParserNode::HandleTrackState() TimeStampOffset [%d]", iTrack.timestamp_offset));
                        iTrack.iClockConverter->set_clock((uint32)0, (uint32)0);
                        Reschedule();
                    }
                }
                else
                {
                    iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_ENDOFTRACK;
                }
            }
            else
            {
                // EOS command sending failed -- wait on outgoing queue ready notice
                // before trying again.
                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_NOTICE, (0, "PVMFMP3FFParserNode::HandleTrackState() EOS media command sending failed"));
                return true;
            }
        }
        break;

        case PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_SENDBOC:
            // need to send BOC
            // then followed by data
            if (iClipInfoList[iPlaybackClipIndex].iClipInfo.iSendBOC &&
                    iClipInfoList[iPlaybackClipIndex].iClipInfo.iHasBOCFrame)
            {
                // send BOC downstream
                if (!SendBeginOfClipCommand(iTrack))
                {
                    // try again
                    return true;
                }
            }
            // may need to send EOC as well
            if (iClipInfoList[iPlaybackClipIndex].iClipInfo.iSendEOC &&
                    iClipInfoList[iPlaybackClipIndex].iClipInfo.iHasEOCFrame)
            {
                iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_SENDEOC;
            }
            // falling through
        case PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_SENDEOC:

            // need to send EOC
            // then followed by data
            if (iClipInfoList[iPlaybackClipIndex].iClipInfo.iSendEOC &&
                    iClipInfoList[iPlaybackClipIndex].iClipInfo.iHasEOCFrame)
            {
                // send EOC downstream
                if (!SendEndOfClipCommand(iTrack))
                {
                    // try again
                    return true;
                }
            }

            // send data
            iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_SENDDATA;

            if (SendTrackData(iTrack))
            {
                iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_GETDATA;
                ret_status = true;
            }
            break;

        case PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRACKDATAPOOLEMPTY:
        case PVMP3FFNodeTrackPortInfo::TRACKSTATE_MEDIADATAPOOLEMPTY:
        case PVMP3FFNodeTrackPortInfo::TRACKSTATE_INITIALIZED:
        case PVMP3FFNodeTrackPortInfo::TRACKSTATE_ENDOFTRACK:
        case PVMP3FFNodeTrackPortInfo::TRACKSTATE_DESTFULL:
        case PVMP3FFNodeTrackPortInfo::TRACKSTATE_SOURCEEMPTY:
        case PVMP3FFNodeTrackPortInfo::TRACKSTATE_ERROR:
        default:
            break;
    }
    return ret_status;
}

// Retrieve Data from Mp3FF

bool PVMFMP3FFParserNode::RetrieveTrackData(PVMP3FFNodeTrackPortInfo& aTrackPortInfo)
{
    // parser object is null, assert here
    OSCL_ASSERT(NULL != iPlaybackParserObj);
    // Parsing is successful, we must have estimated the duration by now.
    // Pass the duration to download progress interface
    if (iDownloadProgressInterface && iFileSizeRecvd &&
            iFileSize > 0 && NULL != iPlaybackParserObj)
    {
        iPlaybackParserObj->SetFileSize(iFileSize);
        uint32 durationInMsec = iPlaybackParserObj->GetDuration();
        if (durationInMsec > 0)
        {
            iDownloadProgressInterface->setClipDuration(durationInMsec);
            int32 leavecode = 0;
            PVMFDurationInfoMessage* eventMsg = NULL;
            OSCL_TRY(leavecode, eventMsg = PVMF_BASE_NODE_NEW(PVMFDurationInfoMessage, (durationInMsec)));

            uint8 localbuffer[4];
            oscl_memcpy(localbuffer, &iPlaybackClipIndex, sizeof(uint32));
            PVMFAsyncEvent asyncevent(PVMFInfoEvent, PVMFInfoDurationAvailable, NULL, OSCL_STATIC_CAST(PVInterface*, eventMsg), NULL, localbuffer, 4);

            ReportInfoEvent(asyncevent);

            if (eventMsg)
            {
                eventMsg->removeRef();
            }
            iFileSize = 0;
        }
    }

    if (iAutoPaused == true)
    {
        aTrackPortInfo.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_DOWNLOAD_AUTOPAUSE;
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                        (0, "PVMFMP3FFParserNode::RetrieveTrackData() Node in Auto pause"));
        return false;
    }

    //Maximum number of mp3 frames to be read at a time
    uint32 numsamples = PVMF3FF_DEFAULT_NUM_OF_FRAMES;
    // Create new media data buffer from pool
    int errcode = 0;
    OsclSharedPtr<PVMFMediaDataImpl> mediaDataImplOut;

    // Try block start
    OSCL_TRY(errcode,
             mediaDataImplOut = aTrackPortInfo.iMediaDataImplAlloc->allocate(numsamples * iMaxFrameSize)
            );
    // Try block end

    if (errcode != 0)
    {
        // There was an error while allocating MediaDataImpl
        if (errcode == OsclErrNoResources)
        {
            aTrackPortInfo.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRACKDATAPOOLEMPTY;
            aTrackPortInfo.iTrackDataMemoryPool->notifyfreeblockavailable(*this, numsamples*iMaxFrameSize); // Enable flag to receive event when next deallocate() is called on pool
        }
        else if (errcode == OsclErrNoMemory)
        {
            // Memory allocation for the pool failed
            aTrackPortInfo.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_ERROR;
            ReportErrorEvent(PVMFErrNoMemory, NULL);
        }
        else if (errcode == OsclErrArgument)
        {
            // Invalid parameters passed to mempool
            aTrackPortInfo.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_ERROR;
            ReportErrorEvent(PVMFErrArgument, NULL);
        }
        else
        {
            // General error
            aTrackPortInfo.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_ERROR;
            ReportErrorEvent(PVMFFailure, NULL);
        }
        // All above conditions were Error conditions
        return false;
    }

    if (mediaDataImplOut.GetRep() == NULL)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_INFO, (0, "PVMFMP3FFParserNode::RetrieveTrackData() No Resource Found"));
        aTrackPortInfo.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRACKDATAPOOLEMPTY;
        aTrackPortInfo.iTrackDataMemoryPool->notifyfreeblockavailable(*this);
        return false;
    }

    PVMFSharedMediaDataPtr mediadataout;
    mediadataout =
        PVMFMediaData::createMediaData(mediaDataImplOut, aTrackPortInfo.iMediaDataMemPool);

    if (mediadataout.GetRep() == NULL)
    {
        aTrackPortInfo.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_MEDIADATAPOOLEMPTY;
        aTrackPortInfo.iMediaDataMemPool->notifyfreechunkavailable(*this);
        return false;
    }

    // Retrieve memory fragment to write to
    OsclRefCounterMemFrag refCtrMemFragOut;
    OsclMemoryFragment memFragOut;
    mediadataout->getMediaFragment(0, refCtrMemFragOut);
    memFragOut.ptr = refCtrMemFragOut.getMemFrag().ptr;

    // Set up the GAU structure
    GAU gau;
    gau.numMediaSamples = numsamples;
    gau.buf.num_fragments = 1;
    gau.buf.buf_states[0] = NULL;
    gau.buf.fragments[0].ptr = refCtrMemFragOut.getMemFrag().ptr;
    gau.buf.fragments[0].len = refCtrMemFragOut.getCapacity();
    gau.frameNum = 0;

    int32 eocFrameIndex = -1;
    uint32 numPaddingFrames = 0;
    uint32 framesToFollowEOC = 0;
    // Mp3FF ErrorCode
    MP3ErrorType error = MP3_SUCCESS;
    // Grab data from the mp3 ff parser library
    int32 retval = iPlaybackParserObj->GetNextBundledAccessUnits(&numsamples, &gau, error, eocFrameIndex, numPaddingFrames);

    // Determine actual size of the retrieved data by summing each sample length in GAU
    // Check if the frame contains encoder delay or zero padding
    uint32 actualdatasize = 0;
    iCurrSampleDuration = 0;
    for (uint32 index = 0; index < numsamples; ++index)
    {
        actualdatasize += gau.info[index].len;
        iCurrSampleDuration += gau.info[index].ts_delta;

        if ((gau.frameNum + index) == iClipInfoList[iPlaybackClipIndex].iClipInfo.iFrameBOC)
        {
            iClipInfoList[iPlaybackClipIndex].iClipInfo.iHasBOCFrame = true;
        }

        if (eocFrameIndex >= 0 && eocFrameIndex == (int32) index)
        {
            iClipInfoList[iPlaybackClipIndex].iClipInfo.iFirstFrameEOC = gau.frameNum + eocFrameIndex;
            if (iClipInfoList[iPlaybackClipIndex].iClipInfo.iGaplessInfoAvailable)
            {
                // number of frames read this cycle
                framesToFollowEOC = numsamples;
                // there could possibly be more frames following
                if (MP3_SUCCESS == error)
                {
                    // account for more samples present
                    framesToFollowEOC += numPaddingFrames;
                }
            }
            else
            {
                // gapless metadata is not available
                framesToFollowEOC = iPlaybackParserObj->GetNumSampleEntries() - gau.frameNum + 1;
            }

            iClipInfoList[iPlaybackClipIndex].iClipInfo.iFramesToFollowEOC = framesToFollowEOC;
            iClipInfoList[iPlaybackClipIndex].iClipInfo.iHasEOCFrame = true;
        }
    }

    if (retval > 0)
    {
        // Set buffer size
        mediadataout->setMediaFragFilledLen(0, actualdatasize);
        mediaDataImplOut->setCapacity(actualdatasize);
        // Return the unused space from mempool back
        if (refCtrMemFragOut.getCapacity() > actualdatasize)
        {
            // Need to go to the resizable memory pool and free some memory
            aTrackPortInfo.iMediaDataImplAlloc->ResizeMemoryFragment(mediaDataImplOut);
        }

        // Set format specific info for the first frame
        if (iSendDecodeFormatSpecificInfo)
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                            (0, "PVMFMP3FFParserNode::RetrieveTrackData() Send channel sample info"));
            iSendDecodeFormatSpecificInfo = false;
            mediadataout->setFormatSpecificInfo(iDecodeFormatSpecificInfo);
        }

        // Set M bit to 1 always - MP3 FF only outputs complete frames
        uint32 markerInfo = 0;
        markerInfo |= PVMF_MEDIA_DATA_MARKER_INFO_M_BIT;

        // Set Key Frame bit
        if (aTrackPortInfo.iFirstFrame)
        {
            markerInfo |= PVMF_MEDIA_DATA_MARKER_INFO_RANDOM_ACCESS_POINT_BIT;
            aTrackPortInfo.iFirstFrame = false;
        }
        mediaDataImplOut->setMarkerInfo(markerInfo);

        // Save the media data in the trackport info
        aTrackPortInfo.iMediaData = mediadataout;
        // Retrieve timestamp and convert to milliseconds
        aTrackPortInfo.iClockConverter->update_clock(gau.info[0].ts);
        uint32 timestamp = aTrackPortInfo.iClockConverter->get_converted_ts(COMMON_PLAYBACK_CLOCK_TIMESCALE);
        timestamp += aTrackPortInfo.timestamp_offset;

        // Set the media data timestamp
        aTrackPortInfo.iMediaData->setTimestamp(timestamp);

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                        (0, "PVMFMP3FFParserNode::RetrieveTrackData Seq=%d, TS=%d ClipId=%d", aTrackPortInfo.iSeqNum, timestamp, iPlaybackClipIndex));

        // if gapless, check if BOC and/or EOC has to be sent
        // if the whole clip fits inside the frag, both BOC and EOC have to be sent
        if (iClipInfoList[iPlaybackClipIndex].iClipInfo.iSendBOC && iClipInfoList[iPlaybackClipIndex].iClipInfo.iHasBOCFrame)
        {
            // first frame and gapless
            // send BOC msg downstream
            if (!SendBeginOfClipCommand(aTrackPortInfo))
            {
                // failed to send BOC
                // data is already in aTrackPortInfo.iMediaData
                iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_SENDBOC;
                return false;
            }
        }

        // Set msg sequence number and stream id
        aTrackPortInfo.iMediaData->setSeqNum(aTrackPortInfo.iSeqNum++);
        aTrackPortInfo.iMediaData->setStreamID(iStreamID);

        if (iClipInfoList[iPlaybackClipIndex].iClipInfo.iSendEOC && iClipInfoList[iPlaybackClipIndex].iClipInfo.iHasEOCFrame)
        {
            // first frame containing zero padding and gapless
            // send EOC msg downstream
            if (!SendEndOfClipCommand(aTrackPortInfo))
            {
                // failed to send EOC
                // data is already in aTrackPortInfo.iMediaData
                iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_SENDEOC;
                return false;
            }
        }

        if (error == MP3_INSUFFICIENT_DATA && !iDownloadProgressInterface)
        {
            //parser reported underflow during local playback session
            if (!SendTrackData(iTrack))
            {
                // SendTrackData un-successful
                iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_SENDDATA;
                return false;
            }
        }
    }
    // EOS may occur even if some data was read
    // Also handles the condition if somehow error was not set even
    // if there is no data to read.
    if ((retval <= 0) || (MP3_SUCCESS != error))
    {
        // ffparser was not able to read data
        if (error == MP3_INSUFFICIENT_DATA) // mp3ff return insufficient data
        {
            // Check if DPI is present
            if (iDownloadProgressInterface != NULL)
            {
                if (retval > 0)
                {
                    //parser reported underflow during download playback session
                    if (!SendTrackData(iTrack))
                    {
                        // SendTrackData un-successful
                        iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_SENDDATA;
                        return true;
                    }
                }

                if (iDownloadComplete)
                {
                    aTrackPortInfo.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_SEND_ENDOFTRACK;
                    return false;
                }
                // ffparser ran out of data, need to request a call back from DPI
                // when data beyond current timestamp is downloaded
                uint32 timeStamp = iPlaybackParserObj->GetTimestampForCurrentSample();
                iDownloadProgressInterface->requestResumeNotification(timeStamp, iDownloadComplete);
                // Change track state to Autopause and set iAutopause
                aTrackPortInfo.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_DOWNLOAD_AUTOPAUSE;
                iAutoPaused = true;
                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                                (0, "PVMFMP3FFParserNode::RetrieveTrackData() \
                                 Auto pause Triggered"));
                return false;
            }
            else
            {
                // if we recieve Insufficient data for local playback from parser library that means
                // its end of track, so change track state to send end of track.
                aTrackPortInfo.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_SEND_ENDOFTRACK;
                return false;
            }
        }
        else if (error == MP3_END_OF_FILE) // mp3ff return EOF
        {
            aTrackPortInfo.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_SEND_ENDOFTRACK;
            return false;
        }
        else
        {
            PVMFStatus errCode = PVMFErrArgument;
            if (error == MP3_ERROR_UNKNOWN_OBJECT)
            {
                PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_NOTICE,
                                (0, "PVMFMP3FFParserNode::RetrieveTrackData() \
                                 Clip format not identified by parser %d", error));
                errCode = PVMFErrNotSupported;
            }
            else
            {
                PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_NOTICE,
                                (0, "PVMFMP3FFParserNode::RetrieveTrackData() \
                                 Unknown error code reported err code  %d", error));
            }
            aTrackPortInfo.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_SEND_ENDOFTRACK;
            ReportErrorEvent(errCode);
            return false;
        }
    }
    return true;
}

// Send track data to output port
bool PVMFMP3FFParserNode::SendTrackData(PVMP3FFNodeTrackPortInfo& aTrackPortInfo)
{
    // Send frame to downstream node via port
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                    (0, "PVMFMP3FFParserNode::SendTrackData: SeqNum %d", \
                     aTrackPortInfo.iMediaData->getSeqNum()));

    PVMFSharedMediaMsgPtr mediaMsgOut;
    // Convert media data to media message
    convertToPVMFMediaMsg(mediaMsgOut, aTrackPortInfo.iMediaData);
    // Queue media msg to port's outgoing queue
    PVMFStatus status = aTrackPortInfo.iPort->QueueOutgoingMsg(mediaMsgOut);
    if (status != PVMFSuccess)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                        (0, "PVMFMP3FFParserNode::SendTrackData: Outgoing queue busy"));
        return false;
    }

    //keep count of the number of source frames generated on this port
    aTrackPortInfo.iPort->iNumFramesGenerated++;
    // Don't need reference to iMediaData so unbind it
    aTrackPortInfo.iMediaData.Unbind();
    return true;
}

/**
 * Outgoing port queue handler
 */
bool PVMFMP3FFParserNode::HandleOutgoingQueueReady(PVMFPortInterface* aPortInterface)
{
    if (iTrack.iPort == aPortInterface &&
            iTrack.iState == PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_SENDDATA)
    {
        // Found the element and right state
        // re-send the data
        if (!SendTrackData(iTrack))
        {
            // SendTrackData un-successful
            return false;
        }
        // Success in re-sending the data, change state to getdata
        iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_GETDATA;
        return true;
    }
    // Either the track was not in correct state or the port was not correct
    return false;
}

/**
 * Parse the File
 */
PVMFStatus PVMFMP3FFParserNode::ParseFile(uint32 aClipIndex)
{
    IMpeg3File* parserObj = GetParserObjAtIndex(aClipIndex);
    if (!iSourceURLSet || NULL == parserObj)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                        (0, "PVMFMP3FFParserNode::ParseFile() SourceURL not set"));
        // Can't init the node if the node, File name is not specified yet.
        return PVMFFailure;
    }

    MP3ErrorType mp3Err = parserObj->ParseMp3File();

    if (mp3Err == MP3_INSUFFICIENT_DATA)
    {
        return PVMFPending;
    }
    else if (mp3Err == MP3_END_OF_FILE ||
             mp3Err != MP3_SUCCESS)
    {
        return PVMFFailure;
    }

    // Find out what the largest frame in the file is. This information is used
    // when allocating the buffers in DoRequestPort().
    iMaxFrameSize = parserObj->GetMaxBufferSizeDB();
    if (iMaxFrameSize <= 0)
    {
        iMaxFrameSize = PVMP3FF_DEFAULT_MAX_FRAMESIZE;
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_INFO,
                        (0, "PVMFMP3FFParserNode::ParseFile() Mp3FF \
                         MaxFrameSize %d", iMaxFrameSize));
    }

    // get config Details from mp3ff
    MP3ContentFormatType mp3format;
    iConfigOk = parserObj->GetConfigDetails(mp3format);
    if (!iConfigOk)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_INFO,
                        (0, "PVMFMP3FFParserNode::ParseFile() Mp3FF \
                         Config Not returned", iMaxFrameSize));

    }
    else
    {
        iMP3FormatBitrate = mp3format.Bitrate;
    }
    return PVMFSuccess;
}

/**
 * Reset the trackinfo
 */
void PVMFMP3FFParserNode::ResetTrack()
{
    iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_UNINITIALIZED;
    iTrack.iMediaData.Unbind();
    iTrack.iSeqNum = 0;
    iTrack.timestamp_offset = 0;
    iTrack.iSendBOS = false;
    iTrack.iFirstFrame = false;
    iAutoPaused = false;

    // if this is shoutcast session,
    // reset the stream and read pointers
    if ((GetClipFormatTypeAt(0) == PVMF_MIME_DATA_SOURCE_SHOUTCAST_URL) && (iSCSPFactory != NULL))
    {
        iSCSPFactory->ResetShoutcastStream();
    }
}

/**
 * Release the trackinfo and do necessary cleanup
 */
void PVMFMP3FFParserNode::ReleaseTrack()
{
    //Cleanup allocated ports
    if (iOutPort)
    {
        OSCL_DELETE(iOutPort);
        iOutPort = NULL;
    }

    iTrack.iMediaData.Unbind();

    iTrack.iPort = NULL;

    if (iTrack.iTrackDataMemoryPool != NULL)
    {
        iTrack.iTrackDataMemoryPool->removeRef();
        iTrack.iTrackDataMemoryPool = NULL;
    }

    if (iTrack.iMediaDataImplAlloc != NULL)
    {
        OSCL_DELETE(iTrack.iMediaDataImplAlloc);
        iTrack.iMediaDataImplAlloc = NULL;
    }

    if (iTrack.iMediaDataMemPool != NULL)
    {
        iTrack.iMediaDataMemPool->CancelFreeChunkAvailableCallback();
        iTrack.iMediaDataMemPool->removeRef();
        iTrack.iMediaDataMemPool = NULL;
    }

    if (iTrack.iClockConverter != NULL)
    {
        OSCL_DELETE(iTrack.iClockConverter);
        iTrack.iClockConverter = NULL;
    }
}

/**
 * Cleanup all file sources
 */
void PVMFMP3FFParserNode::CleanupFileSource()
{
    if (iDurationCalcAO)
    {
        if (iDurationCalcAO->IsBusy())
        {
            iDurationCalcAO->Cancel();
        }

        OSCL_DELETE(iDurationCalcAO);
        iDurationCalcAO = NULL;
    }

    while (!iClipInfoList.empty())
    {
        // delete file handle, if any
        PVMFMp3ClipInfo& clipInfo = iClipInfoList.back();
        OsclFileHandle* fileHandle = clipInfo.iClipInfo.GetFileHandle();
        if (fileHandle)
        {
            OSCL_DELETE(fileHandle);
            fileHandle = NULL;
        }

        // delete file parser object, if any
        if (clipInfo.iParserObj)
        {
            bool cleanParserAtLastIndex = true;
            ReleaseMP3FileParser(iClipInfoList.size() - 1, cleanParserAtLastIndex);
        }
        // clear the vector element
        iClipInfoList.pop_back();
    }

    iPlaybackParserObj = NULL;
    iMetadataParserObj = NULL;
    iPlaylistExhausted = false;

    iNumClipsInPlayList = 0;
    iPlaybackClipIndex = -1;
    iClipIndexForMetadata = -1;
    iPlaylistRepositioning = false;
    iNextInitializedClipIndex = -1;
    iInitNextClip = false;

    if (iDataStreamInterface != NULL)
    {
        PVInterface* iFace = OSCL_STATIC_CAST(PVInterface*, iDataStreamInterface);
        PVUuid uuid = PVMIDataStreamSyncInterfaceUuid;

        if (iSCSPFactory != NULL)
        {
            iSCSPFactory->DestroyPVMFCPMPluginAccessInterface(uuid, iFace);
            iSCSP = NULL;
        }
        else
        {
            iDataStreamFactory->DestroyPVMFCPMPluginAccessInterface(uuid, iFace);
        }
        iDataStreamInterface = NULL;
    }

    if (iSCSPFactory != NULL)
    {
        OSCL_DELETE(iSCSPFactory);
        iSCSPFactory = NULL;
    }
    if (iMetadataBuf != NULL)
    {
        oscl_free(iMetadataBuf);
        iMetadataBuf = NULL;
        iMetadataBufSize = 0;
        iMetadataSize = 0;
    }

    if (iDataStreamFactory != NULL)
    {
        iDataStreamFactory->removeRef();
        iDataStreamFactory = NULL;
    }
    iMP3ParserNodeMetadataValueCount = 0;
    iSourceURLSet = false;

    oWaitingOnLicense = false;
    iDownloadComplete = false;
    iUseCPMPluginRegistry = false;
}

/**
 * From OsclMemPoolFixedChunkAllocatorObserver
 * Call back is received when free mem-chunk is available
 */
void PVMFMP3FFParserNode::freechunkavailable(OsclAny*)
{
    if (iTrack.iState == PVMP3FFNodeTrackPortInfo::TRACKSTATE_MEDIADATAPOOLEMPTY)
    {
        iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_GETDATA;
        // Notification is received by node for a free chunk of memory
        // Reschedule the node
        Reschedule();
    }
}

/**
 * From OsclMemPoolResizableAllocatorObserver
 * Call back is received when free mem-block is available
 */
void PVMFMP3FFParserNode::freeblockavailable(OsclAny*)
{
    if (iTrack.iState == PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRACKDATAPOOLEMPTY)
    {
        iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_GETDATA;
        // Notification is received by node for a free block of memory
        // Reschedule the node
        Reschedule();
    }
}


////////////////////////////////////////////////////////////////////////
/**
 * Extension interface implementation
 */
////////////////////////////////////////////////////////////////////////

void PVMFMP3FFParserNode::addRef()
{
    ++iExtensionRefCount;
}

void PVMFMP3FFParserNode::removeRef()
{
    --iExtensionRefCount;
}

PVMFStatus PVMFMP3FFParserNode::QueryInterfaceSync(PVMFSessionId aSession,
        const PVUuid& aUuid,
        PVInterface*& aInterfacePtr)
{
    OSCL_UNUSED_ARG(aSession);
    aInterfacePtr = NULL;
    if (queryInterface(aUuid, aInterfacePtr))
    {
        // PVMFCPMPluginLicenseInterface is not part of this node
        if (aUuid != PVMFCPMPluginLicenseInterfaceUuid)
        {
            aInterfacePtr->addRef();
        }
        return PVMFSuccess;
    }
    return PVMFErrNotSupported;
}

bool PVMFMP3FFParserNode::queryInterface(const PVUuid& uuid, PVInterface*& iface)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "PVMFMP3FFParserNode::queryInterface() In"));

    if (uuid == PVMF_TRACK_SELECTION_INTERFACE_UUID)
    {
        PVMFTrackSelectionExtensionInterface* myInterface = OSCL_STATIC_CAST(PVMFTrackSelectionExtensionInterface*, this);
        iface = OSCL_STATIC_CAST(PVInterface*, myInterface);
    }
    else if (uuid == PVMF_DATA_SOURCE_INIT_INTERFACE_UUID)
    {
        PVMFDataSourceInitializationExtensionInterface* myInterface = OSCL_STATIC_CAST(PVMFDataSourceInitializationExtensionInterface*, this);
        iface = OSCL_STATIC_CAST(PVInterface*, myInterface);
    }
    else if (uuid == KPVMFMetadataExtensionUuid)
    {
        PVMFMetadataExtensionInterface* myInterface = OSCL_STATIC_CAST(PVMFMetadataExtensionInterface*, this);
        iface = OSCL_STATIC_CAST(PVInterface*, myInterface);
    }
    else if (PvmfDataSourcePlaybackControlUuid == uuid)
    {
        PvmfDataSourcePlaybackControlInterface* myInterface = OSCL_STATIC_CAST(PvmfDataSourcePlaybackControlInterface*, this);
        iface = OSCL_STATIC_CAST(PVInterface*, myInterface);
    }
    else if (uuid == PVMFCPMPluginLicenseInterfaceUuid)
    {
        iface = OSCL_STATIC_CAST(PVInterface*, iCPMContainer.iCPMLicenseInterface);
    }
    else if (PVMF_FF_PROGDOWNLOAD_SUPPORT_INTERFACE_UUID == uuid)
    {
        PVMFFormatProgDownloadSupportInterface* myInterface = OSCL_STATIC_CAST(PVMFFormatProgDownloadSupportInterface*, this);
        iface = OSCL_STATIC_CAST(PVInterface*, myInterface);
    }
    else if (PVMIDatastreamuserInterfaceUuid == uuid)
    {
        PVMIDatastreamuserInterface* myInterface = OSCL_STATIC_CAST(PVMIDatastreamuserInterface*, this);
        iface = OSCL_STATIC_CAST(PVInterface*, myInterface);
    }
    else
    {
        return false;
    }
    return true;
}


/**
 * From PVMFDataSourceInitializationExtensionInterface
 */
PVMFStatus PVMFMP3FFParserNode::SetSourceInitializationData(OSCL_wString& aSourceURL,
        PVMFFormatType& aSourceFormat,
        OsclAny* aSourceData,
        uint32 aClipIndex,
        PVMFFormatTypeDRMInfo aType)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_NOTICE, (0, "PVMFMP3FFParserNode::SetSourceInitializationData() In ClipIndex [%d] iPlaybackClipIndex %d", aClipIndex, iPlaybackClipIndex));

    // updates cant be accepted for currently playing back clip
    if ((int32)aClipIndex == iPlaybackClipIndex)
        return PVMFErrAlreadyExists;

    PVMFMp3ClipInfo mp3clipInfo;
    // initiliaze parser object as null
    mp3clipInfo.iParserObj = NULL;

    PVMFSourceClipInfo info;
    bool updateExistingClip = false;
    // if the clip was already initialized no updates can be excepted
    // for this .
    // if there were no updates in existing data, treat this as no-op success
    // else update the existing clip info data.
    uint32 index = 0;
    for (index = 0; index < iClipInfoList.size(); index++)
    {
        if (iClipInfoList[index].iClipInfo.GetClipIndex() == aClipIndex)
        {
            if (iClipInfoList[index].iClipInfo.iIsInitialized)
            {
                if (false == ValidateSourceInitializationParams(aSourceURL, aSourceFormat, aClipIndex, iClipInfoList[index].iClipInfo))
                {
                    // clip is already initialized, updates cant be accepted now.
                    return PVMFErrAlreadyExists;
                }
                // this would mean that we there was no update for this track hence mark it as a no-op
                return PVMFSuccess;
            }
            updateExistingClip = true;
            break;
        }
    }

    // intialize clip info
    info.SetSourceURL(aSourceURL);
    info.SetClipIndex(aClipIndex);
    info.SetFormatType(aSourceFormat);
    info.SetFileHandle(NULL); //initialize file handle

    if (iPlaybackClipIndex == -1 && aClipIndex == 0)
    {
        // either information is recieved for the first time for zeroth index
        // of zeroth index is being updated again first same index is being updated
        CleanupFileSource();
    }

    // check for protected content here, after CleanupFileSource()
    if (aType != PVMF_FORMAT_TYPE_CONNECT_UNPROTECTED)
    {
        iUseCPMPluginRegistry = true;
    }
    else
    {
        iUseCPMPluginRegistry = false;
    }

    if (aClipIndex == 0)
    {
        // check if earlier mime type was correct, if it was, ignore this update
        if (aSourceFormat == PVMF_MIME_FORMAT_UNKNOWN &&
                iClipInfoList[index].iClipInfo.GetFormatType() == PVMF_MIME_MP3FF)
        {
            // same url is being updated, dont update the format type.
            info.SetFormatType(iClipInfoList[index].iClipInfo.GetFormatType());
        }
        else
        {
            // for clip index == 0 only mp3 and shoutcast url mime types are
            // supported by this node
            if (aSourceFormat != PVMF_MIME_MP3FF &&
                    aSourceFormat != PVMF_MIME_DATA_SOURCE_SHOUTCAST_URL)
            {
                // Node doesnt support any other format than MP3/Shoutcast stream
                return PVMFErrNotSupported;
            }
        }
    }
    else
    {
        // for clip index > 0 only mp3 and unknown mime types are supported by this node
        if (aSourceFormat != PVMF_MIME_MP3FF &&
                aSourceFormat != PVMF_MIME_FORMAT_UNKNOWN)
        {
            return PVMFErrNotSupported;
        }
    }

    iSourceURLSet = true;

    if (aSourceData)
    {
        PVInterface* pvInterface = OSCL_STATIC_CAST(PVInterface*, aSourceData);
        PVInterface* localDataSrc = NULL;
        PVUuid localDataSrcUuid(PVMF_LOCAL_DATASOURCE_UUID);
        // Check if it is a local file
        if (pvInterface->queryInterface(localDataSrcUuid, localDataSrc))
        {
            PVMFLocalDataSource* opaqueData = OSCL_STATIC_CAST(PVMFLocalDataSource*, localDataSrc);
            if (opaqueData->iFileHandle)
            {
                OsclFileHandle* fileHandle = PVMF_BASE_NODE_NEW(OsclFileHandle, (*(opaqueData->iFileHandle)));
                info.SetFileHandle(fileHandle);
                info.iCPMSourceData.iFileHandle = fileHandle;
            }
            info.iCPMSourceData.iPreviewMode = opaqueData->iPreviewMode;
            info.iCPMSourceData.iIntent = opaqueData->iIntent;
            if (opaqueData->iContentAccessFactory != NULL)
            {
                //Cannot have both plugin usage and a datastream factory
                return PVMFErrArgument;
            }
        }
        else
        {
            PVInterface* sourceDataContext = NULL;
            PVInterface* commonDataContext = NULL;
            PVUuid sourceContextUuid(PVMF_SOURCE_CONTEXT_DATA_UUID);
            PVUuid commonContextUuid(PVMF_SOURCE_CONTEXT_DATA_COMMON_UUID);
            if (pvInterface->queryInterface(sourceContextUuid, sourceDataContext))
            {
                if (sourceDataContext->queryInterface(commonContextUuid, commonDataContext))
                {
                    PVMFSourceContextDataCommon* cContext = OSCL_STATIC_CAST(
                                                                PVMFSourceContextDataCommon*,
                                                                commonDataContext);
                    OsclFileHandle* fileHandle = NULL;
                    if (cContext->iFileHandle)
                    {
                        fileHandle = PVMF_BASE_NODE_NEW(OsclFileHandle, (*(cContext->iFileHandle)));
                    }
                    info.SetFileHandle(fileHandle);
                    if (cContext->iContentAccessFactory != NULL)
                    {
                        //Cannot have both plugin usage and a datastream factory
                        return PVMFErrArgument;
                    }

                    PVMFSourceContextData* sContext = OSCL_STATIC_CAST(
                                                          PVMFSourceContextData*,
                                                          sourceDataContext);

                    info.iSourceContextData = *sContext;
                    info.iSourceContextDataValid = true;
                }
            }
        }
    }
    if (updateExistingClip)
    {
        iClipInfoList[aClipIndex].iClipInfo = info;
    }
    else
    {
        mp3clipInfo.iClipInfo = info;
        iClipInfoList.push_back(mp3clipInfo);
        iNumClipsInPlayList++;
    }

    // this is a new clip addition request but the existing clip list has exhausted
    // need to wake up source node.
    if (!updateExistingClip && iPlaylistExhausted)
    {
        if (iInterfaceState == EPVMFNodeStarted &&
                PVMFSuccess == InitNextValidClipInPlaylist(aClipIndex))
        {
            iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_GETDATA;
            iPlaybackClipIndex = iNextInitializedClipIndex;
            iPlaybackParserObj = GetParserObjAtIndex(iNextInitializedClipIndex);
            iPlaylistExhausted = false;
            iTrack.iSendBOS = true;
            uint32 timestamp = iTrack.iClockConverter->get_converted_ts(COMMON_PLAYBACK_CLOCK_TIMESCALE);
            iTrack.timestamp_offset += timestamp;
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_NOTICE, (0, "PVMFMP3FFParserNode::HandleTrackState() TimeStampOffset [%d]", iTrack.timestamp_offset));
            iTrack.iClockConverter->set_clock((uint32)0, (uint32)0);
            RunIfNotReady();
            return PVMFSuccess;
        }
        return PVMFFailure;
    }

    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_NOTICE, (0, "PVMFMP3FFParserNode::SetSourceInitializationData() Out ClipIndex [%d]", aClipIndex));
    return PVMFSuccess;
}

PVMFStatus PVMFMP3FFParserNode::SetClientPlayBackClock(PVMFMediaClock* aClientClock)
{
    OSCL_UNUSED_ARG(aClientClock);
    return PVMFSuccess;
}

PVMFStatus PVMFMP3FFParserNode::SetEstimatedServerClock(PVMFMediaClock* aClientClock)
{
    OSCL_UNUSED_ARG(aClientClock);
    return PVMFSuccess;
}

void PVMFMP3FFParserNode::AudioSinkEvent(PVMFStatus aEvent, uint32 aClipIndex)
{
    if (aEvent == PVMFInfoEndOfData)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                        (0, "PVMFMP3FFParserNode::AudioSinkEvent() EOS ClipIndex %d", aClipIndex));
        if ((int32)aClipIndex == iLastPlayingClipIndex)
        {
            iLastPlayingClipIndex = -1;
        }
        ReleaseMP3FileParser(aClipIndex);
    }
    else if (aEvent == PVMFInfoStartOfData)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                        (0, "PVMFMP3FFParserNode::AudioSinkEvent() BOS ClipIndex %d", aClipIndex));
        iLastPlayingClipIndex = aClipIndex;
    }
    else
    {
        // unknown event, log it
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                        (0, "PVMFMP3FFParserNode::AudioSinkEvent() unknown event %d ClipIndex %d", aEvent, aClipIndex));
    }
}

/**
 * From PVMFTrackSelectionExtensionInterface
 */
PVMFStatus PVMFMP3FFParserNode::GetMediaPresentationInfo(PVMFMediaPresentationInfo& aInfo)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::GetMediaPresentationInfo() In"));

    if (NULL == iPlaybackParserObj || iPlaybackClipIndex == -1)
    {
        // start playback from last playing back clip
        iPlaylistExhausted = true;
        PVMFStatus status = InitNextValidClipInPlaylist(iPlaybackClipIndex);
        iPlaybackParserObj = GetParserObjAtIndex(iPlaybackClipIndex);
        if (status != PVMFSuccess)
            return status;
    }

    aInfo.setDurationValue(iPlaybackParserObj->GetDuration());
    int32 iNumTracks = iPlaybackParserObj->GetNumTracks();

    if (iNumTracks <= 0)
    {
        // Number of tracks is null
        return PVMFFailure;
    }

    int32 id;
    for (id = 0; id < iNumTracks; id++)
    {
        PVMFTrackInfo tmpTrackInfo;
        // set the port tag for this track
        tmpTrackInfo.setPortTag(PVMF_MP3FFPARSER_NODE_PORT_TYPE_SOURCE);
        // track id
        tmpTrackInfo.setTrackID(0);
        // bitrate
        uint32 aBitRate = 0;
        if (iConfigOk)
        {
            aBitRate = iMP3FormatBitrate;
        }
        tmpTrackInfo.setTrackBitRate(aBitRate);
        // config info
        MP3ContentFormatType mp3Config;
        if (!iPlaybackParserObj->GetConfigDetails(mp3Config))
        {
            // mp3 config not available
            return PVMFFailure;
        }
        if (!CreateFormatSpecificInfo(mp3Config.NumberOfChannels, mp3Config.SamplingRate))
        {
            return PVMFFailure;
        }

        tmpTrackInfo.setTrackConfigInfo(iDecodeFormatSpecificInfo);
        // timescale
        uint64 timescale = (uint64)iPlaybackParserObj->GetTimescale();
        tmpTrackInfo.setTrackDurationTimeScale(timescale);
        // in movie timescale
        uint32 trackDuration = iPlaybackParserObj->GetDuration();
        tmpTrackInfo.setTrackDurationValue(trackDuration);
        // mime type
        OSCL_FastString mime_type = _STRLIT_CHAR(PVMF_MIME_MP3);
        tmpTrackInfo.setTrackMimeType(mime_type);
        // add the track
        aInfo.addTrackInfo(tmpTrackInfo);
    }
    return PVMFSuccess;
}

bool PVMFMP3FFParserNode::CreateFormatSpecificInfo(uint32 numChannels, uint32 samplingRate)
{
    // Allocate memory for decode specific info and ref counter
    OsclMemoryFragment frag;
    frag.ptr = NULL;
    frag.len = sizeof(channelSampleInfo);
    uint refCounterSize = oscl_mem_aligned_size(sizeof(OsclRefCounterDA));
    uint8* memBuffer = (uint8*)iDecodeFormatSpecificInfoAlloc.ALLOCATE(refCounterSize + frag.len);
    if (!memBuffer)
    {
        // failure while allocating memory buffer
        return false;
    }

    oscl_memset(memBuffer, 0, refCounterSize + frag.len);
    // Create ref counter
    OsclRefCounter* refCounter = OSCL_PLACEMENT_NEW(memBuffer, OsclRefCounterDA(memBuffer,
                                 (OsclDestructDealloc*) & iDecodeFormatSpecificInfoAlloc));
    memBuffer += refCounterSize;
    // Create channel sample info
    frag.ptr = (OsclAny*)(OSCL_PLACEMENT_NEW(memBuffer, channelSampleInfo));
    ((channelSampleInfo*)frag.ptr)->desiredChannels = numChannels;
    ((channelSampleInfo*)frag.ptr)->samplingRate = samplingRate;

    // Store info in a ref counter memfrag
    iDecodeFormatSpecificInfo = OsclRefCounterMemFrag(frag, refCounter,
                                sizeof(struct channelSampleInfo));
    return true;
}

PVMFStatus PVMFMP3FFParserNode::SelectTracks(PVMFMediaPresentationInfo& aInfo)
{
    OSCL_UNUSED_ARG(aInfo);
    return PVMFSuccess;
}

// From PVMFMetadataExtensionInterface
uint32 PVMFMP3FFParserNode::GetNumMetadataValues(PVMFMetadataList& aKeyList)
{
    uint32 numvalentries = 0;
    if (NULL == iMetadataParserObj)
    {
        return numvalentries;
    }
    PVMFMetadataList mp3parserKeyList;

    if (iCPMContainer.iCPMMetaDataExtensionInterface != NULL)
    {
        numvalentries =
            iCPMContainer.iCPMMetaDataExtensionInterface->GetNumMetadataValues(aKeyList);
    }

    PVMFMetadataList* keylistptr = &aKeyList;
    if (aKeyList.size() == 1)
    {
        if (oscl_strncmp(aKeyList[0].get_cstr(),
                         PVMF_MP3_PARSER_NODE_ALL_METADATA_KEY,
                         oscl_strlen(PVMF_MP3_PARSER_NODE_ALL_METADATA_KEY)) == 0)
        {
            //check if the user passed in "all" metadata key, in which case get the complete
            //key list from MP3 FF lib first
            int32 max = 0x7FFFFFFF;
            char* query = NULL;
            iMetadataParserObj->GetMetadataKeys(mp3parserKeyList, 0, max, query);
            keylistptr = &mp3parserKeyList;
        }
    }
    numvalentries += iMetadataParserObj->GetNumMetadataValues(*keylistptr);

    return numvalentries;
}

/**
 * From PVMFMetadataExtensionInterface
 * Set metadata clip index
 */
PVMFStatus PVMFMP3FFParserNode::SetMetadataClipIndex(uint32 aClipNum)
{
    iClipIndexForMetadata = aClipNum;
    iMetadataParserObj = GetParserObjAtIndex(aClipNum);
    if (iMetadataParserObj)
        return PVMFSuccess;
    iMetadataParserObj = NULL;
    return PVMFFailure;
}

/**
 * From PVMFMetadataExtensionInterface
 * Queue an asynchronous node command for GetNodeMetadataValues
 */
PVMFCommandId PVMFMP3FFParserNode::GetNodeMetadataValues(PVMFSessionId aSessionId,
        PVMFMetadataList& aKeyList,
        Oscl_Vector<PvmiKvp, OsclMemAllocator>& aValueList,
        uint32 starting_index,
        int32 max_entries,
        const OsclAny* aContext)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::GetNodeMetadataValues() In"));

    PVMFNodeCommand cmd;
    cmd.PVMFNodeCommand::Construct(aSessionId,
                                   PVMF_GENERIC_NODE_GETNODEMETADATAVALUES,
                                   aKeyList, aValueList,
                                   starting_index, max_entries,
                                   aContext);
    return QueueCommandL(cmd);
}

/**
 * From PVMFMetadataExtensionInterface
 * Queue an asynchronous node command for ReleaseNodeMetadataValues
 */
PVMFStatus PVMFMP3FFParserNode::ReleaseNodeMetadataValues(Oscl_Vector<PvmiKvp, OsclMemAllocator>& aValueList,
        uint32 start, uint32 end)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "PVMFMP3FFParserNode::ReleaseNodeMetadataValues() In"));
    if (!iMetadataParserObj)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR,
                        (0, "PVMFMP3FFParserNode::ReleaseNodeMetadataValues() \
                         Invalid parser object"));
        return PVMFFailure;
    }

    if (iCPMContainer.iCPMMetaDataExtensionInterface != NULL)
    {
        PVMFStatus status = iCPMContainer.iCPMMetaDataExtensionInterface->ReleaseNodeMetadataValues(aValueList, start, end);
        if (status != PVMFSuccess)
        {
            return status;
        }
    }

    end = OSCL_MIN(aValueList.size(), iMP3ParserNodeMetadataValueCount);

    if (start > end || aValueList.size() == 0)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR,
                        (0, "PVMFMP3FFParserNode::ReleaseNodeMetadataValues() \
                         Invalid start/end index"));
        return PVMFErrArgument;
    }

    // Go through the specified values and free it
    for (uint32 i = start; i < end; i++)
    {
        iMetadataParserObj->ReleaseMetadataValue(aValueList[i]);
    }
    return PVMFSuccess;
}

/**
 * From PvmfDataSourcePlaybackControlInterface
 * Queue an asynchronous node command for SetDataSourcePosition
 */
PVMFCommandId PVMFMP3FFParserNode::SetDataSourcePosition(PVMFSessionId aSessionId,
        PVMFTimestamp aTargetNPT,
        PVMFTimestamp& aActualNPT,
        PVMFTimestamp& aActualMediaDataTS,
        bool aSeekToSyncPoint,
        uint32 aStreamID,
        OsclAny* aContext)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::SetDataSourcePosition()"));
    PVMFNodeCommand cmd;
    cmd.PVMFNodeCommand::Construct(aSessionId,
                                   PVMF_GENERIC_NODE_SET_DATASOURCE_POSITION,
                                   aTargetNPT, &aActualNPT,
                                   &aActualMediaDataTS, aSeekToSyncPoint,
                                   aStreamID, aContext);
    return QueueCommandL(cmd);
}

/**
 * From PvmfDataSourcePlaybackControlInterface
 * Queue an asynchronous node command for SetDataSourcePosition
 */
PVMFCommandId PVMFMP3FFParserNode::SetDataSourcePosition(PVMFSessionId aSessionId,
        PVMFDataSourcePositionParams& aPVMFDataSourcePositionParams,
        OsclAny* aContext)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::SetDataSourcePosition()"));
    PVMFNodeCommand cmd;
    cmd.PVMFNodeCommand::Construct(aSessionId,
                                   PVMF_GENERIC_NODE_SET_DATASOURCE_POSITION,
                                   &aPVMFDataSourcePositionParams, aContext);

    iPlaylistRepositioning = true;
    return QueueCommandL(cmd);

}

/**
 * From PvmfDataSourcePlaybackControlInterface
 * Queue an asynchronous node command for QueryDataSourcePosition
 */
PVMFCommandId PVMFMP3FFParserNode::QueryDataSourcePosition(PVMFSessionId aSessionId,
        PVMFTimestamp aTargetNPT,
        PVMFTimestamp& aActualNPT,
        bool aSeekToSyncPoint,
        OsclAny* aContext)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::QueryDataSourcePosition()"));
    PVMFNodeCommand cmd;
    cmd.PVMFNodeCommand::Construct(aSessionId,
                                   PVMF_GENERIC_NODE_QUERY_DATASOURCE_POSITION,
                                   aTargetNPT, &aActualNPT,
                                   aSeekToSyncPoint, aContext);
    return QueueCommandL(cmd);
}

/**
 * From PvmfDataSourcePlaybackControlInterface
 * Queue an asynchronous node command for QueryDataSourcePosition
 */
PVMFCommandId PVMFMP3FFParserNode::QueryDataSourcePosition(PVMFSessionId aSessionId,
        PVMFTimestamp aTargetNPT,
        PVMFTimestamp& aSeekPointBeforeTargetNPT,
        PVMFTimestamp& aSeekPointAfterTargetNPT,
        OsclAny* aContextData,
        bool aSeekToSyncPoint)
{
    OSCL_UNUSED_ARG(aSeekPointAfterTargetNPT);
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::QueryDataSourcePosition()"));
    PVMFNodeCommand cmd;
    // Construct call is not changed, the aSeekPointBeforeTargetNPT will
    // contain the replaced actualNPT
    cmd.PVMFNodeCommand::Construct(aSessionId,
                                   PVMF_GENERIC_NODE_QUERY_DATASOURCE_POSITION,
                                   aTargetNPT, &aSeekPointBeforeTargetNPT,
                                   aSeekToSyncPoint, aContextData);
    return QueueCommandL(cmd);
}

/**
 * From PvmfDataSourcePlaybackControlInterface
 * Queue an asynchronous node command for SetDataSourceRate
 */
PVMFCommandId PVMFMP3FFParserNode::SetDataSourceRate(PVMFSessionId aSessionId,
        int32 aRate,
        PVMFTimebase* aTimebase,
        OsclAny* aContext)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::SetDataSourceRate()"));
    PVMFNodeCommand cmd;
    cmd.PVMFNodeCommand::Construct(aSessionId,
                                   PVMF_GENERIC_NODE_SET_DATASOURCE_RATE,
                                   aRate, aTimebase,
                                   aContext);
    return QueueCommandL(cmd);
}

/**
 * Command Handler for SetDataSourceRate
 */
PVMFStatus PVMFMP3FFParserNode::DoSetDataSourceRate()
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::DoSetDataSourceRate() In"));

    return PVMFSuccess;
}

/**
 * Command Handler for SetDataSourcePosition
 */
PVMFStatus PVMFMP3FFParserNode::DoSetDataSourcePosition()
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "PVMFMP3FFParserNode::DoSetDataSourcePosition() In CurrentClipIndex %d", iPlaybackClipIndex));
    uint32 targetNPT = 0;
    uint32* actualNPT = NULL;
    uint32* actualMediaDataTS = NULL;
    bool seektosyncpoint = false;
    uint32 streamID = 0;
    int32 reposIndex = 0;
    int32 lastPlayingIndex = -1;

    if (iLastPlayingClipIndex >= 0)
    {
        lastPlayingIndex = iLastPlayingClipIndex;
    }
    else
    {
        lastPlayingIndex = iPlaybackClipIndex;
    }

    // check for availability of clip index in the clip list.
    for (uint32 index = 0; index < iClipInfoList.size(); index++)
    {
        if (lastPlayingIndex == (int32) iClipInfoList[index].iClipInfo.GetClipIndex())
        {
            reposIndex = (int32) index;
            break;
        }
    }

    iCurrentCommand.PVMFNodeCommand::Parse(targetNPT, actualNPT,
                                           actualMediaDataTS, seektosyncpoint,
                                           streamID);

    PVMFStatus status = SetPlaybackStartupTime(targetNPT, actualNPT, actualMediaDataTS, seektosyncpoint, streamID, reposIndex);
    if (status == PVMFSuccess)
    {
        iPlaybackClipIndex = lastPlayingIndex;
        iPlaybackParserObj = GetParserObjAtIndex(reposIndex);
    }

    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "PVMFMP3FFParserNode::DoSetDataSourcePosition() Out Status %d", status));
    return status;
}

/**
 * Command Handler for SetDataSourcePosition
 */
PVMFStatus PVMFMP3FFParserNode::DoSetDataSourcePositionPlaylist()
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR, (0, "PVMFMP3FFParserNode::DoSetDataSourcePositionPlaylist() In"));

    PVMFDataSourcePositionParams* aReposParams;
    uint32 targetNPT = 0;
    uint32 *actualNPT = NULL;
    uint32 *actualMediaDataTS = NULL;
    bool seekToSyncPoint = false;
    uint32 streamID = 0;
    int32 reposIndex = -1;
    iMetadataParserObj = NULL;

    iPlaylistExhausted = false;

    iCurrentCommand.PVMFNodeCommand::Parse(aReposParams);

    // check for availability of clip index in the clip list.
    for (uint32 index = 0; index < iClipInfoList.size(); index++)
    {
        if (aReposParams->iPlayElementIndex == (int32) iClipInfoList[index].iClipInfo.GetClipIndex())
        {
            reposIndex = (int32) index;
            break;
        }
    }

    // reposition index wasnt found in the list.
    if (reposIndex < 0)
    {
        return PVMFErrArgument;
    }

    iTrack.iSendBOS = true;
    iTrack.iFirstFrame = true;
    streamID = aReposParams->iStreamID;
    seekToSyncPoint = aReposParams->iSeekToSyncPoint;
    targetNPT = aReposParams->iTargetNPT; // target npt in msec
    actualMediaDataTS = &aReposParams->iActualMediaDataTS;
    actualNPT = &aReposParams->iActualNPT;

    PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR, (0, "PVMFMP3FFParserNode::DoSetDataSourcePositionPlaylist() ClipIndex[%d]", aReposParams->iPlayElementIndex));

    PVMFStatus status = PVMFSuccess;
    // reposition is causing track skipping
    // release currently used mp3 parser object
    if (iPlaybackClipIndex != reposIndex &&
            NULL != iPlaybackParserObj)
    {
        // release preexisting parser objects
        for (uint32 index = 0; index < iClipInfoList.size(); index++)
        {
            ReleaseMP3FileParser(index);
        }

        status = InitNextValidClipInPlaylist(reposIndex);

        if (PVMFSuccess != status)
        {
            iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_SEND_ENDOFTRACK;
            iPlaybackClipIndex = iNumClipsInPlayList;
            Reschedule();
            PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR, (0, "PVMFMP3FFParserNode::DoSetDataSourcePositionPlaylist() Failed Status [%d]", status));
            return status;
        }
        else
        {
            reposIndex = iNextInitializedClipIndex;
        }
    }

    status = SetPlaybackStartupTime(targetNPT, actualNPT, actualMediaDataTS, seekToSyncPoint, streamID, reposIndex);
    if (status == PVMFSuccess)
    {
        // update playback clip index, as clip to which skip was issued might be corrupt.
        iPlaybackClipIndex = reposIndex;
        iPlaybackParserObj = GetParserObjAtIndex(reposIndex);
    }

    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "PVMFMP3FFParserNode::DoSetDataSourcePositionPlaylist() Out Status %d", status));
    return status;
}

PVMFStatus PVMFMP3FFParserNode::SetPlaybackStartupTime(uint32& aTargetNPT,
        uint32* aActualNPT,
        uint32* aActualMediaDataTS,
        bool aSeektosyncpoint,
        uint32 aStreamID,
        int32 reposIndex)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "PVMFMP3FFParserNode::SetPlaybackStartupTimeStamp() In"));

    IMpeg3File* parserObj = GetParserObjAtIndex(reposIndex);
    if (NULL == parserObj)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "PVMFMP3FFParserNode::SetPlaybackStartupTimeStamp() Failed, Parser not created!"));
        return PVMFFailure;
    }
    // if progressive streaming, reset download complete flag
    if ((NULL != iDataStreamInterface) && (0 != iDataStreamInterface->QueryBufferingCapacity()))
    {
        iDownloadComplete = false;
    }

    /* In PPB, Seek is not permitted in case when byte-seek is not supported. */
    if ((aTargetNPT != 0) && (iDataStreamInterface != NULL))
    {
        if ((iDataStreamInterface->QueryBufferingCapacity() != 0)
                && (iIsByteSeekNotSupported == true))
        {
            if (iInterfaceState == EPVMFNodePrepared)
            {
                /*This means engine is trying to start the playback session at a non-zero NPT.
                In case of PPB, this is not possible if server does not support byte-seek. */
                return PVMFFailure;
            }
            else
            {
                return PVMFErrNotSupported;
            }
        }
    }

    iStreamID = aStreamID;
    iTrack.iSendBOS = true;
    iTrack.iFirstFrame = true;

    if (iDownloadProgressClock.GetRep())
    {
        // Get the amount downloaded so far
        bool tmpbool = false;
        uint32 dltime = 0;
        iDownloadProgressClock->GetCurrentTime32(dltime, tmpbool, PVMF_MEDIA_CLOCK_MSEC);
        // Check if the requested time is past the downloaded clip
        if (aTargetNPT >= dltime)
        {
            // For now, fail in this case. In future, we want to reposition to valid location.
            PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR,
                            (0, "PVMFMP3FFParserNode::SetPlaybackStartupTimeStamp() \
                             Positioning past the amount downloaded so return as \
                             argument error"));
            return PVMFErrArgument;
        }
    }
    // get the clock offset
    iTrack.iClockConverter->update_clock(parserObj->GetTimestampForCurrentSample());
    iTrack.timestamp_offset += iTrack.iClockConverter->get_converted_ts(COMMON_PLAYBACK_CLOCK_TIMESCALE);
    // Set the timestamp
    *aActualMediaDataTS = iTrack.timestamp_offset;
    // See if targetNPT is greater or equal to clip duration
    uint32 duration = parserObj->GetDuration();
    if (duration > 0 && aTargetNPT >= duration)
    {
        // report End of Stream on the track and reset the track to zero.
        iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_SEND_ENDOFTRACK;
        parserObj->SeekToTimestamp(0);
        *aActualNPT = duration;

        PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR,
                        (0, "PVMFMP3FFParserNode::SetPlaybackStartupTimeStamp: targetNPT=%d, actualNPT=%d, actualMediaTS=%d",
                         aTargetNPT, *aActualNPT, *aActualMediaDataTS));
        if (iAutoPaused)
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR, (0, "PVMFMP3FFParserNode::SetPlaybackStartupTimeStamp Track Autopaused"));
            iAutoPaused = false;
            if (iDownloadProgressInterface != NULL)
            {
                iDownloadProgressInterface->cancelResumeNotification();
            }
        }
        return PVMFSuccess;
    }
    // Seek to the next NPT
    // MP3 FF seeks to the beginning if the requested time is past the end of clip
    *aActualNPT = parserObj->SeekToTimestamp(aTargetNPT);
    if (duration > 0 && *aActualNPT == duration)
    {
        // this means there was no data to render after the seek so just send End of Track
        iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_SEND_ENDOFTRACK;
        return PVMFSuccess;
    }

    iTrack.iClockConverter->set_clock_other_timescale(*aActualNPT, COMMON_PLAYBACK_CLOCK_TIMESCALE);
    iTrack.timestamp_offset -= *aActualNPT;

    // Reposition has occured, so reset the track state
    if (iAutoPaused)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR, (0, "PVMFMP3FFParserNode::SetPlaybackStartupTimeStamp Track Autopaused"));
        iAutoPaused = false;
        if (iDownloadProgressInterface != NULL)
        {
            iDownloadProgressInterface->cancelResumeNotification();
        }
    }
    iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_GETDATA;

    PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::SetPlaybackStartupTimeStamp: targetNPT=%d, actualNPT=%d, actualMediaTS=%d",
                     aTargetNPT, *aActualNPT, *aActualMediaDataTS));
    return PVMFSuccess;
}

/**
 * Command Handler for QueryDataSourcePosition
 */
PVMFStatus PVMFMP3FFParserNode::DoQueryDataSourcePosition()
{
    uint32 targetNPT = 0;
    uint32* actualNPT = NULL;
    bool seektosyncpoint = false;

    iCurrentCommand.PVMFNodeCommand::Parse(targetNPT, actualNPT, seektosyncpoint);
    if (NULL == actualNPT || NULL == iPlaybackParserObj)
    {
        return PVMFErrArgument;
    }
    // First check if MP3 file is being PDed to make sure the requested
    // position is before amount downloaded
    if (iDownloadProgressClock.GetRep())
    {
        // Get the amount downloaded so far
        bool tmpbool = false;
        uint32 dltime = 0;
        iDownloadProgressClock->GetCurrentTime32(dltime, tmpbool, PVMF_MEDIA_CLOCK_MSEC);
        // Check if the requested time is past clip dl
        if (targetNPT >= dltime)
        {
            return PVMFErrArgument;
        }
    }
    // Determine the actual NPT without actually repositioning
    // MP3 FF goes to the beginning if the requested time is past the end of clip
    *actualNPT = targetNPT;
    uint32 duration = iPlaybackParserObj->GetDuration();
    if (duration > 0 && targetNPT >= duration)
    {
        // return without any call on parser library.
        return PVMFSuccess;
    }
    iPlaybackParserObj->SeekPointFromTimestamp(*actualNPT);
    return PVMFSuccess;
}

/**
 * Queues SubNode Commands
 */
void PVMFMP3FFParserNode::Push(PVMFSubNodeContainerBaseMp3& c, PVMFSubNodeContainerBaseMp3::CmdType cmd)
{
    SubNodeCmd snc;
    snc.iSubNodeContainer = &c;
    snc.iCmd = cmd;
    iSubNodeCmdVec.push_back(snc);
}

PVMFCommandId PVMFCPMContainerMp3::GetCPMLicenseInterface()
{
    iCPMLicenseInterfacePVI = NULL;
    return (iCPM->QueryInterface(iSessionId,
                                 PVMFCPMPluginLicenseInterfaceUuid,
                                 iCPMLicenseInterfacePVI));
}


PVMFStatus PVMFCPMContainerMp3::CheckApprovedUsage()
{
    //compare the approved and requested usage bitmaps
    if ((iApprovedUsage.value.uint32_value & iRequestedUsage.value.uint32_value)
            != iRequestedUsage.value.uint32_value)
    {
        return PVMFErrAccessDenied;//media access denied by CPM.
    }
    return PVMFSuccess;
}

PVMFStatus PVMFCPMContainerMp3::CreateUsageKeys()
{
    iCPMContentType = iCPM->GetCPMContentType(iSessionId);
    if ((iCPMContentType != PVMF_CPM_FORMAT_OMA1) &&
            (iCPMContentType != PVMF_CPM_FORMAT_AUTHORIZE_BEFORE_ACCESS))
    {
        return PVMFFailure;//invalid content type.
    }

    //cleanup any old usage keys
    CleanUsageKeys();

    int32 UseKeyLen = oscl_strlen(_STRLIT_CHAR(PVMF_CPM_REQUEST_USE_KEY_STRING));
    int32 AuthKeyLen = oscl_strlen(_STRLIT_CHAR(PVMF_CPM_AUTHORIZATION_DATA_KEY_STRING));
    int32 leavecode = 0;

    OSCL_TRY(leavecode,
             iRequestedUsage.key = OSCL_ARRAY_NEW(char, UseKeyLen + 1);
             iApprovedUsage.key = OSCL_ARRAY_NEW(char, UseKeyLen + 1);
             iAuthorizationDataKvp.key = OSCL_ARRAY_NEW(char, AuthKeyLen + 1);
            );

    if (leavecode || !iRequestedUsage.key || !iApprovedUsage.key || !iAuthorizationDataKvp.key)
    {
        // Leave occured, do neccessary cleanup
        CleanUsageKeys();
        return PVMFErrNoMemory;
    }

    oscl_strncpy(iRequestedUsage.key, PVMF_CPM_REQUEST_USE_KEY_STRING, UseKeyLen);
    iRequestedUsage.key[UseKeyLen] = 0;
    iRequestedUsage.length = 0;
    iRequestedUsage.capacity = 0;
    iRequestedUsage.value.uint32_value =
        (BITMASK_PVMF_CPM_DRM_INTENT_PLAY |
         BITMASK_PVMF_CPM_DRM_INTENT_PAUSE |
         BITMASK_PVMF_CPM_DRM_INTENT_SEEK_FORWARD |
         BITMASK_PVMF_CPM_DRM_INTENT_SEEK_BACK);

    oscl_strncpy(iApprovedUsage.key, PVMF_CPM_REQUEST_USE_KEY_STRING, UseKeyLen);
    iApprovedUsage.key[UseKeyLen] = 0;
    iApprovedUsage.length = 0;
    iApprovedUsage.capacity = 0;
    iApprovedUsage.value.uint32_value = 0;

    oscl_strncpy(iAuthorizationDataKvp.key, _STRLIT_CHAR(PVMF_CPM_AUTHORIZATION_DATA_KEY_STRING),
                 AuthKeyLen);
    iAuthorizationDataKvp.key[AuthKeyLen] = 0;

    if ((iCPMContentType == PVMF_CPM_FORMAT_OMA1) ||
            (iCPMContentType == PVMF_CPM_FORMAT_AUTHORIZE_BEFORE_ACCESS))
    {
        iAuthorizationDataKvp.length = 0;
        iAuthorizationDataKvp.capacity = 0;
        iAuthorizationDataKvp.value.pUint8_value = NULL;
    }
    else
    {
        CleanUsageKeys();
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                        (0, "PVMFCPMContainerMp3::CreateUsageKeys Usage key creation failed"));
        return PVMFFailure;
    }
    return PVMFSuccess;
}

void PVMFCPMContainerMp3::CleanUsageKeys()
{
    //cleanup usage keys

    if (iRequestedUsage.key)
    {
        OSCL_ARRAY_DELETE(iRequestedUsage.key);
        iRequestedUsage.key = NULL;
    }

    if (iApprovedUsage.key)
    {
        OSCL_ARRAY_DELETE(iApprovedUsage.key);
        iApprovedUsage.key = NULL;
    }

    if (iAuthorizationDataKvp.key)
    {
        OSCL_ARRAY_DELETE(iAuthorizationDataKvp.key);
        iAuthorizationDataKvp.key = NULL;
    }
}

void PVMFCPMContainerMp3::Cleanup()
{
    //cleanup usage keys
    CleanUsageKeys();

    //cleanup cpm access
    if (iCPMContentAccessFactory)
    {
        iCPMContentAccessFactory->removeRef();
        iCPMContentAccessFactory = NULL;
    }


    //cleanup CPM object.
    if (iCPM)
    {
        iCPM->ThreadLogoff();
        PVMFCPMFactory::DestroyContentPolicyManager(iCPM);
        iCPM = NULL;
    }
}

PVMFStatus PVMFCPMContainerMp3::IssueCommand(int32 aCmd)
{
    // Issue a command to the sub-node.
    // Return the sub-node completion status: either pending, success, or failure.
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFCPMContainerMp3::IssueCommand In"));

    OSCL_ASSERT(iCmdState == EIdle && iCancelCmdState == EIdle);
    // Find the current node command since we may need its parameters.
    OSCL_ASSERT(iContainer->IsCommandInProgress(iContainer->iCurrentCommand));

    //save the sub-node command code
    iCmd = aCmd;

    switch (aCmd)
    {
        case ECPMCleanup:
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                            (0, "PVMFCPMContainerMp3::IssueCommand Calling Cleanup"));
            Cleanup();
            return PVMFSuccess;

        case ECPMInit:
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                            (0, "PVMFCPMContainerMp3::IssueCommand Calling Init"));
            //make sure any prior instance is cleaned up
            Cleanup();
            //Create a CPM instance.
            OSCL_ASSERT(iCPM == NULL);
            iCPM = PVMFCPMFactory::CreateContentPolicyManager(*this);
            if (!iCPM)
            {
                return PVMFErrNoMemory;
            }
            //thread logon may leave if there are no plugins
            int32 err;
            OSCL_TRY(err, iCPM->ThreadLogon(););
            if (err != OsclErrNone)
            {
                //end the sequence now.
                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                                (0, "PVMFCPMContainerMp3::IssueCommand No plugins, ending CPM sequence"));

                iCPM->ThreadLogoff();
                PVMFCPMFactory::DestroyContentPolicyManager(iCPM);
                iCPM = NULL;

                //treat it as unprotected content.
                PVMFStatus status = iContainer->InitNextValidClipInPlaylist(0, iContainer->GetDataStreamFactory());
                return status;
            }
            else
            {
                //continue the sequence
                iContainer->Push(*this, PVMFSubNodeContainerBaseMp3::ECPMOpenSession);
                iContainer->Push(*this, PVMFSubNodeContainerBaseMp3::ECPMRegisterContent);

                iCmdState = EBusy;
                iCmdId = iCPM->Init();
                return PVMFPending;
            }

        case ECPMOpenSession:
            OSCL_ASSERT(iCPM != NULL);
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                            (0, "PVMFCPMContainerMp3::IssueCommand Calling OpenSession"));
            iCmdState = EBusy;
            iCmdId = iCPM->OpenSession(iSessionId);
            return PVMFPending;

        case ECPMRegisterContent:
            OSCL_ASSERT(iCPM != NULL);
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                            (0, "PVMFCPMContainerMp3::IssueCommand Calling RegisterContent"));
            iCmdState = EBusy;
            if (iContainer->IsValidContextData(0) == true)
            {
                iCmdId = iCPM->RegisterContent(iSessionId,
                                               iContainer->GetClipURLAt(0),
                                               iContainer->GetClipFormatTypeAt(0),
                                               (OsclAny*) & iContainer->GetSourceContextDataAt(0));
            }
            else
            {
                iCmdId = iCPM->RegisterContent(iSessionId,
                                               iContainer->GetClipURLAt(0),
                                               iContainer->GetClipFormatTypeAt(0),
                                               (OsclAny*) & iContainer->GetCPMSourceDataAt(0));
            }
            return PVMFPending;

        case ECPMGetLicenseInterface:
            OSCL_ASSERT(iCPM != NULL);
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                            (0, "PVMFCPMContainerMp3::IssueCommand Calling GetCPMLicenseInterface"));
            iCmdState = EBusy;
            iCmdId = GetCPMLicenseInterface();
            return PVMFPending;

        case ECPMApproveUsage:
        {
            PVMFStatus status = PVMFFailure;
            OSCL_ASSERT(iCPM != NULL);
            GetCPMMetaDataExtensionInterface();
            iCPMContentType = iCPM->GetCPMContentType(iSessionId);
            if ((iCPMContentType == PVMF_CPM_FORMAT_OMA1) ||
                    (iCPMContentType == PVMF_CPM_FORMAT_AUTHORIZE_BEFORE_ACCESS))
            {
                iCmdState = EBusy;
                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                                (0, "PVMFCPMContainerMp3::IssueCommand Calling ApproveUsage"));

                //Create the usage keys
                status = CreateUsageKeys();
                if (status != PVMFSuccess)
                {
                    return status;
                }
                iCPM->GetContentAccessFactory(iSessionId, iCPMContentAccessFactory);

                if (iContainer->iDataStreamReadCapacityObserver != NULL)
                {
                    iCPMContentAccessFactory->SetStreamReadCapacityObserver(iContainer->iDataStreamReadCapacityObserver);
                }

                iCmdId = iCPM->ApproveUsage(iSessionId,
                                            iRequestedUsage,
                                            iApprovedUsage,
                                            iAuthorizationDataKvp,
                                            iUsageID);
                iContainer->oWaitingOnLicense = true;
                status = PVMFPending;
            }
            else
            {
                /* Unsupported format - use it as unprotected content */
                status = iContainer->InitNextValidClipInPlaylist(0, iContainer->GetDataStreamFactory());
            }
            return status;
        }

        case ECPMCheckUsage:
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                            (0, "PVMFCPMContainerMp3::IssueCommand Calling ECPMCheckUsage"));
            iContainer->oWaitingOnLicense = false;
            PVMFStatus status = PVMFSuccess;
            //Check for usage approval, and if approved, parse the file.
            if ((iCPMContentType == PVMF_CPM_FORMAT_OMA1) ||
                    (iCPMContentType == PVMF_CPM_FORMAT_AUTHORIZE_BEFORE_ACCESS))
            {
                status = CheckApprovedUsage();
                if (status != PVMFSuccess)
                {
                    return status;
                }
                if (!iCPMContentAccessFactory)
                {
                    return PVMFFailure;//unexpected, since ApproveUsage succeeded.
                }
                status = iContainer->InitNextValidClipInPlaylist(0, iContainer->GetDataStreamFactory());
            }
            return status;
        }
        break;

        case ECPMUsageComplete:
            if ((iCPMContentType == PVMF_CPM_FORMAT_OMA1) ||
                    (iCPMContentType == PVMF_CPM_FORMAT_AUTHORIZE_BEFORE_ACCESS))
            {
                OSCL_ASSERT(iCPM != NULL);
                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                                (0, "PVMFCPMContainerMp3::IssueCommand Calling UsageComplete"));

                iCmdState = EBusy;
                iContainer->iCPMUsageCompleteCmdId = iCPM->UsageComplete(iSessionId, iUsageID);
                return PVMFPending;
            }
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                            (0, "PVMFCPMContainerMp3::IssueCommand Calling UsageComplete"));
            return PVMFSuccess;

        case ECPMCloseSession:
            OSCL_ASSERT(iCPM != NULL);
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                            (0, "PVMFCPMContainerMp3::IssueCommand Calling CloseSession"));
            iCmdState = EBusy;
            iContainer->iCPMCloseSessionCmdId = iCPM->CloseSession(iSessionId);
            return PVMFPending;
        case ECPMReset:
            OSCL_ASSERT(iCPM != NULL);
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                            (0, "PVMFCPMContainerMp3::IssueCommand Calling Reset"));
            iCmdState = EBusy;
            iContainer->iCPMResetCmdId = iCPM->Reset();
            return PVMFPending;
        default:
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                            (0, "PVMFMP3FFParserNode::IssueCommand Failure. Command not recognized"));
            OSCL_ASSERT(false);
            return PVMFFailure;
    }
}

bool PVMFCPMContainerMp3::CancelPendingCommand()
{
    // Initiate sub-node command cancel, return True if cancel initiated.
    if (iCmdState != EBusy)
    {
        return false;//nothing to cancel
    }
    iCancelCmdState = EBusy;

    return true;//cancel initiated
}

/**
 * From PVMFCPMStatusObserver: callback from the CPM object.
 */
OSCL_EXPORT_REF void PVMFCPMContainerMp3::CPMCommandCompleted(const PVMFCmdResp& aResponse)
{
    //A command to the CPM node is complete
    PVMFCommandId aCmdId = aResponse.GetCmdId();

    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFCPMContainerMp3::CPMCommandCompleted cmdId=%d, iCmdId=%d, iCmdState=%d, cmd=%d", aCmdId, iCmdId, iCmdState, iCmd));

    if (aCmdId == iCmdId && iCmdState == EBusy)
    {
        //this is decision point, if CPM does not care about the content
        //skip rest of the CPM steps
        if (iCmd == ECPMRegisterContent)
        {
            PVMFStatus status = aResponse.GetCmdStatus();
            if (status == PVMFErrNotSupported)
            {
                //if CPM comes back as PVMFErrNotSupported then by pass rest of the CPM
                //sequence. Fake success here so that node doesnt treat this as an error
                status = iContainer->InitNextValidClipInPlaylist(0, iContainer->GetDataStreamFactory());
                if (status == PVMFPending)
                {
                    return;
                }
            }
            else if (status == PVMFSuccess)
            {
                //proceed with rest of the CPM steps
                iContainer->Push(iContainer->iCPMContainer,
                                 PVMFSubNodeContainerBaseMp3::ECPMGetLicenseInterface);
                iContainer->Push(iContainer->iCPMContainer,
                                 PVMFSubNodeContainerBaseMp3::ECPMApproveUsage);
            }
            CommandDone(status,
                        aResponse.GetEventExtensionInterface(),
                        aResponse.GetEventData());
        }
        else if (iCmd == ECPMApproveUsage)
        {
            PVMFStatus status = aResponse.GetCmdStatus();
            if (status == PVMFSuccess)
            {
                iContainer->Push(iContainer->iCPMContainer,
                                 PVMFSubNodeContainerBaseMp3::ECPMCheckUsage);
            }
            if (status != PVMFPending)
            {
                CommandDone(status,
                            aResponse.GetEventExtensionInterface(),
                            aResponse.GetEventData());
            }
            else
            {
                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE, (0, "PVMFCPMContainerMp3::CPMCommandCompleted - pending for more data "));
            }
        }
        else
        {
            if (iCmd == ECPMGetLicenseInterface)
            {
                iCPMLicenseInterface = OSCL_STATIC_CAST(PVMFCPMPluginLicenseInterface*, iCPMLicenseInterfacePVI);
                iCPMLicenseInterfacePVI = NULL;
            }
            CommandDone(aResponse.GetCmdStatus(),
                        aResponse.GetEventExtensionInterface(),
                        aResponse.GetEventData());
        }
        //catch completion of cancel for CPM commands
        //since there's no cancel to the CPM module, the cancel
        //is done whenever the current CPM command is done.
        if (iCancelCmdState != EIdle)
        {
            CancelCommandDone(PVMFSuccess, NULL, NULL);
        }
    }
    else if (aResponse.GetCmdId() == iCancelCmdId
             && iCancelCmdState == EBusy)
    {
        //Process node cancel command response
        CancelCommandDone(aResponse.GetCmdStatus(), aResponse.GetEventExtensionInterface(), aResponse.GetEventData());
    }
    else if (aResponse.GetCmdId() == iContainer->iCPMGetMetaDataValuesCmdId)
    {
        // End of GetNodeMetaDataValues
        iContainer->CommandComplete(iContainer->iCurrentCommand, aResponse.GetCmdStatus());
    }
    else if (aResponse.GetCmdId() == iContainer->iCPMUsageCompleteCmdId ||
             aResponse.GetCmdId() == iContainer->iCPMCloseSessionCmdId)
    {
        //In case these commands fail, ignore them
        CommandDone(PVMFSuccess,
                    aResponse.GetEventExtensionInterface(),
                    aResponse.GetEventData());
    }
    else if (aResponse.GetCmdId() == iContainer->iCPMResetCmdId)
    {
        if (aResponse.GetCmdStatus() != PVMFSuccess)
        {
            OSCL_ASSERT(false);
        }
        else
        {
            CommandDone(PVMFSuccess,
                        aResponse.GetEventExtensionInterface(),
                        aResponse.GetEventData());
        }
    }
    else
    {
        OSCL_ASSERT(false);//unexpected response
    }
}

void PVMFSubNodeContainerBaseMp3::CommandDone(PVMFStatus aStatus, PVInterface*aExtMsg,
        OsclAny*aEventData)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFCPMContainerMp3::CommandDone "));
    // Sub-node command is completed, process the result.
    OSCL_ASSERT(aStatus != PVMFPending);

    iCmdState = EIdle;
    PVMFStatus status = aStatus;

    // Pop the sub-node command vector.
    OSCL_ASSERT(!iContainer->iSubNodeCmdVec.empty());
    iContainer->iSubNodeCmdVec.erase(&iContainer->iSubNodeCmdVec.front());

    // Figure out the next step in the sequence
    // We need to finish all the subnode commands before completing the node
    // command. But, before continuing with the rest of the commands, store
    // the first failure from the subnode.
    if ((status != PVMFSuccess) && (iFirstSubNodeFailure == PVMFSuccess))
    {
        iFirstSubNodeFailure = status;
    }
    if (!iContainer->iSubNodeCmdVec.empty())
    {
        //The node needs to issue the next sub-node command.
        iContainer->Reschedule();
    }
    else
    {
        //node command is done.
        OSCL_ASSERT(iContainer->IsCommandInProgress(iContainer->iCurrentCommand));
        iContainer->CommandComplete(iContainer->iCurrentCommand, iFirstSubNodeFailure, aExtMsg, aEventData);
        iFirstSubNodeFailure = PVMFSuccess;

        // If cancel command pending and current command was cancelled
        if (iCancelCmdState != EIdle)
        {
            // Complete the cancel command
            CancelCommandDone(PVMFSuccess, NULL, NULL);
        }
    }
}

void PVMFSubNodeContainerBaseMp3::CancelCommandDone(PVMFStatus aStatus, PVInterface*aExtMsg, OsclAny*aEventData)
{
    // Sub-node cancel command is done: process the result
    OSCL_UNUSED_ARG(aExtMsg);
    OSCL_UNUSED_ARG(aEventData);

    OSCL_ASSERT(aStatus != PVMFPending);
    iCancelCmdState = EIdle;
    //print and ignore any failed sub-node cancel commands.
    if (aStatus != PVMFSuccess)
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iContainer->iLogger, PVLOGMSG_ERR, (0,
                        "PVMFCPMContainerMp3::CancelCommandDone CPM Node Cancel failed"));
    }

    //Node cancel command is now done.
    OSCL_ASSERT(iContainer->IsCommandInProgress(iContainer->iCurrentCommand));
    iContainer->CommandComplete(iContainer->iCurrentCommand, PVMFErrCancelled);
    iContainer->CommandComplete(iContainer->iCancelCommand, aStatus);
}

/**
 * From PvmiDataStreamObserver: callback when the DataStreamCommand is completed
 */
void PVMFMP3FFParserNode::DataStreamCommandCompleted(const PVMFCmdResp& aResponse)
{
    if (PVMF_GENERIC_NODE_INIT == iCurrentCommand.iCmd)
    {
        PVMFStatus cmdStatus = PVMFFailure;
        if (aResponse.GetCmdId() == iRequestReadCapacityNotificationID)
        {
            cmdStatus = aResponse.GetCmdStatus();
            if (cmdStatus == PVMFSuccess)
            {
                // set flag
                iCheckForMP3HeaderDuringInit = true;
                // read capacity notification is received by node,
                // i.e. amount of data that was requested by node
                // has been downloaded, reschedule now
                Reschedule();
            }
            else
            {
                LOGINFO((0, "PVMFMP3FFParserNode::DataStreamCommandCompleted() RequestReadCapacityNotification failed %d", cmdStatus));
                // command init command with some kind of failure
                CompleteInit(cmdStatus);
            }
        }
        return;
    }
    // Handle Autopause
    if (iAutoPaused)
    {
        if (aResponse.GetCmdStatus() == PVMFSuccess)
        {
            if (iTrack.iState == PVMP3FFNodeTrackPortInfo::TRACKSTATE_DOWNLOAD_AUTOPAUSE)
            {
                iTrack.iState = PVMP3FFNodeTrackPortInfo::TRACKSTATE_TRANSMITTING_GETDATA;
            }

            iAutoPaused = false;
            // Node was in auto pause state, since data
            // availability is signalled reschedule now
            Reschedule();
        }
        else
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR, (0, "PVMFMP3FFParserNode::DataStreamReadCapacityNotificationCallBack() Reporting failure"));
            ReportErrorEvent(PVMFErrResource, NULL);
        }
    }
    else
    {
        // unrecognized callback
        OSCL_ASSERT(false);
    }
}

/*
 * From PvmiDataStreamObserver: callback for info event from DataStream
 */
void PVMFMP3FFParserNode::DataStreamInformationalEvent(const PVMFAsyncEvent& aEvent)
{
    //if Datadownload is complete then send PVMFInfoBufferingComplete event from DS to parser node
    if (aEvent.GetEventType() == PVMFInfoBufferingComplete)
    {
        iDownloadComplete = true;
    }
}

/**
 * From PvmiDataStreamObserver: callback for error event from DataStream
 */
void PVMFMP3FFParserNode::DataStreamErrorEvent(const PVMFAsyncEvent& aEvent)
{
    OSCL_UNUSED_ARG(aEvent);
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_ERR, (0, "PVMFMP3FFParserNode::DataStreamErrorEvent() Doing an assert here. Unexpected error callback from DataStream"));
    //Should never be called
    OSCL_ASSERT(false);
}

PVMFStatus PVMFMP3FFParserNode::CheckForMP3HeaderAvailability(int32 aClipIndex)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::CheckForMP3HeaderAvailability In"));

    IMpeg3File* parserObj = GetParserObjAtIndex(aClipIndex);
    if (NULL == parserObj)
    {
        return PVMFFailure;
    }

    TOsclFileOffset currCapacity = 0;
    uint32 minBytesRequired = 0;

    // in local playback these variables will not be used.
    OSCL_UNUSED_ARG(currCapacity);
    OSCL_UNUSED_ARG(minBytesRequired);

    if (iDataStreamInterface != NULL)
    {
        minBytesRequired = parserObj->GetMinBytesRequired();
        /*
         * First check if we have minimum number of bytes to recognize
         * the file and determine the header size.
         */
        PvmiDataStreamStatus status = iDataStreamInterface->QueryReadCapacity(iDataStreamSessionID,
                                      currCapacity);

        if ((PVDS_SUCCESS == status) && (currCapacity < (TOsclFileOffset)minBytesRequired))
        {
            iRequestReadCapacityNotificationID =
                iDataStreamInterface->RequestReadCapacityNotification(iDataStreamSessionID,
                        *this,
                        minBytesRequired);
            return PVMFPending;
        }

        MP3ErrorType retCode = MP3_ERROR_UNKNOWN;
        if (GetClipFormatTypeAt(iPlaybackClipIndex) != PVMF_MIME_DATA_SOURCE_SHOUTCAST_URL)
        {
            retCode = parserObj->GetMetadataSize(iMP3MetaDataSize);
            if (retCode == MP3_SUCCESS)
            {
                /* Fetch the id3 tag size, if any and make it persistent in cache*/
                iDataStreamInterface->MakePersistent(0, iMP3MetaDataSize);
                if (currCapacity < (TOsclFileOffset)iMP3MetaDataSize)
                {
                    iRequestReadCapacityNotificationID =
                        iDataStreamInterface->RequestReadCapacityNotification(iDataStreamSessionID,
                                *this,
                                iMP3MetaDataSize + minBytesRequired);
                    return PVMFPending;
                }
            }
            else
            {
                iDataStreamInterface->MakePersistent(0, 0);
            }
        }
        else
        {
            iDataStreamInterface->MakePersistent(0, 0);
        }
    }

    PVMFStatus retVal = ParseFile(aClipIndex);
    // parse file failed because of lack of available data
    // if there's lack of data request more data
    if (NULL != iDataStreamInterface)
    {
        if (retVal == PVMFPending)
        {
            minBytesRequired = parserObj->GetMinBytesRequired();
            // available data wasnt sufficient to get to first valid audio frame
            // get more data
            if (currCapacity < (TOsclFileOffset)(iMP3MetaDataSize + minBytesRequired))
            {
                iRequestReadCapacityNotificationID =
                    iDataStreamInterface->RequestReadCapacityNotification(iDataStreamSessionID,
                            *this,
                            iMP3MetaDataSize + minBytesRequired);
                return PVMFPending;
            }
            else
            {
                // data read capacity notification failed.
                return PVMFFailure;
            }
        }
    }
    else
    {
        // underflow during Init for a local clip means that,
        // the clip doesnt have valid audio data to playback.
        if (retVal != PVMFSuccess)
            return PVMFFailure;
    }

    // if local playback, retrieve gapless metadata if present
    if (NULL == iDataStreamInterface)
    {
        GetGaplessMetadata(aClipIndex);
    }

    return retVal;
}

bool PVMFCPMContainerMp3::GetCPMMetaDataExtensionInterface()
{
    PVInterface* temp = NULL;
    bool retVal =
        iCPM->queryInterface(KPVMFMetadataExtensionUuid, temp);
    iCPMMetaDataExtensionInterface = OSCL_STATIC_CAST(PVMFMetadataExtensionInterface*, temp);
    return retVal;
}

PVMp3DurationCalculator::PVMp3DurationCalculator(int32 aPriority, IMpeg3File* aMP3File, PVMFMP3FFParserNode* aNode, bool aScanEnabled):
        OsclTimerObject(aPriority, "PVMp3DurationCalculator"), iNode(aNode)
{
    iErrorCode = MP3_SUCCESS;
    iMP3File = aMP3File;
    iScanComplete = false;
    iScanEnabled = aScanEnabled;
    if (!IsAdded())
    {
        AddToScheduler();
    }
    iClipIndex = 0;
}


void PVMp3DurationCalculator::SetParserObj(IMpeg3File* aMP3File)
{
    iMP3File = aMP3File;
    iErrorCode = MP3_SUCCESS; // reset error code for new parser
    iScanComplete = false;
}

void PVMp3DurationCalculator::SetClipIndex(uint32 aClipIndex)
{
    iClipIndex = aClipIndex;
}

PVMp3DurationCalculator::~PVMp3DurationCalculator()
{
    if (IsAdded())
    {
        RemoveFromScheduler();
    }
}

void PVMp3DurationCalculator::ScheduleAO()
{
    totalticks = 0;
    if (iScanEnabled && iMP3File)
    {
        RunIfNotReady();
    }
}

void PVMp3DurationCalculator::Run()
{
    // dont do the duration calculation scan in case of PS/PD
    if (iNode->iDownloadProgressInterface)
    {
        return;
    }

    if (iErrorCode == MP3_DURATION_PRESENT)
    {
        // A valid duration is already present no need to scan the file, just send the duration event and return
        iScanComplete = true;
        int32 durationInMsec = iMP3File->GetDuration();
        int32 leavecode = 0;
        PVMFDurationInfoMessage* eventmsg = NULL;
        OSCL_TRY(leavecode, eventmsg = OSCL_NEW(PVMFDurationInfoMessage, (durationInMsec)));

        uint8 localbuffer[4];
        oscl_memcpy(localbuffer, &iClipIndex, sizeof(uint32));
        PVMFAsyncEvent asyncevent(PVMFInfoEvent, PVMFInfoDurationAvailable, NULL, OSCL_STATIC_CAST(PVInterface*, eventmsg), NULL, localbuffer, 4);
        iNode->ReportInfoEvent(asyncevent);
        if (eventmsg)
        {
            eventmsg->removeRef();
        }
        return;
    }
    if (iErrorCode != MP3_SUCCESS)
    {
        iScanComplete = true;
        int32 durationInMsec = iMP3File->GetDuration();
        int32 leavecode = 0;
        PVMFDurationInfoMessage* eventmsg = NULL;
        OSCL_TRY(leavecode, eventmsg = OSCL_NEW(PVMFDurationInfoMessage, (durationInMsec)));
        uint8 localbuffer[4];
        oscl_memcpy(localbuffer, &iClipIndex, sizeof(uint32));
        PVMFAsyncEvent asyncevent(PVMFInfoEvent, PVMFInfoDurationAvailable, NULL, OSCL_STATIC_CAST(PVInterface*, eventmsg), NULL, localbuffer, 4);
        iNode->ReportInfoEvent(asyncevent);
        if (eventmsg)
        {
            eventmsg->removeRef();
        }
        return;
    }
    else if (!iScanComplete)
    {
        RunIfNotReady(PVMF3FF_DURATION_SCAN_AO_DELAY);
    }
    else
    {
        return;
    }

    if (!(iNode->iTrack.iSendBOS))
    {
        // Start the scan only when we have send first audio sample
        iErrorCode = iMP3File->ScanMP3File(PVMF3FF_DEFAULT_NUM_OF_FRAMES * 5);
    }
}

PVMFStatus PVMFMP3FFParserNode::ConstructMP3FileParser(MP3ErrorType &aSuccess, int32 aClipIndex, PVMFCPMPluginAccessInterfaceFactory* aCPM)
{
    int32 leavecode = 0;
    IMpeg3File* mp3file = NULL;
    PVMFStatus status = PVMFFailure;
    OSCL_TRY(leavecode, mp3file = PVMF_BASE_NODE_NEW(IMpeg3File,
                                  (iClipInfoList[aClipIndex].iClipInfo.GetSourceURL(), aSuccess,
                                   &iFileServer, aCPM,
                                   iClipInfoList[aClipIndex].iClipInfo.GetFileHandle(), false)));

    OSCL_FIRST_CATCH_ANY(leavecode, return PVMFErrNoMemory);
    if (aSuccess == MP3_SUCCESS)
    {
        iClipInfoList[aClipIndex].iParserObj = mp3file;
        status = PVMFSuccess;

    }
    else
    {
        // clean up the parser object
        OSCL_DELETE(mp3file);
        mp3file = NULL;
    }

    PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "PVMFMP3FFParserNode::ConstructMP3FileParser() ClipIndex[%d]", aClipIndex));
    return status;
}


PVMFStatus PVMFMP3FFParserNode::ReleaseMP3FileParser(int32 aClipIndex, bool cleanParserAtLastIndex)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "PVMFMP3FFParserNode::ReleaseMP3FileParser() ClipIndex[%d]", aClipIndex));
    // dont clean up parser object at last index in the list, unless it is requested
    if (aClipIndex >= 0 && (iNumClipsInPlayList > 1 || cleanParserAtLastIndex))
    {
        if (((uint32) aClipIndex == iClipInfoList[iClipInfoList.size() - 1].iClipInfo.GetClipIndex()) ||
                iPlaylistExhausted)
        {
            iPlaybackParserObj = NULL;
            if (iDurationCalcAO)
            {
                PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR, (0, "PVMFMP3FFParserNode::ReleaseMP3FileParser() Release Duration Calc AO", aClipIndex));
                iDurationCalcAO->Cancel();
                OSCL_DELETE(iDurationCalcAO);
                iDurationCalcAO = NULL;
            }
        }

        IMpeg3File* parserObj = GetParserObjAtIndex(aClipIndex);
        if (NULL != parserObj)
        {
            if (parserObj == iMetadataParserObj)
            {
                iMetadataParserObj = NULL;
            }

            OSCL_DELETE(parserObj);
            parserObj = NULL;
            iClipInfoList[aClipIndex].iParserObj = NULL;
        }

        return PVMFSuccess;
    }
    return PVMFFailure;
}

void PVMFMP3FFParserNode::MetadataUpdated(uint32 aMetadataSize)
{
    if (!iMetadataVector.empty())
    {
        iMetadataVector.clear();
    }

    iMetadataSize = aMetadataSize;
    int32 leavecode = OsclErrNone;
    PVMFMetadataInfoMessage* eventMsg = NULL;
    // parse the metadata to a kvp vector
    ParseShoutcastMetadata((char*) iMetadataBuf, iMetadataSize, iMetadataVector);
    // create a info msg
    OSCL_TRY(leavecode, eventMsg = PVMF_BASE_NODE_NEW(PVMFMetadataInfoMessage, (iMetadataVector)));
    // report the info msg to observer
    uint8 localbuffer[4];
    oscl_memcpy(localbuffer, &iPlaybackClipIndex, sizeof(uint32));
    PVMFAsyncEvent asyncevent(PVMFInfoEvent, PVMFInfoMetadataAvailable, NULL, OSCL_STATIC_CAST(PVInterface*, eventMsg), NULL, localbuffer, 4);

    ReportInfoEvent(asyncevent);

    if (eventMsg)
    {
        eventMsg->removeRef();
    }

    uint32 i = 0;
    //cleanup the metadata vector
    while (i < iMetadataVector.size())
    {
        PvmiKvp kvp = iMetadataVector[i];
        if (kvp.key)
        {
            OSCL_ARRAY_DELETE(kvp.key);
            kvp.key = NULL;
        }
        if (kvp.value.pChar_value)
        {
            OSCL_ARRAY_DELETE(kvp.value.pChar_value);
            kvp.value.pChar_value = NULL;
        }
        i++;
    }

    while (!iMetadataVector.empty())
    {
        iMetadataVector.erase(iMetadataVector.begin());
    }
}

PVMFStatus PVMFMP3FFParserNode::ParseShoutcastMetadata(char* aMetadataBuf, uint32 aMetadataSize, Oscl_Vector<PvmiKvp, OsclMemAllocator>& aKvpVector)
{
    // parse shoutcast metadata
    char* metadataPtr = NULL;
    metadataPtr = (char*)oscl_malloc(aMetadataSize);
    oscl_strncpy(metadataPtr, aMetadataBuf, aMetadataSize);

    char* bufPtr = metadataPtr;

    PvmiKvp kvp;

    char* key = NULL;
    char* valueStr = NULL;
    while (true)
    {
        key = bufPtr;
        char* tmpPtr = oscl_strchr(bufPtr, '=');
        if (NULL == tmpPtr)
        {
            break;
        }
        *tmpPtr = '\0';
        valueStr = tmpPtr + 2; // skip 2 bytes. '=' & '''
        tmpPtr = oscl_strchr(valueStr, ';');
        if (NULL == tmpPtr)
        {
            break;
        }
        *(tmpPtr - 1) = '\0'; // remove '''
        *tmpPtr = '\0';

        bufPtr = tmpPtr + 1;

        // make kvp from key & valueStr info
        OSCL_StackString<128> keyStr;
        keyStr = _STRLIT_CHAR("");

        if (!(oscl_strncmp(key, "StreamTitle", oscl_strlen("StreamTitle"))))
        {
            keyStr += _STRLIT_CHAR(KVP_KEY_TITLE);
            keyStr += SEMI_COLON;
            keyStr += _STRLIT_CHAR(KVP_VALTYPE_ISO88591_CHAR);
        }
        else if (!(oscl_strncmp(key, "StreamUrl", oscl_strlen("StreamUrl"))))
        {
            keyStr += _STRLIT_CHAR(KVP_KEY_DESCRIPTION);
            keyStr += SEMI_COLON;
            keyStr += _STRLIT_CHAR(KVP_VALTYPE_ISO88591_CHAR);
        }
        else
        {
            //not supported
        }

        keyStr += NULL_CHARACTER;

        int32 keylen = oscl_strlen(keyStr.get_cstr());
        int32 valuelen = oscl_strlen(valueStr);

        kvp.key = OSCL_ARRAY_NEW(char, (keylen + 1));
        kvp.value.pChar_value = OSCL_ARRAY_NEW(char, (valuelen + 1));

        oscl_strncpy(kvp.key, keyStr.get_cstr(), keylen + 1);
        oscl_strncpy(kvp.value.pChar_value, valueStr, valuelen + 1);

        aKvpVector.push_back(kvp);
    }

    if (metadataPtr)
    {
        oscl_free(metadataPtr);
        metadataPtr = NULL;
    }
    return PVMFSuccess;
}

uint32 PVMFMP3FFParserNode::GetCurrentClipIndex()
{
    return iPlaybackClipIndex;
}

OSCL_wHeapString<OsclMemAllocator>& PVMFMP3FFParserNode::GetClipURLAt(uint32 aClipIndex)
{
    return iClipInfoList[aClipIndex].iClipInfo.GetSourceURL();
}

PVMFFormatType& PVMFMP3FFParserNode::GetClipFormatTypeAt(uint32 aClipIndex)
{
    return iClipInfoList[aClipIndex].iClipInfo.GetFormatType();
}

PVMFSourceContextData& PVMFMP3FFParserNode::GetSourceContextDataAt(uint32 aClipIndex)
{
    return iClipInfoList[aClipIndex].iClipInfo.iSourceContextData;
}

bool PVMFMP3FFParserNode::IsValidContextData(uint32 aClipIndex)
{
    return iClipInfoList[aClipIndex].iClipInfo.iSourceContextDataValid;
}

PVMFLocalDataSource& PVMFMP3FFParserNode::GetCPMSourceDataAt(uint32 aClipIndex)
{
    return iClipInfoList[aClipIndex].iClipInfo.iCPMSourceData;
}

PVMFDataStreamFactory* PVMFMP3FFParserNode::GetDataStreamFactory()
{
    PVMFDataStreamFactory* dsFactory = NULL;
    dsFactory = iCPMContainer.iCPMContentAccessFactory;
    if ((dsFactory == NULL) && (iDataStreamFactory != NULL))
    {
        if (GetClipFormatTypeAt(0) == PVMF_MIME_DATA_SOURCE_SHOUTCAST_URL && iSCSPFactory != NULL && iSCSP != NULL)
        {
            dsFactory = iSCSPFactory;
            iSCSP->RequestMetadataUpdates(iDataStreamSessionID, *this, iMetadataBufSize, iMetadataBuf);
        }
        else
        {
            dsFactory = iDataStreamFactory;
        }
    }
    return dsFactory;
}


PVMFStatus PVMFMP3FFParserNode::InitNextValidClipInPlaylist(int32 aSkipToTrack, PVMFDataStreamFactory* aDataStreamFactory)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_NOTICE, (0, "PVMFMP3FFParserNode::InitNextValidClipInPlaylist In"));
    PVMFStatus status = PVMFFailure;
    MP3ErrorType bSuccess = MP3_SUCCESS;
    int32 clipIndex = -1;

    // reposition has occured, track needs to be changed to skipped location
    if (aSkipToTrack < 0)
    {
        // skip to next track
        clipIndex = (-1 == iPlaybackClipIndex) ? 0 : iPlaybackClipIndex + 1;
    }
    else
    {
        // skip to requested track
        clipIndex = aSkipToTrack;
    }

    while (PVMFSuccess != status && clipIndex <= (int32)(iNumClipsInPlayList - 1))
    {
        PVMFStatus returncode = ConstructMP3FileParser(bSuccess, clipIndex, aDataStreamFactory);
        IMpeg3File* parserObj = GetParserObjAtIndex(clipIndex);

        if (PVMFSuccess != returncode ||
                NULL == parserObj ||
                MP3_SUCCESS != bSuccess)
        {
            if (iNumClipsInPlayList == 1)
            {
                // playback cant proceed if there's only one clip in the list
                // else skip shall happen to next clip.
                SetState(EPVMFNodeError);
                return PVMFErrResource;
            }
            else
            {
                uint8 localbuffer[4];
                oscl_memcpy(localbuffer, &clipIndex, sizeof(uint32));
                PVMFAsyncEvent asyncevent(PVMFInfoEvent, PVMFInfoClipCorrupted, NULL, OSCL_STATIC_CAST(PVInterface*, NULL), NULL, localbuffer, 4);
                ReportInfoEvent(asyncevent);
                clipIndex++; // index for next clip
                continue;
            }
        }

        status = CheckForMP3HeaderAvailability(clipIndex);
        uint32 metadataindex = clipIndex;
        if (status == PVMFSuccess)
        {
            // report the info msg to observer
            uint8 localbuffer[4];
            oscl_memcpy(localbuffer, &metadataindex, sizeof(uint32));
            PVMFAsyncEvent asyncevent(PVMFInfoEvent, PVMFInfoMetadataAvailable, NULL, OSCL_STATIC_CAST(PVInterface*, NULL), NULL, localbuffer, 4);

            ReportInfoEvent(asyncevent);

            iNextInitializedClipIndex = iClipInfoList[clipIndex].iClipInfo.GetClipIndex();
            if (iPlaybackClipIndex == -1)
            {
                // set first valid clip in list
                iPlaybackClipIndex = iClipIndexForMetadata = iNextInitializedClipIndex;
                iPlaybackParserObj = iMetadataParserObj = parserObj;
            }

            if (OsclErrNone == AllocateDurationCalculator())
            {
                if (iDurationCalcAO)
                {
                    iDurationCalcAO->SetParserObj(parserObj);
                    iDurationCalcAO->SetClipIndex(iNextInitializedClipIndex);
                    iDurationCalcAO->ScheduleAO();
                }
            }

            iClipInfoList[clipIndex].iClipInfo.iIsInitialized = true;
        }
        else if (status == PVMFPending)
        {
            return status;
        }
        else
        {
            ReleaseMP3FileParser(clipIndex);

            uint8 localbuffer[4];
            oscl_memcpy(localbuffer, &clipIndex, sizeof(uint32));
            PVMFAsyncEvent asyncevent(PVMFInfoEvent, PVMFInfoClipCorrupted, NULL, OSCL_STATIC_CAST(PVInterface*, NULL), NULL, localbuffer, 4);

            ReportInfoEvent(asyncevent);
            clipIndex++; // index for next clip
        }
    }

    if (status != PVMFSuccess && clipIndex >= (int32)iNumClipsInPlayList)
    {
        // no more valid clips are found
        // clip list has exhausted, dont accept more playlist updates
        iPlaylistExhausted = true;
    }
    iInitNextClip = false;
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_NOTICE, (0, "PVMFMP3FFParserNode::InitNextValidClipInPlaylist Out Initialized Index [%d]", iNextInitializedClipIndex));
    return status;
}


void PVMFMP3FFParserNode::GetGaplessMetadata(int32 aClipIndex)
{
    // retrieve gapless metadata if present
    // do it only once per clip

    IMpeg3File* mp3File = iClipInfoList[aClipIndex].iParserObj;
    if (iClipInfoList[aClipIndex].iParserObj != NULL)
    {
        iClipInfoList[aClipIndex].iClipInfo.iGaplessInfoAvailable = mp3File->GetGaplessMetadata(iClipInfoList[aClipIndex].iClipInfo.iGaplessMetadata);

        if (iClipInfoList[aClipIndex].iClipInfo.iGaplessInfoAvailable)
        {
            // check encoder delay
            uint32 delay = iClipInfoList[aClipIndex].iClipInfo.iGaplessMetadata.GetEncoderDelay();
            if (0 != delay)
            {
                // frame numbers from the parser are 1 based
                iClipInfoList[aClipIndex].iClipInfo.iFrameBOC = 1;
                iClipInfoList[aClipIndex].iClipInfo.iSendBOC = true;

                // create format specific info for BOC
                // uint32 - number of samples to skip
                // allocate memory for BOC specific info and ref counter
                OsclMemoryFragment frag;
                frag.ptr = NULL;
                frag.len = sizeof(BOCInfo);
                uint refCounterSize = oscl_mem_aligned_size(sizeof(OsclRefCounterDA));
                uint8* memBuffer = (uint8*)iClipInfoList[aClipIndex].iClipInfo.iBOCFormatSpecificInfoAlloc.ALLOCATE(refCounterSize + frag.len);
                if (!memBuffer)
                {
                    // failure while allocating memory buffer
                    iClipInfoList[aClipIndex].iClipInfo.iSendBOC = false;
                }

                oscl_memset(memBuffer, 0, refCounterSize + frag.len);
                // create ref counter
                OsclRefCounter* refCounter = new(memBuffer) OsclRefCounterDA(memBuffer,
                        (OsclDestructDealloc*)&iClipInfoList[aClipIndex].iClipInfo.iBOCFormatSpecificInfoAlloc);
                memBuffer += refCounterSize;
                // create BOC info
                frag.ptr = (OsclAny*)(new(memBuffer) BOCInfo);
                ((BOCInfo*)frag.ptr)->samplesToSkip = delay;

                // store info in a ref counter memfrag
                // how do we make sure that we are not doing this more than once?
                iClipInfoList[aClipIndex].iClipInfo.iBOCFormatSpecificInfo = OsclRefCounterMemFrag(frag, refCounter, sizeof(struct BOCInfo));
            }

            // check zero padding
            uint32 padding = iClipInfoList[aClipIndex].iClipInfo.iGaplessMetadata.GetZeroPadding();
            if (0 != padding)
            {
                // calculate frame number of the first frame of EOC
                uint64 total = iClipInfoList[aClipIndex].iClipInfo.iGaplessMetadata.GetTotalFrames();
                uint32 spf = iClipInfoList[aClipIndex].iClipInfo.iGaplessMetadata.GetSamplesPerFrame();
                uint32 frames = padding / spf;
                if (padding % spf)
                {
                    frames++;
                }
                // frame numbers from the parser are 1 based
                iClipInfoList[aClipIndex].iClipInfo.iFirstFrameEOC = total - frames + 1;
                iClipInfoList[aClipIndex].iClipInfo.iSendEOC = true;

                // create format specific info for EOC
                // uint32 - number of samples to skip
                // allocate memory for BOC specific info and ref counter
                OsclMemoryFragment frag;
                frag.ptr = NULL;
                frag.len = sizeof(EOCInfo);
                uint refCounterSize = oscl_mem_aligned_size(sizeof(OsclRefCounterDA));
                uint8* memBuffer = (uint8*)iClipInfoList[aClipIndex].iClipInfo.iBOCFormatSpecificInfoAlloc.ALLOCATE(refCounterSize + frag.len);
                if (!memBuffer)
                {
                    // failure while allocating memory buffer
                    iClipInfoList[aClipIndex].iClipInfo.iSendEOC = false;
                }

                oscl_memset(memBuffer, 0, refCounterSize + frag.len);
                // create ref counter
                OsclRefCounter* refCounter = new(memBuffer) OsclRefCounterDA(memBuffer,
                        (OsclDestructDealloc*)&iClipInfoList[aClipIndex].iClipInfo.iEOCFormatSpecificInfoAlloc);
                memBuffer += refCounterSize;
                // create EOC info
                frag.ptr = (OsclAny*)(new(memBuffer) EOCInfo);
                // but we don't know how many frames will be following this msg yet!!!
                ((EOCInfo*)frag.ptr)->framesToFollow = 0;
                ((EOCInfo*)frag.ptr)->samplesToSkip = padding;

                // store info in a ref counter memfrag
                // how do we make sure that we are not doing this more than once?
                iClipInfoList[aClipIndex].iClipInfo.iEOCFormatSpecificInfo = OsclRefCounterMemFrag(frag, refCounter, sizeof(EOCInfo));
            }

            // log the gapless metadata
            LOGGAPLESSINFO((0, "PVMFMP3FFParserNode::GetGaplessMetadata() clip index %d, encoder delay %d samples, zero padding %d samples, original length %d%d samples, samples per frame %d, total frames %d%d, part of gapless album %d",
                            aClipIndex, delay, padding, (uint32)(iClipInfoList[aClipIndex].iClipInfo.iGaplessMetadata.GetOriginalStreamLength() >> 32), (uint32)(iClipInfoList[aClipIndex].iClipInfo.iGaplessMetadata.GetOriginalStreamLength() & 0xFFFFFFFF),
                            iClipInfoList[aClipIndex].iClipInfo.iGaplessMetadata.GetSamplesPerFrame(), (uint32)(iClipInfoList[aClipIndex].iClipInfo.iGaplessMetadata.GetTotalFrames() >> 32),
                            (uint32)(iClipInfoList[aClipIndex].iClipInfo.iGaplessMetadata.GetTotalFrames() & 0xFFFFFFFF), iClipInfoList[aClipIndex].iClipInfo.iGaplessMetadata.GetPartOfGaplessAlbum()));
        }
        else
        {
            LOGGAPLESSINFO((0, "PVMFMP3FFParserNode::GetGaplessMetadata() clip index %d, no gapless metadata found", aClipIndex));
        }
    }
}


/**
 * Send BOC command to output port
 */
bool PVMFMP3FFParserNode::SendBeginOfClipCommand(PVMP3FFNodeTrackPortInfo& aTrackPortInfo)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::SendBeginOfClipCommand() In"));

    // Create media command
    PVMFSharedMediaCmdPtr sharedMediaCmdPtr = PVMFMediaCmd::createMediaCmd();

    // Set command id to BOC
    sharedMediaCmdPtr->setFormatID(PVMF_MEDIA_CMD_BOC_FORMAT_ID);
    // Retrieve timestamp and convert to milliseconds
    uint32 timestamp = aTrackPortInfo.iClockConverter->get_converted_ts(COMMON_PLAYBACK_CLOCK_TIMESCALE);
    timestamp += aTrackPortInfo.timestamp_offset;
    timestamp += iCurrSampleDuration;
    // Set the timestamp
    sharedMediaCmdPtr->setTimestamp(timestamp);
    // Set the sequence number
    sharedMediaCmdPtr->setSeqNum(aTrackPortInfo.iSeqNum++);
    // set stream id
    sharedMediaCmdPtr->setStreamID(iStreamID);
    // Set current playback clip id
    sharedMediaCmdPtr->setClipID(iPlaybackClipIndex);

    // set format specific info
    sharedMediaCmdPtr->setFormatSpecificInfo(iClipInfoList[iPlaybackClipIndex].iClipInfo.iBOCFormatSpecificInfo);

    // Convert media command to media message
    PVMFSharedMediaMsgPtr mediaMsgOut;
    convertToPVMFMediaCmdMsg(mediaMsgOut, sharedMediaCmdPtr);

    // Queue media msg to output pout
    if (aTrackPortInfo.iPort->QueueOutgoingMsg(mediaMsgOut) != PVMFSuccess)
    {
        // Output queue is busy, so wait for the output queue being ready
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                        (0, "PVMFMP3FFParserNode::SendBeginOfClipCommand: Outgoing queue busy. "));
        return false;
    }

    // BOC was sent successfully
    iClipInfoList[iPlaybackClipIndex].iClipInfo.iHasBOCFrame = false;
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::SendBeginOfClipCommand() Out"));
    return true;
}

/**
 * Send EOC command to output port
 */
bool PVMFMP3FFParserNode::SendEndOfClipCommand(PVMP3FFNodeTrackPortInfo& aTrackPortInfo)
{
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::SendEndOfClipCommand() In"));

    // Create media command
    PVMFSharedMediaCmdPtr sharedMediaCmdPtr = PVMFMediaCmd::createMediaCmd();

    // Set command id to EOC
    sharedMediaCmdPtr->setFormatID(PVMF_MEDIA_CMD_EOC_FORMAT_ID);
    // Retrieve media data timestamp
    uint32 timestamp = aTrackPortInfo.iClockConverter->get_converted_ts(COMMON_PLAYBACK_CLOCK_TIMESCALE);
    timestamp += aTrackPortInfo.timestamp_offset;
    //@todo timestamp += iCurrSampleDuration;
    // Set the timestamp
    sharedMediaCmdPtr->setTimestamp(timestamp);
    // Set the duration
    sharedMediaCmdPtr->setDuration(0);
    // Set the sequence number
    sharedMediaCmdPtr->setSeqNum(aTrackPortInfo.iSeqNum++);
    // set stream id
    sharedMediaCmdPtr->setStreamID(iStreamID);
    // Set current playback clip id
    sharedMediaCmdPtr->setClipID(iPlaybackClipIndex);
    // set format specific info
    struct EOCInfo* fragPtr = (struct EOCInfo*)iClipInfoList[iPlaybackClipIndex].iClipInfo.iEOCFormatSpecificInfo.getMemFragPtr();
    fragPtr->framesToFollow = iClipInfoList[iPlaybackClipIndex].iClipInfo.iFramesToFollowEOC;

    // fill in the number of frames to follow
    sharedMediaCmdPtr->setFormatSpecificInfo(iClipInfoList[iPlaybackClipIndex].iClipInfo.iEOCFormatSpecificInfo);

    // Convert media command to media message
    PVMFSharedMediaMsgPtr mediaMsgOut;
    convertToPVMFMediaCmdMsg(mediaMsgOut, sharedMediaCmdPtr);

    // Queue media msg to output pout
    if (aTrackPortInfo.iPort->QueueOutgoingMsg(mediaMsgOut) != PVMFSuccess)
    {
        // Output queue is busy, so wait for the output queue being ready
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                        (0, "PVMFMP3FFParserNode::SendEndOfClipCommand: Outgoing queue busy. "));
        return false;
    }

    // EOC was sent successfully
    iClipInfoList[iPlaybackClipIndex].iClipInfo.iHasEOCFrame = false;
    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                    (0, "PVMFMP3FFParserNode::SendEndOfClipCommand() Out"));
    return true;
}


/**
 * Adjust for the dropped frames for gapless playback
 */
uint32 PVMFMP3FFParserNode::GetGaplessDuration(PVMP3FFNodeTrackPortInfo& aTrackPortInfo)
{
    if (iPlaybackParserObj)
    {
        uint32 durationInMsec = iPlaybackParserObj->GetDuration();
        MP3ContentFormatType mp3Config;

        if (iPlaybackParserObj->GetConfigDetails(mp3Config) && (mp3Config.SamplingRate != 0))
        {
            uint32 droppedSamples = iClipInfoList[iPlaybackClipIndex].iClipInfo.iGaplessMetadata.GetEncoderDelay() + iClipInfoList[iPlaybackClipIndex].iClipInfo.iGaplessMetadata.GetZeroPadding();
            uint32 droppedMsec = (droppedSamples * 1000) / mp3Config.SamplingRate;
            durationInMsec = (durationInMsec > droppedMsec) ? (durationInMsec - droppedMsec) : 0;
        }
        return durationInMsec;
    }
    return 0;
}

bool PVMFMP3FFParserNode::ValidateSourceInitializationParams(OSCL_wString& aSourceURL,
        PVMFFormatType& aSourceFormat,
        uint32 aClipIndex,
        PVMFSourceClipInfo aClipInfo)
{
    if (aClipInfo.GetFormatType() != aSourceFormat)
    {
        return true;
    }

    if (aClipInfo.GetClipIndex() != aClipIndex)
    {
        return true;
    }

    int32 res = oscl_strncmp(aSourceURL.get_cstr(), aClipInfo.GetSourceURL().get_cstr(), oscl_strlen(aSourceURL.get_cstr()));
    if (res != 0)
    {
        return true;
    }

    return false;
}

int32 PVMFMP3FFParserNode::AllocateDurationCalculator()
{
    int32 leavecode = OsclErrNone;
    if (!iDataStreamFactory && !iDurationCalcAO)
    {
        OSCL_TRY(leavecode, iDurationCalcAO = PVMF_BASE_NODE_NEW(PVMp3DurationCalculator,
                                              (OsclActiveObject::EPriorityIdle, NULL, this)));
        if (leavecode)
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                            (0, "PVMFMP3FFParserNode::AllocateDurationCalculator() Duration Scan is disabled. DurationCalcAO not created"));
        }
    }
    return leavecode;
}