File: cBaseMediaFile.cpp

package info (click to toggle)
ffdiaporama 1.5-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 23,772 kB
  • ctags: 3,454
  • sloc: cpp: 30,926; xml: 183; makefile: 10
file content (2709 lines) | stat: -rwxr-xr-x 140,157 bytes parent folder | download | duplicates (2)
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
/* ======================================================================
    This file is part of ffDiaporama
    ffDiaporama is a tools to make diaporama as video
    Copyright (C) 2011-2012 Dominique Levray <levray.dominique@bbox.fr>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
   ====================================================================== */

// Include some common various class
#include "cBaseApplicationConfig.h"

// Include some additional standard class
#include "_QCustomDialog.h"
#include <QFileDialog>
#include <QPainter>

// Include some additional standard class
#include "cBaseMediaFile.h"
#include "cLuLoImageCache.h"

#define FFD_APPLICATION_ROOTNAME    "Project"           // Name of root node in the project xml file

#ifndef INT64_MAX
    #define 	INT64_MAX   0x7fffffffffffffffLL
    #define 	INT64_MIN   (-INT64_MAX - 1LL)
#endif

//#ifdef _MSC_VER
//    #undef AV_TIME_BASE_Q
//    AVRational AV_TIME_BASE_Q={1, AV_TIME_BASE};
//#endif

#define VC_ERROR        0x00000001
#define VC_BUFFER       0x00000002
#define VC_PICTURE      0x00000004
#define VC_USERDATA     0x00000008
#define VC_FLUSHED      0x00000010

//****************************************************************************************************************************************************************

// from Google music manager (see:http://code.google.com/p/gogglesmm/source/browse/src/gmutils.cpp?spec=svn6c3dbecbad40ee49736b9ff7fe3f1bfa6ca18c13&r=6c3dbecbad40ee49736b9ff7fe3f1bfa6ca18c13)
bool gm_decode_base64(uchar *buffer,uint &len) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:gm_decode_base64");

    static const unsigned char base64[256]={
    0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,
    0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,
    0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x3e,0x80,0x80,0x80,0x3f,
    0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x80,0x80,0x80,0x80,0x80,0x80,
    0x80,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,
    0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x80,0x80,0x80,0x80,0x80,
    0x80,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,
    0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,0x30,0x31,0x32,0x33,0x80,0x80,0x80,0x80,0x80,
    0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,
    0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,
    0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,
    0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,
    0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,
    0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,
    0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,
    0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80};

    uint  pos=0;
    uchar v;
    for (uint i=0,b=0;i<len;i++) {
        v=base64[buffer[i]];
        if (v!=0x80) {
          switch(b) {
            case 0: buffer[pos]=(v<<2);
                    b++;
                    break;
            case 1: buffer[pos++]|=(v>>4);
                    buffer[pos]=(v<<4);
                    b++;
                    break;
            case 2: buffer[pos++]|=(v>>2);
                    buffer[pos]=(v<<6);
                    b++;
                    break;
            case 3: buffer[pos++]|=v;
                    b=0;
                    break;
            }
        } else {
            if (buffer[i]=='=' && b>1) {
                len=pos;
                return true;
            } else return false;
        }
    }
    len=pos;
    return true;
}

QImage *GetEmbededImage(QString FileName) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:GetEmbededImage");

    // Try to get embeded image
    QImage *Image=new QImage();

    //*********** MP3
    if ((Image->isNull())&&(QFileInfo(FileName).suffix().toLower()=="mp3")) {
        TagLib::MPEG::File MP3File(TagLib::FileName(FileName.toLocal8Bit()));
        if (MP3File.ID3v2Tag()) {
            TagLib::ID3v2::FrameList l=MP3File.ID3v2Tag()->frameListMap()["APIC"];
            if (!l.isEmpty()) {
                TagLib::ID3v2::AttachedPictureFrame *pic=static_cast<TagLib::ID3v2::AttachedPictureFrame *>(l.front());
                if (pic) Image->loadFromData((const uchar *)pic->picture().data(),pic->picture().size());
            }
        }
    }
    //*********** FLAC
    #ifdef TAGLIBWITHFLAC
    if ((Image->isNull())&&(QFileInfo(FileName).suffix().toLower()=="flac")) {
        TagLib::FLAC::File                      FLACFile(TagLib::FileName(FileName.toLocal8Bit()));
        TagLib::List<TagLib::FLAC::Picture *>   PictList=FLACFile.pictureList();

        // Search PreferedPic : the one with the type lesser
        TagLib::FLAC::Picture *PreferedPic=NULL;
        if (!PictList.isEmpty()) for (uint i=0;i<PictList.size();i++) {
            TagLib::FLAC::Picture *Pic=PictList[i];
            if ((Pic!=NULL)&&((PreferedPic==NULL)||(PreferedPic->type()>Pic->type()))) PreferedPic=Pic;
        }
        if (PreferedPic) Image->loadFromData((const uchar *)PreferedPic->data().data(),PreferedPic->data().size());
    }
    #endif
    //*********** OGG
    if ((Image->isNull())&&((QFileInfo(FileName).suffix().toLower()=="ogg")||(QFileInfo(FileName).suffix().toLower()=="oga"))) {
        TagLib::Vorbis::File OggFile(TagLib::FileName(FileName.toLocal8Bit()));
        if ((OggFile.tag())&&(OggFile.tag()->contains(TagLib::String("COVERART")))) {
            const TagLib::StringList &CoverList=OggFile.tag()->fieldListMap()["COVERART"];
            for (TagLib::StringList::ConstIterator it=CoverList.begin();it!=CoverList.end();it++) {
                const TagLib::ByteVector &Vector=(*it).data(TagLib::String::UTF8);
                if ((Image->isNull())&&(Vector.size())) {
                    uint  len    =Vector.size();
                    uchar *buffer=(uchar *)malloc(len);
                    memcpy(buffer,Vector.data(),len);
                    if (gm_decode_base64(buffer,len))
                        Image->loadFromData((const uchar *)buffer,len);
                    free(buffer);
                }

            }
        }
    }
    //*********** MP4/M4A => don't work with M4V or MP4 video
    #ifdef TAGLIBWITHMP4
    if ((Image->isNull())&&(/*(QFileInfo(FileName).suffix().toLower()=="mp4")||*/(QFileInfo(FileName).suffix().toLower()=="m4a")||(QFileInfo(FileName).suffix().toLower()=="m4v"))) {
        TagLib::MP4::File MP4File(TagLib::FileName(FileName.toLocal8Bit()));
        if ((MP4File.tag())&&(MP4File.tag()->itemListMap().contains("covr"))) {
            TagLib::MP4::CoverArtList coverArtList = MP4File.tag()->itemListMap()["covr"].toCoverArtList();
            if (coverArtList.size()!= 0) {
                TagLib::MP4::CoverArt ca = coverArtList.front();
                Image->loadFromData((const uchar *) ca.data().data(),ca.data().size());
            }
        }
    }
    #endif
    //*********** ASF/WMA //////////////////// A FINIR ! ///////////// CA A PAS L'AIR DE MARCHER !
    #ifdef TAGLIBWITHASF
    if ((Image->isNull())&&(QFileInfo(FileName).suffix().toLower()=="wma")) {
        TagLib::ASF::File ASFFile(TagLib::FileName(TagLib::FileName(FileName.toLocal8Bit())));
        /*
        TagLib::ASF::Tag* asfTag = dynamic_cast<TagLib::ASF::Tag*>(ASFFile.tag());
        TagLib::ASF::AttributeListMap& attrListMap = asfTag->attributeListMap();
        for (TagLib::ASF::AttributeListMap::Iterator it=attrListMap.begin();it!=attrListMap.end();++it) {

            TagLib::ASF::AttributeList& attrList = (*it).second;
            for (TagLib::ASF::AttributeList::Iterator ait = attrList.begin();ait != attrList.end();++ait) {
                //qDebug()<< QString().fromStdString((*ait).toString().toCString());
            }
        }
        */
        #ifdef TAGLIBWITHASFPICTURE
        if ((ASFFile.tag())&&(ASFFile.tag()->attributeListMap().contains("WM/Picture"))) {
            const TagLib::ASF::AttributeList &attrList=ASFFile.tag()->attributeListMap()["WM/Picture"];
            if (!attrList.isEmpty()) {
                    TagLib::ASF::Picture pic = attrList[0].toPicture();
                    if (pic.isValid()) Image->loadFromData((const uchar *)pic.picture().data(),pic.picture().size());
            }
        }
        #endif
    }
    #endif
    //***********
    if (!Image->isNull()) return Image; else {
        delete Image;
        return NULL;
    }
}

//*********************************************************************************************************************************************
// Base class object
//*********************************************************************************************************************************************

cBaseMediaFile::cBaseMediaFile(cBaseApplicationConfig *TheApplicationConfig):cCustomIcon() {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cBaseMediaFile::cBaseMediaFile");

    ApplicationConfig   = TheApplicationConfig;
    Reset();
}

void cBaseMediaFile::Reset() {
    ObjectType          = OBJECTTYPE_UNMANAGED;
    IsValide            = false;                                    // if true then object if initialise
    IsInformationValide = false;                                    // if true then information list if fuly initialise
    ObjectGeometry      = IMAGE_GEOMETRY_UNKNOWN;                   // Image geometry
    FileName            = "";                                       // filename
    FileExtension       = "";
    ShortName           = "";
    FileSize            = 0;
    FileSizeText        = "";
    ImageWidth          = 0;                                        // Widht of normal image
    ImageHeight         = 0;                                        // Height of normal image
    CreatDateTime       = QDateTime(QDate(0,0,0),QTime(0,0,0));     // Original date/time
    ModifDateTime       = QDateTime(QDate(0,0,0),QTime(0,0,0));     // Last modified date/time
    AspectRatio         = 1;
    ImageOrientation    = -1;
}

//====================================================================================================================

cBaseMediaFile::~cBaseMediaFile() {
    ToLog(LOGMSG_DEBUGTRACE,QString("IN:cBaseMediaFile::~cBaseMediaFile for object %1").arg(FileName));
}

//====================================================================================================================

bool cBaseMediaFile::GetInformationFromFile(QString GivenFileName,QStringList *AliasList,bool *ModifyFlag) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cBaseMediaFile::GetInformationFromFile");

    FileName=QFileInfo(GivenFileName).absoluteFilePath();

    if (ModifyFlag) *ModifyFlag=false;

    // Use aliaslist
    if ((AliasList)&&(!QFileInfo(FileName).exists())) {
        // First test : seach for a new path+filename for this filename
        int i;
        for (i=0;(i<AliasList->count())&&(!AliasList->at(i).startsWith(FileName));i++);
        if ((i<AliasList->count())&&(AliasList->at(i).startsWith(FileName))) {
            FileName=AliasList->at(i);
            if (FileName.indexOf("####")>0) FileName=FileName.mid(FileName.indexOf("####")+QString("####").length());
        } else {
            // Second test : use each remplacement folder to try to find find
            i=0;
            QString NewFileName=QFileInfo(GivenFileName).absoluteFilePath();
            while ((i<AliasList->count())&&(!QFileInfo(NewFileName).exists())) {
                QString OldName=AliasList->at(i);
                QString NewName=OldName.mid(OldName.indexOf("####")+QString("####").length());
                OldName=OldName.left(OldName.indexOf("####"));
                OldName=OldName.left(OldName.lastIndexOf(QDir::separator()));
                NewName=NewName.left(NewName.lastIndexOf(QDir::separator()));
                NewFileName=NewName+QDir::separator()+QFileInfo(GivenFileName).fileName();
                i++;
            }
            if (QFileInfo(NewFileName).exists()) {
                FileName=NewFileName;
                if (AliasList) AliasList->append(FileName+"####"+NewFileName);
                if (ApplicationConfig->RememberLastDirectories) ApplicationConfig->LastMediaPath=QFileInfo(FileName).absolutePath();     // Keep folder for next use
                if (ModifyFlag) *ModifyFlag=true;
            }
        }
    }

    bool Continue=true;
    while ((Continue)&&(!QFileInfo(FileName).exists())) {
        QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
        if (CustomMessageBox(ApplicationConfig->TopLevelWindow,QMessageBox::Question,QApplication::translate("cBaseMediaFile","Open file"),
            QApplication::translate("cBaseMediaFile","Impossible to open file ")+FileName+"\n"+QApplication::translate("cBaseMediaFile","Do you want to select another file ?"),
            QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes)!=QMessageBox::Yes)
            Continue=false;
        else {
            QString NewFileName=QFileDialog::getOpenFileName(ApplicationConfig->TopLevelWindow,QApplication::translate("cBaseMediaFile","Select another file for ")+QFileInfo(FileName).fileName(),
               ApplicationConfig->RememberLastDirectories?ApplicationConfig->LastMediaPath:"",
               ApplicationConfig->GetFilterForMediaFile(ObjectType==OBJECTTYPE_IMAGEFILE?cBaseApplicationConfig::IMAGEFILE:ObjectType==OBJECTTYPE_VIDEOFILE?cBaseApplicationConfig::VIDEOFILE:cBaseApplicationConfig::MUSICFILE));
            if (NewFileName!="") {
                if (AliasList) AliasList->append(FileName+"####"+NewFileName);
                FileName=NewFileName;
                if (ApplicationConfig->RememberLastDirectories) ApplicationConfig->LastMediaPath=QFileInfo(FileName).absolutePath();     // Keep folder for next use
                if (ModifyFlag) *ModifyFlag=true;
            } else Continue=false;
        }
        QApplication::restoreOverrideCursor();
    }
    if (!Continue) {
        ToLog(LOGMSG_CRITICAL,QApplication::translate("cBaseMediaFile","Impossible to open file %1").arg(FileName));
        ShortName=QFileInfo(FileName).fileName();
        return false;
    }

    ShortName    =QFileInfo(FileName).fileName();
    FileExtension=QFileInfo(FileName).completeSuffix().toLower();
    FileSize     =QFileInfo(FileName).size();
    FileSizeText =GetTextSize(FileSize);
    ModifDateTime=QFileInfo(FileName).lastModified();
    CreatDateTime=QFileInfo(FileName).created();

    IsValide=true;

    return IsValide;
}

//====================================================================================================================

QString cBaseMediaFile::GetInformationValue(QString ValueToSearch) {
    //ToLog(LOGMSG_DEBUGTRACE,"IN:cBaseMediaFile::GetInformationValue");    // Remove: to much

    int i=0;
    while ((i<InformationList.count())&&(!((QString )InformationList[i]).startsWith(ValueToSearch+"##"))) i++;
    if ((i<InformationList.count())&&(((QString )InformationList[i]).startsWith(ValueToSearch))) {
        QStringList Values=((QString)InformationList[i]).split("##");
        if (Values.count()==2) return ((QString)Values[1]).trimmed();
    }
    return "";
}

//====================================================================================================================

QString cBaseMediaFile::GetImageGeometryStr() {
    //ToLog(LOGMSG_DEBUGTRACE,"IN:cBaseMediaFile::GetImageGeometryStr");    // Remove: to much

    switch (ObjectGeometry) {
        case IMAGE_GEOMETRY_3_2     : return "3:2";
        case IMAGE_GEOMETRY_2_3     : return "2:3";
        case IMAGE_GEOMETRY_4_3     : return "4:3";
        case IMAGE_GEOMETRY_3_4     : return "3:4";
        case IMAGE_GEOMETRY_16_9    : return "16:9";
        case IMAGE_GEOMETRY_9_16    : return "9:16";
        case IMAGE_GEOMETRY_40_17   : return "40:17";
        case IMAGE_GEOMETRY_17_40   : return "17:40";
        default                     : return "";        //QApplication::translate("cBaseMediaFile","ns","Non standard image geometry");
    }
}

//====================================================================================================================

QString cBaseMediaFile::GetFileSizeStr() {
    //ToLog(LOGMSG_DEBUGTRACE,"IN:cBaseMediaFile::GetFileSizeStr");         // Remove: to much

    return FileSizeText;
}

//====================================================================================================================

QString cBaseMediaFile::GetFileDateTimeStr(bool Created) {
    //ToLog(LOGMSG_DEBUGTRACE,"IN:cBaseMediaFile::GetFileDateTimeStr");     // Remove: to much

    if (Created) return CreatDateTime.toString("dd/MM/yyyy hh:mm:ss");
        else return ModifDateTime.toString("dd/MM/yyyy hh:mm:ss");
}

//====================================================================================================================

QString cBaseMediaFile::GetImageSizeStr(ImageSizeFmt Fmt) {
    //ToLog(LOGMSG_DEBUGTRACE,"IN:cBaseMediaFile::GetImageSizeStr");        // Remove: to much

    QString SizeInfo="";
    QString FmtInfo ="";
    QString GeoInfo ="";

    if ((ImageWidth>0)&&(ImageHeight>0)) {
        // Compute MPix
        double MPix=double(double(ImageWidth)*double(ImageHeight))/double(1000000);
        int    RealImageWidth=ImageWidth;
        if (AspectRatio!=1) RealImageWidth=int(double(ImageWidth)/AspectRatio);
        SizeInfo=QString("%1x%2").arg(RealImageWidth).arg(ImageHeight);

        // now search if size is referenced in DefImageFormat
        for (int i=0;i<2;i++) for (int j=0;j<3;j++) for (int k=0;k<NBR_SIZEDEF;k++) if ((DefImageFormat[i][j][k].Width==RealImageWidth)&&(DefImageFormat[i][j][k].Height==ImageHeight)) {
            FmtInfo=QString(DefImageFormat[i][j][k].Name).left(QString(DefImageFormat[i][j][k].Name).indexOf(" -"));
            break;
        }
        if ((FmtInfo=="")&&(MPix>=1)) FmtInfo=QString("%1").arg(MPix,8,'f',1).trimmed()+QApplication::translate("cBaseMediaFile","MPix");
        else switch (ImageHeight) {
            case 240:   FmtInfo="QVGA";     break;
            case 320:   FmtInfo="HVGA";     break;
            case 480:   FmtInfo="WVGA";     break;
            case 576:   FmtInfo="DVD";      break;
            case 600:   FmtInfo="SVGA";     break;
            case 720:   FmtInfo="720p";     break;
            case 768:   FmtInfo="XGA";      break;
            case 1080:  FmtInfo="1080p";    break;
            default:    FmtInfo="ns";       break;
        }
    }
    GeoInfo=GetImageGeometryStr();
    switch (Fmt) {
        case FULLWEB  : return SizeInfo+((FmtInfo+GeoInfo)!=""?"("+FmtInfo+(FmtInfo!=""?"-":"")+GeoInfo+")":"");
        case SIZEONLY : return SizeInfo;
        case FMTONLY  : return FmtInfo;
        case GEOONLY  : return GeoInfo;
        default       : return "";
    }
}

//====================================================================================================================

QString cBaseMediaFile::GetCumulInfoStr(QString Key1,QString Key2) {
    //ToLog(LOGMSG_DEBUGTRACE,"IN:cBaseMediaFile::GetCumulInfoStr");        // Remove: to much

    int     Num     =0;
    QString TrackNum="";
    QString Value   ="";
    QString Info    ="";
    do {
        TrackNum=QString("%1").arg(Num);
        while (TrackNum.length()<3) TrackNum="0"+TrackNum;
        TrackNum=Key1+"_"+TrackNum+":";
        Value=GetInformationValue(TrackNum+Key2);
        if (Value!="") Info=Info+((Num>0)?",":"")+Value;
        // Next
        Num++;
    } while (Value!="");
    return Info;
}

//*********************************************************************************************************************************************
// Unmanaged File
//*********************************************************************************************************************************************

cUnmanagedFile::cUnmanagedFile(cBaseApplicationConfig *ApplicationConfig):cBaseMediaFile(ApplicationConfig) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cUnmanagedFile::cUnmanagedFile");

    LoadIcons(&ApplicationConfig->DefaultFILEIcon);
    ObjectType  =OBJECTTYPE_UNMANAGED;
    IsInformationValide=true;
}

//====================================================================================================================

bool cUnmanagedFile::GetInformationFromFile(QString GivenFileName,QStringList *,bool *) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cUnmanagedFile::GetInformationFromFile");

    FileName            =QFileInfo(GivenFileName).absoluteFilePath();
    ShortName           =QFileInfo(FileName).fileName();

    if (!QFileInfo(FileName).exists()) {
        ToLog(LOGMSG_CRITICAL,QApplication::translate("cBaseMediaFile","Impossible to open file %1").arg(FileName));
        IsValide=false;
    } else {
        FileSize            =QFileInfo(FileName).size();
        FileSizeText        =GetTextSize(FileSize);
        CreatDateTime       =QFileInfo(FileName).lastModified();       // Keep date/time file was created by the camera !
        ModifDateTime       =QFileInfo(FileName).created();            // Keep date/time file was created on the computer !

        IsValide=true;
    }

    return IsValide;
}

//====================================================================================================================

QString cUnmanagedFile::GetFileTypeStr() {
    ToLog(LOGMSG_DEBUGTRACE,QString("IN:cUnmanagedFile::GetFileTypeStr for %1").arg(FileName));

    return QApplication::translate("cBaseMediaFile","Unmanaged","File type");
}

//====================================================================================================================

bool cUnmanagedFile::IsFilteredFile(int RequireObjectType) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cUnmanagedFile::IsFilteredFile");

    return RequireObjectType==OBJECTTYPE_UNMANAGED;
}

//*********************************************************************************************************************************************
// Folder
//*********************************************************************************************************************************************

cFolder::cFolder(cBaseApplicationConfig *ApplicationConfig):cBaseMediaFile(ApplicationConfig) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cFolder::cFolder");

    ObjectType  =OBJECTTYPE_FOLDER;
}

//====================================================================================================================

bool cFolder::GetInformationFromFile(QString GivenFileName,QStringList * /*AliasList*/,bool * /*ModifyFlag*/) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cFolder::GetInformationFromFile");

    FileName            =QFileInfo(GivenFileName).absoluteFilePath();
    ShortName           =QFileInfo(GivenFileName).fileName();
    CreatDateTime       =QFileInfo(FileName).lastModified();       // Keep date/time file was created by the camera !
    ModifDateTime       =QFileInfo(FileName).created();            // Keep date/time file was created on the computer !
    return true;
}

//====================================================================================================================

bool cFolder::IsFilteredFile(int) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cFolder::IsFilteredFile");

    return true;    // always valide
}

//====================================================================================================================

void cFolder::GetFullInformationFromFile() {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cFolder::GetFullInformationFromFile");

    IsInformationValide=true;

    QString AdjustedFileName=FileName;  if (!AdjustedFileName.endsWith(QDir::separator())) AdjustedFileName=AdjustedFileName+QDir::separator();

    // Check if a folder.jpg file exist
    if (Icon16.isNull()) {
        QFileInfoList Directorys=QDir(FileName).entryInfoList(QDir::Files);
        for (int j=0;j<Directorys.count();j++) if (Directorys[j].fileName().toLower()=="folder.jpg") {
            QString FileName=AdjustedFileName+Directorys[j].fileName();
            QImage Final(":img/FolderMask_200.png");
            QImage Img(FileName);
            QImage ImgF;
            if (double(Img.height())/double(Img.width())*double(Img.width())<=162) ImgF=Img.scaledToWidth(180,Qt::SmoothTransformation);
                else ImgF=Img.scaledToHeight(162,Qt::SmoothTransformation);
            QPainter Painter;
            Painter.begin(&Final);
            Painter.drawImage(QRect((Final.width()-ImgF.width())/2,195-ImgF.height(),ImgF.width(),ImgF.height()),ImgF);
            Painter.end();
            LoadIcons(&Final);
        }
    }

    // Check if there is an desktop.ini ==========> WINDOWS EXTENSION
    if (Icon16.isNull()) {
        QFileInfoList Directorys=QDir(FileName).entryInfoList(QDir::Files|QDir::Hidden);
        for (int j=0;j<Directorys.count();j++) if (Directorys[j].fileName().toLower()=="desktop.ini") {
            QFile   FileIO(AdjustedFileName+Directorys[j].fileName());
            QString IconFile ="";
            #ifdef Q_OS_WIN
            int     IconIndex=0;
            #endif
            if (FileIO.open(QIODevice::ReadOnly/*|QIODevice::Text*/)) {
                // Sometimes this kind of files have incorrect line terminator : nor \r\n nor \n
                QTextStream FileST(&FileIO);
                QString     AllInfo=FileST.readAll();
                QString     Line="";
                while (AllInfo!="") {
                    int j=0;
                    while ((j<AllInfo.length())&&((AllInfo[j]>=char(32))||(AllInfo[j]==9))) j++;
                    if (j<AllInfo.length()) {
                        Line=AllInfo.left(j);
                        while ((j<AllInfo.length())&&(AllInfo[j]<=char(32))) j++;
                        if (j<AllInfo.length()) AllInfo=AllInfo.mid(j); else AllInfo="";
                    } else {
                        Line=AllInfo;
                        AllInfo="";
                    }
                    #ifdef Q_OS_WIN
                    if ((Line.toUpper().startsWith("ICONINDEX"))&&(Line.indexOf("=")!=-1)) {
                        IconIndex=Line.mid(Line.indexOf("=")+1).toInt();
                    } else
                    #endif
                    if ((Line.toUpper().startsWith("ICONFILE"))&&(Line.indexOf("=")!=-1)) {
                        Line=Line.mid(Line.indexOf("=")+1).trimmed();
                        // Replace all variables like %systemroot%
                        while (Line.indexOf("%")!=-1) {
                            QString Var=Line.mid(Line.indexOf("%")+1);  Var=Var.left(Var.indexOf("%"));
                            QString Value=getenv(Var.toLocal8Bit());
                            Line.replace("%"+Var+"%",Value,Qt::CaseInsensitive);
                        }
                        if (QFileInfo(Line).isRelative()) IconFile=AdjustDirForOS(AdjustedFileName+Line);
                            else IconFile=AdjustDirForOS(QFileInfo(Line).absoluteFilePath());
                    }
                }
                FileIO.close();
            }
            if (IconFile.toLower().endsWith(".jpg") || IconFile.toLower().endsWith(".png") || IconFile.toLower().endsWith(".ico")) LoadIcons(IconFile);
            #ifdef Q_OS_WIN
            else LoadIcons(GetIconForFileOrDir(IconFile,IconIndex));
            #endif
        }
    }

    // if no icon then load default for type
    if (Icon16.isNull()) LoadIcons(&ApplicationConfig->DefaultFOLDERIcon);
}

//====================================================================================================================

QString cFolder::GetFileTypeStr() {
    ToLog(LOGMSG_DEBUGTRACE,QString("IN:cFolder::GetFileTypeStr for %1").arg(FileName));

    return QApplication::translate("cBaseMediaFile","Folder","File type");
}

//*********************************************************************************************************************************************
// ffDiaporama project file
//*********************************************************************************************************************************************

cffDProjectFile::cffDProjectFile(cBaseApplicationConfig *ApplicationConfig):cBaseMediaFile(ApplicationConfig) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cffDProjectFile::cffDProjectFile");

    LoadIcons(&ApplicationConfig->DefaultFFDIcon);
    ObjectType      =OBJECTTYPE_FFDFILE;
    Title           ="";
    Author          ="";
    Album           ="";
    Year            =QDate::currentDate().year();
    Comment         ="";
    Composer        ="";
    Duration        =0;
    NbrSlide        =0;
    ffDRevision     ="";
    DefaultLanguage ="und";
    NbrChapters     =0;
}

//====================================================================================================================

bool cffDProjectFile::GetInformationFromFile(QString GivenFileName,QStringList * /*AliasList*/,bool * /*ModifyFlag*/) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cffDProjectFile::GetInformationFromFile");

    FileName            =QFileInfo(GivenFileName).absoluteFilePath();
    ShortName           =QFileInfo(GivenFileName).fileName();
    FileSize            =QFileInfo(GivenFileName).size();
    FileSizeText        =GetTextSize(FileSize);
    CreatDateTime       =QFileInfo(FileName).lastModified();       // Keep date/time file was created by the camera !
    ModifDateTime       =QFileInfo(FileName).created();            // Keep date/time file was created on the computer !
    LoadIcons(&ApplicationConfig->DefaultFFDIcon);
    return true;
}

//====================================================================================================================

void cffDProjectFile::SaveToXML(QDomElement &domDocument) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cffDProjectFile::SaveToXML");

    QDomDocument    DomDocument;
    QDomElement     Element=DomDocument.createElement("ffDiaporamaProjectProperties");
    Element.setAttribute("Title",Title);
    Element.setAttribute("Author",Author);
    Element.setAttribute("Album",Album);
    Element.setAttribute("Year",Year);
    Element.setAttribute("Comment",Comment);
    Element.setAttribute("Composer",Composer);
    Element.setAttribute("Duration",Duration);
    Element.setAttribute("ffDRevision",ffDRevision);
    Element.setAttribute("DefaultLanguage",DefaultLanguage);
    Element.setAttribute("ChaptersNumber",NbrChapters);
    for (int i=0;i<NbrChapters;i++) {
        QString     ChapterNum=QString("%1").arg(i); while (ChapterNum.length()<3) ChapterNum="0"+ChapterNum;
        QDomElement SubElement=DomDocument.createElement("Chapter_"+ChapterNum);
        SubElement.setAttribute("Start",GetInformationValue("Chapter_"+ChapterNum+":Start"));
        SubElement.setAttribute("End",GetInformationValue("Chapter_"+ChapterNum+":End"));
        SubElement.setAttribute("Duration",GetInformationValue("Chapter_"+ChapterNum+":Duration"));
        SubElement.setAttribute("title",GetInformationValue("Chapter_"+ChapterNum+":title"));
        SubElement.setAttribute("InSlide",GetInformationValue("Chapter_"+ChapterNum+":InSlide"));
        Element.appendChild(SubElement);
    }
    domDocument.appendChild(Element);
}

//====================================================================================================================

bool cffDProjectFile::LoadFromXML(QDomElement domDocument) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cffDProjectFile::LoadFromXML");

    bool IsOk=false;
    if ((domDocument.elementsByTagName("ffDiaporamaProjectProperties").length()>0)&&(domDocument.elementsByTagName("ffDiaporamaProjectProperties").item(0).isElement()==true)) {
        QDomElement Element=domDocument.elementsByTagName("ffDiaporamaProjectProperties").item(0).toElement();
        if (Element.hasAttribute("Title")) {
            Title   =Element.attribute("Title");
            InformationList.append(QString("title")+QString("##")+QString(Title));
        }
        if (Element.hasAttribute("Author")) {
            Author  =Element.attribute("Author");
            InformationList.append(QString("artist")+QString("##")+QString(Author));
        }
        if (Element.hasAttribute("Album")) {
            Album   =Element.attribute("Album");
            InformationList.append(QString("album")+QString("##")+QString(Album));
        }
        if (Element.hasAttribute("Year")) {
            Year    =Element.attribute("Year").toInt();
            InformationList.append(QString("date")+QString("##")+QString("%1").arg(Year));
        }
        if (Element.hasAttribute("Comment")) {
            Comment =Element.attribute("Comment");
            InformationList.append(QString("comment")+QString("##")+QString(Comment));
        }
        if (Element.hasAttribute("ffDRevision")) {
            ffDRevision=Element.attribute("ffDRevision");
            InformationList.append(QString("ffDRevision")+QString("##")+QString(ffDRevision));
        }
        if (Element.hasAttribute("Composer")) {
            Composer=Element.attribute("Composer");
            InformationList.append(QString("composer")+QString("##")+QString(Composer));
        }
        if (Element.hasAttribute("DefaultLanguage")) {
            DefaultLanguage=Element.attribute("DefaultLanguage");
            InformationList.append(QString("Audio_000:language")+QString("##")+QString(DefaultLanguage));
        }
        if (Element.hasAttribute("Duration")) {
            Duration=Element.attribute("Duration").toLongLong();
            if (Duration!=0) {
                int     TimeMSec    =Duration-(Duration/1000)*1000;
                int     TimeSec     =int(Duration/1000);
                int     TimeHour    =TimeSec/(60*60);
                int     TimeMinute  =(TimeSec%(60*60))/60;
                QTime   tDuration;
                tDuration.setHMS(TimeHour,TimeMinute,TimeSec%60,TimeMSec);
                InformationList.append(QString("Duration")+QString("##")+tDuration.toString("HH:mm:ss.zzz"));
            }
        }
        if (Element.hasAttribute("ChaptersNumber")) {
            NbrChapters=Element.attribute("ChaptersNumber").toInt();
            for (int i=0;i<NbrChapters;i++) {
                QString     ChapterNum=QString("%1").arg(i); while (ChapterNum.length()<3) ChapterNum="0"+ChapterNum;
                if ((domDocument.elementsByTagName("Chapter_"+ChapterNum).length()>0)&&(domDocument.elementsByTagName("Chapter_"+ChapterNum).item(0).isElement()==true)) {
                    QDomElement SubElement=domDocument.elementsByTagName("Chapter_"+ChapterNum).item(0).toElement();
                    QString     Start="";
                    QString     End="";
                    QString     Duration="";
                    QString     Title="";
                    QString     InSlide="";
                    if (SubElement.hasAttribute("Start"))       Start=SubElement.attribute("Start");
                    if (SubElement.hasAttribute("End"))         End=SubElement.attribute("End");
                    if (SubElement.hasAttribute("Duration"))    Duration=SubElement.attribute("Duration");
                    if (SubElement.hasAttribute("title"))       Title=SubElement.attribute("title");
                    if (SubElement.hasAttribute("InSlide"))     InSlide=SubElement.attribute("InSlide");

                    InformationList.append("Chapter_"+ChapterNum+":Start"   +QString("##")+Start);
                    InformationList.append("Chapter_"+ChapterNum+":End"     +QString("##")+End);
                    InformationList.append("Chapter_"+ChapterNum+":Duration"+QString("##")+Duration);
                    InformationList.append("Chapter_"+ChapterNum+":title"   +QString("##")+Title);
                    InformationList.append("Chapter_"+ChapterNum+":InSlide" +QString("##")+InSlide);
                }
            }
        }
        IsOk=true;
    }
    if ((domDocument.elementsByTagName("Project").length()>0)&&(domDocument.elementsByTagName("Project").item(0).isElement()==true)) {
        QDomElement Element=domDocument.elementsByTagName("Project").item(0).toElement();
        if (Element.hasAttribute("ImageGeometry")) {
            switch (Element.attribute("ImageGeometry").toInt()) {
                case GEOMETRY_16_9:  ObjectGeometry=IMAGE_GEOMETRY_16_9;   break;
                case GEOMETRY_40_17: ObjectGeometry=IMAGE_GEOMETRY_40_17;  break;
                case GEOMETRY_4_3:
                default:             ObjectGeometry=IMAGE_GEOMETRY_4_3;    break;
            }
        }
        if (Element.hasAttribute("ObjectNumber")) {
            NbrSlide=Element.attribute("ObjectNumber").toInt();
            InformationList.append(QApplication::translate("cBaseMediaFile","Slide number")+QString("##%1").arg(NbrSlide));
        }
    }
    return IsOk;
}

//====================================================================================================================

void cffDProjectFile::GetFullInformationFromFile() {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cffDProjectFile::GetFullInformationFromFile");

    QFile           file(FileName);
    QDomDocument    domDocument;
    QDomElement     root;
    QString         errorStr;
    int             errorLine,errorColumn;
    if (file.open(QFile::ReadOnly | QFile::Text)) {
        if (domDocument.setContent(&file, true, &errorStr, &errorLine,&errorColumn)) {
            root = domDocument.documentElement();
            // Load project properties
            if (root.tagName()==FFD_APPLICATION_ROOTNAME) LoadFromXML(root);
        }
        file.close();
    }
    IsInformationValide=true;
}

//====================================================================================================================

QString cffDProjectFile::GetTechInfo() {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cffDProjectFile::GetTechInfo");

    QString Info="";
    if (Composer!="")   Info=Info+(Info!=""?" - ":"")+Composer+" ("+ffDRevision+")";
    if (GetImageSizeStr(cBaseMediaFile::GEOONLY)!="")   Info=Info+(Info!=""?" - ":"")+GetImageSizeStr(cBaseMediaFile::GEOONLY);
    if (NbrSlide>0)                                     Info=Info+(Info!=""?" - ":"")+QString("%1").arg(NbrSlide)   +" "+QApplication::translate("cBaseMediaFile","Slides");
    if (NbrChapters>0)                                  Info=Info+(Info!=""?" - ":"")+QString("%1").arg(NbrChapters)+" "+QApplication::translate("cBaseMediaFile","Chapters");
    return Info;
}

//====================================================================================================================

QString cffDProjectFile::GetTAGInfo() {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cffDProjectFile::GetTechInfo");

    QString Info=Title;
    if (Album!="")      Info=Info+(Info!=""?" - ":"")+Album;
    if (Info!="")       Info=Info+(Info!=""?" - ":"")+QString("%1").arg(Year);
    if (Author!="")     Info=Info+(Info!=""?" - ":"")+Author;
    return Info;
}

//====================================================================================================================

bool cffDProjectFile::IsFilteredFile(int RequireObjectType) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cffDProjectFile::IsFilteredFile");

    return (RequireObjectType==OBJECTTYPE_UNMANAGED)||(RequireObjectType==OBJECTTYPE_MANAGED)||(RequireObjectType==OBJECTTYPE_FFDFILE);
}

//====================================================================================================================

QString cffDProjectFile::GetFileTypeStr() {
    ToLog(LOGMSG_DEBUGTRACE,QString("IN:cffDProjectFile::GetFileTypeStr for %1").arg(FileName));

    return QApplication::translate("cBaseMediaFile","ffDiaporama","File type");
}

//*********************************************************************************************************************************************
// Image file
//*********************************************************************************************************************************************

cImageFile::cImageFile(cBaseApplicationConfig *ApplicationConfig):cBaseMediaFile(ApplicationConfig) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cImageFile::cImageFile");

    ObjectType  =OBJECTTYPE_IMAGEFILE;  // coul be turn later to OBJECTTYPE_THUMBNAIL
}

//====================================================================================================================

bool cImageFile::IsFilteredFile(int RequireObjectType) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cImageFile::IsFilteredFile");
    if (FileName.endsWith("_ffd.jpg",Qt::CaseInsensitive)) return (RequireObjectType==OBJECTTYPE_UNMANAGED);
        else if (ObjectType==OBJECTTYPE_IMAGEFILE) return (RequireObjectType==OBJECTTYPE_UNMANAGED)||(RequireObjectType==OBJECTTYPE_MANAGED)||(RequireObjectType==OBJECTTYPE_IMAGEFILE);
        else return (RequireObjectType==OBJECTTYPE_UNMANAGED);
}

//====================================================================================================================

QString cImageFile::GetFileTypeStr() {
    ToLog(LOGMSG_DEBUGTRACE,QString("IN:cImageFile::GetFileTypeStr for %1").arg(FileName));

    if (ObjectType==OBJECTTYPE_IMAGEFILE) return QApplication::translate("cBaseMediaFile","Image","File type");
        else return QApplication::translate("cBaseMediaFile","Thumbnail","File type");
}

//====================================================================================================================

void cImageFile::GetFullInformationFromFile() {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cImageFile::GetFullInformationFromFile");

    ImageOrientation    =-1;
    IsInformationValide =false;
    bool ExifOk=false;

    // ******************************************************************************************************
    // Try to load EXIF information using library exiv2
    // ******************************************************************************************************
    Exiv2::Image::AutoPtr ImageFile;
    try {
        #ifdef Q_OS_WIN
            ImageFile=Exiv2::ImageFactory::open(FileName.toLocal8Bit().data());
        #else
            ImageFile=Exiv2::ImageFactory::open(FileName.toUtf8().data());
        #endif
        ExifOk=true;
    }
    catch( Exiv2::Error& /*e*/ ) {
        ToLog(LOGMSG_INFORMATION,QApplication::translate("cBaseMediaFile","Image don't have EXIF metadata %1").arg(FileName));
    }
    if (ExifOk) {
        ImageFile->readMetadata();
        // Read data
        Exiv2::ExifData &exifData = ImageFile->exifData();
        if (!exifData.empty()) {
            Exiv2::ExifData::const_iterator end = exifData.end();
            for (Exiv2::ExifData::const_iterator CurrentData=exifData.begin();CurrentData!=end;++CurrentData) {

                if ((QString().fromStdString(CurrentData->key())=="Exif.Image.Orientation")&&(CurrentData->tag()==274))
                    ImageOrientation=QString().fromStdString(CurrentData->value().toString()).toInt();

                if ((CurrentData->typeId()!=Exiv2::undefined)&&
                    (!(((CurrentData->typeId()==Exiv2::unsignedByte)||(CurrentData->typeId()==Exiv2::signedByte))&&(CurrentData->size()>64)))) {
                    QString Key  =QString().fromStdString(CurrentData->key());
                    #ifdef Q_OS_WIN
                    QString Value=QString().fromStdString(CurrentData->print(&exifData).c_str());
                    #else
                    QString Value=QString().fromUtf8(CurrentData->print(&exifData).c_str());
                    #endif
                    if (Key.startsWith("Exif.")) Key=Key.mid(QString("Exif.").length());
                    InformationList.append(Key+QString("##")+Value);
                }
            }
        }

        // Append InformationList
        if (GetInformationValue("Image.Artist")!="") InformationList.append(QString("artist")+QString("##")+GetInformationValue("Image.Artist"));
        if (GetInformationValue("Image.Model")!="")  {
            if (GetInformationValue("Image.Model").contains(GetInformationValue("Image.Make"),Qt::CaseInsensitive)) InformationList.append(QString("composer")+QString("##")+GetInformationValue("Image.Model"));
                else InformationList.append(QString("composer")+QString("##")+GetInformationValue("Image.Make")+" "+GetInformationValue("Image.Model"));
        }
        // Get size information
        ImageWidth =ImageFile->pixelWidth();
        ImageHeight=ImageFile->pixelHeight();
        /*if (GetInformationValue("Photo.PixelXDimension")!="")       ImageWidth =GetInformationValue("Photo.PixelXDimension").toInt();
            else if (GetInformationValue("Image.ImageWidth")!="")   ImageWidth =GetInformationValue("Image.ImageWidth").toInt();            // TIFF Version
        if (GetInformationValue("Photo.PixelYDimension")!="")       ImageHeight=GetInformationValue("Photo.PixelYDimension").toInt();
            else if (GetInformationValue("Image.ImageLength")!="")  ImageHeight=GetInformationValue("Image.ImageLength").toInt();           // TIFF Version
        */
        // switch ImageWidth and ImageHeight if image was rotated
        if ((ImageOrientation==6)||(ImageOrientation==8)) {
            int IW=ImageWidth;
            ImageWidth=ImageHeight;
            ImageHeight=IW;
        }

        // Read preview image
        #ifdef EXIV2WITHPREVIEW
        if (IsIconNeeded) {
            Exiv2::PreviewManager *Manager=new Exiv2::PreviewManager(*ImageFile);
            if (Manager) {
                Exiv2::PreviewPropertiesList Properties=Manager->getPreviewProperties();
                if (!Properties.empty()) {
                    Exiv2::PreviewImage Image=Manager->getPreviewImage(Properties[Properties.size()-1]);      // Get the latest image (biggest)
                    QImage *Icon=new QImage();
                    if (Icon->loadFromData(QByteArray((const char*)Image.pData(),Image.size()))) {
                        if (ImageOrientation==8) {          // Rotating image anti-clockwise by 90 degrees...'
                            QMatrix matrix;
                            matrix.rotate(-90);
                            QImage *NewImage=new QImage(Icon->transformed(matrix,Qt::SmoothTransformation));
                            delete Icon;
                            Icon=NewImage;
                        } else if (ImageOrientation==3) {   // Rotating image clockwise by 180 degrees...'
                            QMatrix matrix;
                            matrix.rotate(180);
                            QImage *NewImage=new QImage(Icon->transformed(matrix,Qt::SmoothTransformation));
                            delete Icon;
                            Icon=NewImage;
                        } else if (ImageOrientation==6) {   // Rotating image clockwise by 90 degrees...'
                            QMatrix matrix;
                            matrix.rotate(90);
                            QImage *NewImage=new QImage(Icon->transformed(matrix,Qt::SmoothTransformation));
                            delete Icon;
                            Icon=NewImage;
                        }

                        // Sometimes, Icon have black bar : try to remove them
                        if ((double(Icon->width())/double(Icon->height()))!=(double(ImageWidth)/double(ImageHeight))) {
                            if (ImageWidth>ImageHeight) {
                                int RealHeight=int((double(Icon->width())*double(ImageHeight))/double(ImageWidth));
                                int Delta     =Icon->height()-RealHeight;
                                QImage *NewImage=new QImage(Icon->copy(0,Delta/2,Icon->width(),Icon->height()-Delta));
                                delete Icon;
                                Icon=NewImage;
                            } else {
                                int RealWidth=int((double(Icon->height())*double(ImageWidth))/double(ImageHeight));
                                int Delta     =Icon->width()-RealWidth;
                                QImage *NewImage=new QImage(Icon->copy(Delta/2,0,Icon->width()-Delta,Icon->height()));
                                delete Icon;
                                Icon=NewImage;
                            }
                        }

                        // if preview Icon have a really small size, then don't use it
                        if (Icon->height()>=ApplicationConfig->MinimumEXIFHeight) LoadIcons(Icon);
                    }
                    delete Icon;
                }
                delete Manager;
            }
        }
        #endif
    }

    //************************************************************************************
    // If no exif preview image (of image too small) then load/create thumbnail
    //************************************************************************************
    if ((IsIconNeeded)&&(Icon16.isNull())) {
        cLuLoImageCacheObject *ImageObject=ApplicationConfig->ImagesCache.FindObject(FileName,ModifDateTime,ImageOrientation,ApplicationConfig->Smoothing,true);
        if (ImageObject==NULL) {
            ToLog(LOGMSG_CRITICAL,"Error in cImageFile::GetFullInformationFromFile : FindObject return NULL for thumbnail creation !");
        } else {
            QImage *LN_Image=ImageObject->ValidateCacheRenderImage();   // Get a link to render image in LuLoImageCache collection
            if ((LN_Image==NULL)||(LN_Image->isNull())) {
                ToLog(LOGMSG_CRITICAL,"Error in cImageFile::GetFullInformationFromFile : ValidateCacheRenderImage return NULL for thumbnail creation !");
            } else {
                LoadIcons(LN_Image);
            }
        }
    }

    //************************************************************************************
    // if no information about size then load image
    //************************************************************************************
    if ((ImageWidth==0)||(ImageHeight==0)) {
        cLuLoImageCacheObject *ImageObject=ApplicationConfig->ImagesCache.FindObject(FileName,ModifDateTime,ImageOrientation,ApplicationConfig->Smoothing,true);
        if (ImageObject==NULL) {
            ToLog(LOGMSG_CRITICAL,"Error in cImageFile::GetFullInformationFromFile : FindObject return NULL for size computation !");
        } else {
            QImage *LN_Image=ImageObject->ValidateCacheRenderImage();   // Get a link to render image in LuLoImageCache collection
            if ((LN_Image==NULL)||(LN_Image->isNull())) {
                ToLog(LOGMSG_CRITICAL,"Error in cImageFile::GetFullInformationFromFile : ValidateCacheRenderImage return NULL for size computation !");
            } else {
                ImageWidth =LN_Image->width();
                ImageHeight=LN_Image->height();
                InformationList.append(QString("Photo.PixelXDimension")+QString("##")+QString("%1").arg(ImageWidth));
                InformationList.append(QString("Photo.PixelYDimension")+QString("##")+QString("%1").arg(ImageHeight));
                IsInformationValide=true;
            }
        }
    }

    //************************************************************************************
    // End process by computing some values ....
    //************************************************************************************

    // Sort InformationList
    InformationList.sort();

    // Now we have image size then compute image geometry
    ObjectGeometry=IMAGE_GEOMETRY_UNKNOWN;
    double RatioHW=double(ImageWidth)/double(ImageHeight);
    if ((RatioHW>=1.45)&&(RatioHW<=1.55))           ObjectGeometry=IMAGE_GEOMETRY_3_2;
    else if ((RatioHW>=0.65)&&(RatioHW<=0.67))      ObjectGeometry=IMAGE_GEOMETRY_2_3;
    else if ((RatioHW>=1.32)&&(RatioHW<=1.34))      ObjectGeometry=IMAGE_GEOMETRY_4_3;
    else if ((RatioHW>=0.74)&&(RatioHW<=0.76))      ObjectGeometry=IMAGE_GEOMETRY_3_4;
    else if ((RatioHW>=1.77)&&(RatioHW<=1.79))      ObjectGeometry=IMAGE_GEOMETRY_16_9;
    else if ((RatioHW>=0.56)&&(RatioHW<=0.58))      ObjectGeometry=IMAGE_GEOMETRY_9_16;
    else if ((RatioHW>=2.34)&&(RatioHW<=2.36))      ObjectGeometry=IMAGE_GEOMETRY_40_17;
    else if ((RatioHW>=0.42)&&(RatioHW<=0.44))      ObjectGeometry=IMAGE_GEOMETRY_17_40;

    // if Icon16 stil null then load default icon
    if ((IsIconNeeded)&&(Icon16.isNull())) LoadIcons(&ApplicationConfig->DefaultIMAGEIcon);

    IsInformationValide=true;
}

//====================================================================================================================

QString cImageFile::GetTechInfo() {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cImageFile::GetTechInfo");

    QString Info=GetImageSizeStr(FULLWEB);
    if (GetInformationValue("artist")!="")              Info=Info+(Info!=""?"-":"")+GetInformationValue("artist");
    if (GetInformationValue("composer")!="")            Info=Info+(Info!=""?"-":"")+GetInformationValue("composer");
    if (GetInformationValue("Image.Orientation")!="")   Info=Info+(Info!=""?"-":"")+GetInformationValue("Image.Orientation");
    return Info;
}

//====================================================================================================================

QString cImageFile::GetTAGInfo() {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cImageFile::GetTAGInfo");

    QString Info=GetInformationValue("Photo.ExposureTime");
    if (GetInformationValue("Photo.ApertureValue")!="")    Info=Info+(Info!=""?"-":"")+GetInformationValue("Photo.ApertureValue");
    if (GetInformationValue("Photo.ISOSpeedRatings")!="")  Info=Info+(Info!=""?"-":"")+GetInformationValue("Photo.ISOSpeedRatings")+" ISO";
    if (GetInformationValue("CanonCs.LensType")!="")       Info=Info+(Info!=""?"-":"")+GetInformationValue("CanonCs.LensType");                // Canon version
    if (GetInformationValue("NikonLd3.LensIDNumber")!="")  Info=Info+(Info!=""?"-":"")+GetInformationValue("NikonLd3.LensIDNumber");           // Nikon version
    if (GetInformationValue("Photo.Flash")!="")            Info=Info+(Info!=""?"-":"")+GetInformationValue("Photo.Flash");
    if (GetInformationValue("CanonCs.FlashMode")!="")      Info=Info+(Info!=""?"-":"")+GetInformationValue("CanonCs.FlashMode");               // Canon version
    if (GetInformationValue("Nikon3.FlashMode")!="")       Info=Info+(Info!=""?"-":"")+GetInformationValue("Nikon3.FlashMode");                // Nikon version
    return Info;
}

//====================================================================================================================

QImage *cImageFile::ImageAt(bool PreviewMode) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cImageFile::ImageAt");

    if (!IsValide)            return NULL;
    if (!IsInformationValide) GetFullInformationFromFile();

    QImage                *LN_Image   =NULL;
    QImage                *RetImage   =NULL;
    cLuLoImageCacheObject *ImageObject=ApplicationConfig->ImagesCache.FindObject(FileName,ModifDateTime,ImageOrientation,(!PreviewMode || ApplicationConfig->Smoothing),true);

    if (!ImageObject) {
        ToLog(LOGMSG_CRITICAL,"Error in cImageFile::ImageAt : FindObject return NULL !");
        return NULL;  // There is an error !!!!!
    }

    if (PreviewMode) LN_Image=ImageObject->ValidateCachePreviewImage();
        else         LN_Image=ImageObject->ValidateCacheRenderImage();

    if ((LN_Image==NULL)||(LN_Image->isNull())) {
        ToLog(LOGMSG_CRITICAL,"Error in cImageFile::ImageAt : ValidateCacheImage return NULL !");
    } else {
        RetImage=new QImage(LN_Image->copy());
        if ((RetImage==NULL)||(RetImage->isNull()))
            ToLog(LOGMSG_CRITICAL,"Error in cImageFile::ImageAt : LN_Image->copy() return NULL !");
    }

    // return wanted image
    return RetImage;
}

/*************************************************************************************************************************************
    CLASS cVideoFile
*************************************************************************************************************************************/

cImageInCache::cImageInCache(qlonglong Position,QImage *Image) {
    this->Position=Position;
    this->Image   =Image->copy();
}

cVideoFile::cVideoFile(int TheWantedObjectType,cBaseApplicationConfig *ApplicationConfig):cBaseMediaFile(ApplicationConfig) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::cVideoFile");
    Reset(TheWantedObjectType);
}

void cVideoFile::Reset(int TheWantedObjectType) {
    cBaseMediaFile::Reset();

    MusicOnly               = (TheWantedObjectType==OBJECTTYPE_MUSICFILE);
    ObjectType              = TheWantedObjectType;
    IsOpen                  = false;
    StartPos                = QTime(0,0,0,0);   // Start position
    EndPos                  = QTime(0,0,0,0);   // End position

    // Video part
    IsMTS                   = false;
    ffmpegVideoFile         = NULL;
    VideoDecoderCodec       = NULL;
    VideoStreamNumber       = 0;
    FrameBufferYUV          = NULL;
    FrameBufferYUVReady     = false;
    FrameBufferYUVPosition  = 0;
    dEndFileCachePos        = 0;                        // Position of the cache image of last image of the video
    VideoCodecInfo          = "";
    VideoTrackNbr           = 0;
    VideoStreamNumber       =-1;
    NbrChapters             = 0;

    // Audio part
    ffmpegAudioFile         = NULL;
    AudioDecoderCodec       = NULL;
    LastAudioReadedPosition =-1;
    IsVorbis                = false;
    AudioCodecInfo          = "";
    AudioTrackNbr           = 0;
    AudioStreamNumber       =-1;

    // Filter part
 #ifdef VIDEO_LIBAVFILTER
    VideoFilterGraph        =NULL;
    VideoFilterIn           =NULL;
    VideoFilterOut          =NULL;
#endif
#ifdef AUDIO_LIBAVFILTER
    AudioFilterGraph        =NULL;
    AudioFilterIn           =NULL;
    AudioFilterOut          =NULL;
#endif
}

//====================================================================================================================

cVideoFile::~cVideoFile() {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::~cVideoFile");

    // Close LibAVFormat and LibAVCodec contexte for the file
    CloseCodecAndFile();
}

//====================================================================================================================

// Overloaded function use to dertermine if media file correspond to WantedObjectType
//      WantedObjectType could be OBJECTTYPE_VIDEOFILE or OBJECTTYPE_MUSICFILE
//      if AudioOnly was set to true in constructor then ignore all video track and set WantedObjectType to OBJECTTYPE_MUSICFILE else set it to OBJECTTYPE_VIDEOFILE
//      return true if WantedObjectType=OBJECTTYPE_VIDEOFILE and at least one video track is present
//      return true if WantedObjectType=OBJECTTYPE_MUSICFILE and at least one audio track is present

void cVideoFile::GetFullInformationFromFile() {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::GetFullInformationFromFile");

    int64_t AVNOPTSVALUE=INT64_C(0x8000000000000000); // to solve type error with Qt

    AVFormatContext *ffmpegFile=NULL;
    bool            Continu=true;

    //*********************************************************************************************************
    // Open file and get a LibAVFormat context and an associated LibAVCodec decoder
    //*********************************************************************************************************
    if (avformat_open_input(&ffmpegFile,FileName.toLocal8Bit(),NULL,NULL)!=0) return;
    InformationList.append(QString("Short Format##")+QString(ffmpegFile->iformat->name));
    InformationList.append(QString("Long Format##")+QString(ffmpegFile->iformat->long_name));
    ffmpegFile->flags|=AVFMT_FLAG_GENPTS;       // Generate missing pts even if it requires parsing future NbrFrames.

    //*********************************************************************************************************
    // Search stream in file
    //*********************************************************************************************************
    #ifdef LIBAV_07
    if (av_find_stream_info(ffmpegFile)<0) {
        av_close_input_file(ffmpegFile);// deprecated : use avformat_find_stream_info instead
        Continu=false;
    }
    #else
    if (avformat_find_stream_info(ffmpegFile,NULL)<0) {
        avformat_close_input(&ffmpegFile);
        Continu=false;
    }
    #endif

    if (Continu) {
        //*********************************************************************************************************
        // Get metadata
        //*********************************************************************************************************
        AVDictionaryEntry *tag=NULL;
        while ((tag=av_dict_get(ffmpegFile->metadata,"",tag,AV_DICT_IGNORE_SUFFIX))) {
            QString Value=QString().fromUtf8(tag->value);
            #ifdef Q_OS_WIN
            Value.replace(char(13),"\n");
            #endif
            if (Value.endsWith("\n")) Value=Value.left(Value.lastIndexOf("\n"));
            InformationList.append(QString().fromUtf8(tag->key).toLower()+QString("##")+Value);
        }

        //*********************************************************************************************************
        // Get chapters
        //*********************************************************************************************************
        NbrChapters=ffmpegFile->nb_chapters;
        for (uint i=0;i<ffmpegFile->nb_chapters;i++) {
            AVChapter   *ch=ffmpegFile->chapters[i];
            QString     ChapterNum=QString("%1").arg(i);
            while (ChapterNum.length()<3) ChapterNum="0"+ChapterNum;
            qlonglong Start=double(ch->start)*(double(av_q2d(ch->time_base))*1000);    // Lib AV use 1/1 000 000 000 sec and we want msec !
            qlonglong End  =double(ch->end)*(double(av_q2d(ch->time_base))*1000);    // Lib AV use 1/1 000 000 000 sec and we want msec !
            InformationList.append("Chapter_"+ChapterNum+":Start"   +QString("##")+QTime(0,0,0,0).addMSecs(Start).toString("hh:mm:ss.zzz"));
            InformationList.append("Chapter_"+ChapterNum+":End"     +QString("##")+QTime(0,0,0,0).addMSecs(End).toString("hh:mm:ss.zzz"));
            InformationList.append("Chapter_"+ChapterNum+":Duration"+QString("##")+QTime(0,0,0,0).addMSecs(End-Start).toString("hh:mm:ss.zzz"));
            // Chapter metadata
            while ((tag=av_dict_get(ch->metadata,"",tag,AV_DICT_IGNORE_SUFFIX)))
                InformationList.append("Chapter_"+ChapterNum+":"+QString().fromUtf8(tag->key).toLower()+QString("##")+QString().fromUtf8(tag->value));
        }

        //*********************************************************************************************************
        // Get information about duration
        //*********************************************************************************************************
        int         hh,mm,ss;
        qlonglong   ms;

        ms=ffmpegFile->duration;
        /*if ((ms==AVNOPTSVALUE)&&(!MusicOnly)) {
            // Try to compute duration from video track
            for (int Track=0;Track<(int)ffmpegFile->nb_streams;Track++) {
                if (ffmpegFile->streams[Track]->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
                    AVStream *VideoStream=ffmpegFile->streams[Track];
                    ms=0;
                }
            }
        }*/
        if (ffmpegFile->start_time!=AVNOPTSVALUE)  {
            ms-=ffmpegFile->start_time;
            start_time=ffmpegFile->start_time;
        } else start_time=0;
        ms=ms/1000;

        ss=ms/1000;
        mm=ss/60;
        hh=mm/60;
        mm=mm-(hh*60);
        ss=ss-(ss/60)*60;
        ms=ms-(ms/1000)*1000;
        Duration=QTime(hh,mm,ss,ms);

        EndPos  =Duration;    // By default : EndPos is set to the end of file
        InformationList.append(QString("Duration")+QString("##")+Duration.toString("HH:mm:ss.zzz"));

        //*********************************************************************************************************
        // Get information from track
        //*********************************************************************************************************
        for (int Track=0;Track<(int)ffmpegFile->nb_streams;Track++) {

            // Find codec
            AVCodec *Codec=avcodec_find_decoder(ffmpegFile->streams[Track]->codec->codec_id);

            //*********************************************************************************************************
            // Audio track
            //*********************************************************************************************************
            if (ffmpegFile->streams[Track]->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
                // Keep this as default track
                if (AudioStreamNumber==-1) AudioStreamNumber=Track;

                // Compute TrackNum
                QString TrackNum=QString("%1").arg(AudioTrackNbr);
                while (TrackNum.length()<3) TrackNum="0"+TrackNum;
                TrackNum="Audio_"+TrackNum+":";

                // General
                InformationList.append(TrackNum+QString("Track")+QString("##")+QString("%1").arg(Track));
                if (Codec) InformationList.append(TrackNum+QString("Codec")+QString("##")+QString(Codec->name));

                // Channels
                QString SampleFMT="";
                switch (ffmpegFile->streams[Track]->codec->sample_fmt) {
                    case AV_SAMPLE_FMT_U8 : SampleFMT="-U8";    break;
                    case AV_SAMPLE_FMT_S16: SampleFMT="-S16";    break;
                    case AV_SAMPLE_FMT_S32: SampleFMT="-S32";    break;
                    default               : SampleFMT="-?";      break;
                }
                if (ffmpegFile->streams[Track]->codec->channels==1)        InformationList.append(TrackNum+QString("Channels")+QString("##")+QApplication::translate("cBaseMediaFile","Mono","Audio channels mode")+SampleFMT);
                else if (ffmpegFile->streams[Track]->codec->channels==2)   InformationList.append(TrackNum+QString("Channels")+QString("##")+QApplication::translate("cBaseMediaFile","Stereo","Audio channels mode")+SampleFMT);
                else                                                       InformationList.append(TrackNum+QString("Channels")+QString("##")+QString("%1").arg(ffmpegFile->streams[Track]->codec->channels)+SampleFMT);

                // Frequency
                if (int(ffmpegFile->streams[Track]->codec->sample_rate/1000)*1000>0) {
                    if (int(ffmpegFile->streams[Track]->codec->sample_rate/1000)*1000==ffmpegFile->streams[Track]->codec->sample_rate)
                         InformationList.append(TrackNum+QString("Frequency")+QString("##")+QString("%1").arg(int(ffmpegFile->streams[Track]->codec->sample_rate/1000))+"Khz");
                    else InformationList.append(TrackNum+QString("Frequency")+QString("##")+QString("%1").arg(double(ffmpegFile->streams[Track]->codec->sample_rate)/1000,8,'f',1).trimmed()+"Khz");
                }

                // Bitrate
                if (int(ffmpegFile->streams[Track]->codec->bit_rate/1000)>0) InformationList.append(TrackNum+QString("Bitrate")+QString("##")+QString("%1").arg(int(ffmpegFile->streams[Track]->codec->bit_rate/1000))+"Kb/s");

                // Sample format
                switch (ffmpegFile->streams[Track]->codec->sample_fmt) {
                    case AV_SAMPLE_FMT_U8: 	 InformationList.append(TrackNum+QString("Sample format")+QString("##")+"unsigned 8 bits"); break;
                    case AV_SAMPLE_FMT_S16:  InformationList.append(TrackNum+QString("Sample format")+QString("##")+"signed 16 bits"); break;
                    case AV_SAMPLE_FMT_S32:  InformationList.append(TrackNum+QString("Sample format")+QString("##")+"signed 32 bits"); break;
                    case AV_SAMPLE_FMT_FLT:  InformationList.append(TrackNum+QString("Sample format")+QString("##")+"float"); break;
                    case AV_SAMPLE_FMT_DBL:  InformationList.append(TrackNum+QString("Sample format")+QString("##")+"double"); break;
                    #ifdef AV_SAMPLE_FMT_U8P
                    case AV_SAMPLE_FMT_U8P:  InformationList.append(TrackNum+QString("Sample format")+QString("##")+"unsigned 8 bits, planar"); break;
                    case AV_SAMPLE_FMT_S16P: InformationList.append(TrackNum+QString("Sample format")+QString("##")+"signed 16 bits, planar"); break;
                    case AV_SAMPLE_FMT_S32P: InformationList.append(TrackNum+QString("Sample format")+QString("##")+"signed 32 bits, planar"); break;
                    case AV_SAMPLE_FMT_FLTP: InformationList.append(TrackNum+QString("Sample format")+QString("##")+"float, planar"); break;
                    case AV_SAMPLE_FMT_DBLP: InformationList.append(TrackNum+QString("Sample format")+QString("##")+"double, planar"); break;
                    #endif
                    default:                 InformationList.append(TrackNum+QString("Sample format")+QString("##")+"Unknown"); break;
                }

                // Stream metadata
                while ((tag=av_dict_get(ffmpegFile->streams[Track]->metadata,"",tag,AV_DICT_IGNORE_SUFFIX))) {
                    // OGV container affect TAG to audio stream !
                    QString Key=QString().fromUtf8(tag->key).toLower();
                    if ((FileName.toLower().endsWith(".ogv"))&&((Key=="title")||(Key=="artist")||(Key=="album")||(Key=="comment")||(Key=="date")||(Key=="composer")||(Key=="encoder")))
                             InformationList.append(Key+QString("##")+QString().fromUtf8(tag->value));
                        else InformationList.append(TrackNum+Key+QString("##")+QString().fromUtf8(tag->value));
                }

                // Ensure language exist (Note : AVI and FLV container own language at container level instead of track level)
                if (GetInformationValue(TrackNum+"language")=="") {
                    QString Lng=GetInformationValue("language");
                    InformationList.append(TrackNum+QString("language##")+(Lng==""?"und":Lng));
                }

                // Next
                AudioTrackNbr++;

            //*********************************************************************************************************
            // Video track
            //*********************************************************************************************************
            } else if (!MusicOnly && (ffmpegFile->streams[Track]->codec->codec_type==AVMEDIA_TYPE_VIDEO)) {

                // Keep this as default track
                if (VideoStreamNumber==-1) VideoStreamNumber=Track;

                // Compute TrackNum
                QString TrackNum=QString("%1").arg(VideoTrackNbr);
                while (TrackNum.length()<3) TrackNum="0"+TrackNum;
                TrackNum="Video_"+TrackNum+":";

                // General
                InformationList.append(TrackNum+QString("Track")+QString("##")+QString("%1").arg(Track));
                if (Codec) InformationList.append(TrackNum+QString("Codec")+QString("##")+QString(Codec->name));

                // Bitrate
                if (ffmpegFile->streams[Track]->codec->bit_rate>0) InformationList.append(TrackNum+QString("Bitrate")+QString("##")+QString("%1").arg(int(ffmpegFile->streams[Track]->codec->bit_rate/1000))+"Kb/s");

                // Frame rate
                if (int(double(ffmpegFile->streams[Track]->avg_frame_rate.num)/double(ffmpegFile->streams[Track]->avg_frame_rate.den))>0) {
                    if (int(double(ffmpegFile->streams[Track]->avg_frame_rate.num)/double(ffmpegFile->streams[Track]->avg_frame_rate.den))==double(ffmpegFile->streams[Track]->avg_frame_rate.num)/double(ffmpegFile->streams[Track]->avg_frame_rate.den))
                         InformationList.append(TrackNum+QString("Frame rate")+QString("##")+QString("%1").arg(int(double(ffmpegFile->streams[Track]->avg_frame_rate.num)/double(ffmpegFile->streams[Track]->avg_frame_rate.den)))+" FPS");
                    else InformationList.append(TrackNum+QString("Frame rate")+QString("##")+QString("%1").arg(double(double(ffmpegFile->streams[Track]->avg_frame_rate.num)/double(ffmpegFile->streams[Track]->avg_frame_rate.den)),8,'f',3).trimmed()+" FPS");
                }

                // Stream metadata
                while ((tag=av_dict_get(ffmpegFile->streams[Track]->metadata,"",tag,AV_DICT_IGNORE_SUFFIX)))
                    InformationList.append(TrackNum+QString(tag->key)+QString("##")+QString().fromUtf8(tag->value));

                // Ensure language exist (Note : AVI ‘AttachedPictureFrame’and FLV container own language at container level instead of track level)
                if (GetInformationValue(TrackNum+"language")=="") {
                    QString Lng=GetInformationValue("language");
                    InformationList.append(TrackNum+QString("language##")+(Lng==""?"und":Lng));
                }

                // Next
                VideoTrackNbr++;
            }
        }

        //*********************************************************************************************************
        // Close file
        //*********************************************************************************************************
        #ifdef LIBAV_07
        av_close_input_file(ffmpegFile);
        #else
        avformat_close_input(&ffmpegFile);
        #endif
    }

    //*********************************************************************************************************
    // Produce thumbnail
    //*********************************************************************************************************

    IsInformationValide=true;
    if ((IsIconNeeded)&&(Icon16.isNull())) {
        // If it's an audio file, try to get embeded image
        if (ObjectType==OBJECTTYPE_MUSICFILE) {
            QImage *Img=GetEmbededImage(FileName);
            if (Img) {
                LoadIcons(Img);
                delete Img;
            }

        // If it's a video then search if an image (jpg) with same name exist
        } else if (ObjectType==OBJECTTYPE_VIDEOFILE) {

            // Search if a jukebox mode thumbnail (jpg file with same name as video) exist
            QFileInfo   File(FileName);
            QString     JPegFile=File.absolutePath()+(File.absolutePath().endsWith(QDir::separator())?"":QString(QDir::separator()))+File.completeBaseName()+".jpg";
            if (QFileInfo(JPegFile).exists()) LoadIcons(JPegFile);

            if (Icon16.isNull()||(ImageWidth==0)||(ImageHeight==0)) {
                // Open file
                OpenCodecAndFile();
                CloseCodecAndFile();
            }
        }

        // if no icon then load default for type
        if (Icon16.isNull()) LoadIcons(ObjectType==OBJECTTYPE_VIDEOFILE?&ApplicationConfig->DefaultVIDEOIcon:&ApplicationConfig->DefaultMUSICIcon);
    }
}

//====================================================================================================================

bool cVideoFile::IsFilteredFile(int RequireObjectType) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::IsFilteredFile");

    return (RequireObjectType==OBJECTTYPE_UNMANAGED)||(RequireObjectType==OBJECTTYPE_MANAGED)||(ObjectType==RequireObjectType);
}

//====================================================================================================================

QString cVideoFile::GetFileTypeStr() {
    ToLog(LOGMSG_DEBUGTRACE,QString("IN:cVideoFile::GetFileTypeStr for %1").arg(FileName));

    if (MusicOnly || (ObjectType==OBJECTTYPE_MUSICFILE)) return QApplication::translate("cBaseMediaFile","Music","File type");
        else return QApplication::translate("cBaseMediaFile","Video","File type");
}

//====================================================================================================================

QImage *cVideoFile::GetDefaultTypeIcon(cCustomIcon::IconSize Size) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::GetDefaultTypeIcon");

    if (MusicOnly || (ObjectType==OBJECTTYPE_MUSICFILE)) return ApplicationConfig->DefaultMUSICIcon.GetIcon(Size);
        else return ApplicationConfig->DefaultVIDEOIcon.GetIcon(Size);
}

//====================================================================================================================

QString cVideoFile::GetTechInfo() {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::GetTechInfo");

    QString Info="";
    if (ObjectType==OBJECTTYPE_MUSICFILE) {
        Info=GetCumulInfoStr("Audio","Codec");
        if (GetCumulInfoStr("Audio","Channels")!="")       Info=Info+(Info!=""?"-":"")+GetCumulInfoStr("Audio","Channels");
        if (GetCumulInfoStr("Audio","Bitrate")!="")        Info=Info+(Info!=""?"-":"")+GetCumulInfoStr("Audio","Bitrate");
        if (GetCumulInfoStr("Audio","Frequency")!="")      Info=Info+(Info!=""?"-":"")+GetCumulInfoStr("Audio","Frequency");
    } else {
        Info=GetImageSizeStr();
        if (GetCumulInfoStr("Video","Codec")!="")          Info=Info+(Info!=""?"-":"")+GetCumulInfoStr("Video","Codec");
        if (GetCumulInfoStr("Video","Frame rate")!="")     Info=Info+(Info!=""?"-":"")+GetCumulInfoStr("Video","Frame rate");
        if (GetCumulInfoStr("Video","Bitrate")!="")        Info=Info+(Info!=""?"-":"")+GetCumulInfoStr("Video","Bitrate");

        int     Num     =0;
        QString TrackNum="";
        QString Value   ="";
        QString SubInfo ="";
        do {
            TrackNum=QString("%1").arg(Num);
            while (TrackNum.length()<3) TrackNum="0"+TrackNum;
            TrackNum="Audio_"+TrackNum+":";
            Value=GetInformationValue(TrackNum+"language");
            if (Value!="") {
                if (Num==0) Info=Info+"-"; else Info=Info+"/";
                SubInfo=GetInformationValue(TrackNum+"Codec");
                if (GetInformationValue(TrackNum+"Channels")!="")  SubInfo=SubInfo+(Info!=""?"-":"")+GetInformationValue(TrackNum+"Channels");
                if (GetInformationValue(TrackNum+"Bitrate")!="")   SubInfo=SubInfo+(Info!=""?"-":"")+GetInformationValue(TrackNum+"Bitrate");
                if (GetInformationValue(TrackNum+"Frequency")!="") SubInfo=SubInfo+(Info!=""?"-":"")+GetInformationValue(TrackNum+"Frequency");
                Info=Info+Value+"("+SubInfo+")";
            }
            // Next
            Num++;
        } while (Value!="");
    }
    return Info;
}

//====================================================================================================================

QString cVideoFile::GetTAGInfo() {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::GetTAGInfo");

    QString Info=GetInformationValue("track");
    if (GetInformationValue("title")!="")          Info=Info+(Info!=""?"-":"")+GetInformationValue("title");
    if (GetInformationValue("artist")!="")         Info=Info+(Info!=""?"-":"")+GetInformationValue("artist");
    if (GetInformationValue("album")!="")          Info=Info+(Info!=""?"-":"")+GetInformationValue("album");
    if (GetInformationValue("date")!="")           Info=Info+(Info!=""?"-":"")+GetInformationValue("date");
    if (GetInformationValue("genre")!="")          Info=Info+(Info!=""?"-":"")+GetInformationValue("genre");
    return Info;
}

//====================================================================================================================
// Close LibAVFormat and LibAVCodec contexte for the file
//====================================================================================================================

void cVideoFile::CloseCodecAndFile() {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::CloseCodecAndFile");

    while (CacheImage.count()>0) CacheImage.removeLast();

    // Close the filter context
    #ifdef VIDEO_LIBAVFILTER
    if (VideoFilterGraph) VideoFilter_Close();
    #endif
    #ifdef AUDIO_LIBAVFILTER
    if (AudioFilterGraph) AudioFilter_Close();
    #endif
    // Close the video codec
    if (VideoDecoderCodec!=NULL) {
        avcodec_close(ffmpegVideoFile->streams[VideoStreamNumber]->codec);
        VideoDecoderCodec=NULL;
    }

    // Close the video file
    if (ffmpegVideoFile!=NULL) {
        #ifdef LIBAV_07
        av_close_input_file(ffmpegVideoFile);
        #else
        avformat_close_input(&ffmpegVideoFile);
        #endif
        ffmpegVideoFile=NULL;
    }

    // Close the audio codec
    if (AudioDecoderCodec!=NULL) {
        avcodec_close(ffmpegAudioFile->streams[AudioStreamNumber]->codec);
        AudioDecoderCodec=NULL;
    }
    // Close the audio file
    if (ffmpegAudioFile!=NULL) {
        #ifdef LIBAV_07
        av_close_input_file(ffmpegAudioFile);
        #else
        avformat_close_input(&ffmpegAudioFile);
        #endif
        ffmpegAudioFile=NULL;
    }

    if (FrameBufferYUV!=NULL) {
        av_free(FrameBufferYUV);
        FrameBufferYUV=NULL;
    }
    FrameBufferYUVReady=false;
    IsOpen=false;
}

//====================================================================================================================
// Read an audio frame from current stream
//====================================================================================================================

void cVideoFile::ReadAudioFrame(bool PreviewMode,qlonglong Position,cSoundBlockList *SoundTrackBloc,double Volume,bool DontUseEndPos) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::ReadAudioFrame");

    if (Volume==0) return;

    // Ensure file was previously open and all is ok
    if ((SoundTrackBloc==NULL)||(AudioStreamNumber==-1)||(ffmpegAudioFile->streams[AudioStreamNumber]==NULL)||(ffmpegAudioFile==NULL)||(AudioDecoderCodec==NULL)) return;

    // Ensure Position is not > EndPosition
    if (Position>QTime(0,0,0,0).msecsTo(DontUseEndPos?Duration:EndPos)) return;

    #ifdef AUDIO_LIBAVFILTER
    if (!AudioFilterGraph) AudioFilter_Open("aresample=48000,aconvert=s16:stereo");
    #endif


    int64_t         AVNOPTSVALUE        =INT64_C(0x8000000000000000); // to solve type error with Qt
    AVStream        *AudioStream        =ffmpegAudioFile->streams[AudioStreamNumber];
    int64_t         SrcSampleSize       =(AudioStream->codec->sample_fmt==AV_SAMPLE_FMT_S16?2:1)*int64_t(AudioStream->codec->channels);
    int64_t         DstSampleSize       =(SoundTrackBloc->SampleBytes*SoundTrackBloc->Channels);
    AVPacket        *StreamPacket       =NULL;
    int64_t         MaxAudioLenDecoded  =192000*3;
    int64_t         AudioLenDecoded     =0;
    uint8_t         *BufferForDecoded   =(uint8_t *)av_malloc(MaxAudioLenDecoded+8);    //***************** !
    double          dPosition           =double(Position)/1000;     // Position in double format
    //double          AudioDataWanted     =(PreviewMode?SoundTrackBloc->WantedDuration:5)*double(AudioStream->codec->sample_rate)*SrcSampleSize;  // 5 sec for rendering
    double          AudioLengthWanted   =(PreviewMode?1:5)*SoundTrackBloc->WantedDuration;                                                      // 5 frame for rendering

    bool            Continue        =true;
    double          FramePosition   =dPosition;
    double          FrameDuration   =0;

    // Adjust position if input file have a start_time value
    if (ffmpegAudioFile->start_time!=AVNOPTSVALUE) dPosition+=double(ffmpegAudioFile->start_time)/double(AV_TIME_BASE);

    // Cac difftime between asked position and previous end decoded position
    qlonglong Diff=(qlonglong(SoundTrackBloc->SoundPacketSize*SoundTrackBloc->List.count()+SoundTrackBloc->CurrentTempSize)/DstSampleSize)*1000/SoundTrackBloc->SamplingRate;
    qlonglong DiffTimePosition=(LastAudioReadedPosition-Diff)-(dPosition*1000);
    if (DiffTimePosition<0) DiffTimePosition=-DiffTimePosition;

    #ifdef LIBAV_07
        // if Old ffmpeg : Prepare a buffer for sound decoding
        uint8_t *BufferToDecode=(uint8_t *)av_malloc(48000*4*2);   // 2 sec buffer
    #endif

    // Calc if we need to seek to a position
    if ((Position==0)||(DiffTimePosition>500)) {// Allow 0,5 sec diff (rounded double !)
        // Flush all buffers
        for (unsigned int i=0;i<ffmpegAudioFile->nb_streams;i++)  {
            AVCodecContext *codec_context = ffmpegAudioFile->streams[i]->codec;
            if (codec_context && codec_context->codec) avcodec_flush_buffers(codec_context);
        }
        SoundTrackBloc->ClearList();      // Clear soundtrack list

        // Seek to nearest previous key frame
        ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::ReadAudioFrame => do a seek");
        int64_t seek_target=av_rescale_q(int64_t((dPosition/1000)*AV_TIME_BASE),AV_TIME_BASE_Q,ffmpegAudioFile->streams[AudioStreamNumber]->time_base);
        if (av_seek_frame(ffmpegAudioFile,AudioStreamNumber,seek_target,AVSEEK_FLAG_BACKWARD)<0) {
            // Try in AVSEEK_FLAG_ANY mode
            if (av_seek_frame(ffmpegAudioFile,AudioStreamNumber,seek_target,AVSEEK_FLAG_ANY)<0) {
                ToLog(LOGMSG_CRITICAL,"Error in cVideoFile::ReadAudioFrame : Seek error");
            }
        }
        FramePosition=-1;

    }

    //*************************************************************************************************************************************
    // Decoding process : Get StreamPacket until AudioLenDecoded>=AudioDataWanted or we have reach the end of file
    //*************************************************************************************************************************************

    while (Continue) {
        StreamPacket=new AVPacket();
        av_init_packet(StreamPacket);

        int err=av_read_frame(ffmpegAudioFile,StreamPacket);
        if (err<0) {
            // if error in av_read_frame(...) then may be we have reach the end of file !
            Continue=false;
            ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::ReadAudioFrame : av_read_frame error %1").arg(err));
        } else {
            if ((StreamPacket->stream_index==AudioStreamNumber)&&(StreamPacket->size>0)) {

                AVPacket PacketTemp;
                av_init_packet(&PacketTemp);
                PacketTemp.data=StreamPacket->data;
                PacketTemp.size=StreamPacket->size;

                if (StreamPacket->pts!=AVNOPTSVALUE) FramePosition=double(StreamPacket->pts)*double(av_q2d(AudioStream->time_base));

                // NOTE: the audio packet can contain several NbrFrames
                if (FramePosition!=-1) while (PacketTemp.size>0) {

                    #ifdef LIBAV_07
                    // Decode audio data
                    int SizeDecoded     =(AVCODEC_MAX_AUDIO_FRAME_SIZE*3)/2;
                    int Len             =avcodec_decode_audio3(AudioStream->codec,(int16_t *)BufferToDecode,&SizeDecoded,&PacketTemp);
                    #else
                    AVFrame *Frame      =avcodec_alloc_frame();
                    int     SizeDecoded =0;
                    int     Len         =avcodec_decode_audio4(AudioStream->codec,Frame,&SizeDecoded,&PacketTemp);
                    #endif
                    if (Len<0) {
                        // if decode error then data are not good : replace them with null sound
                        //SizeDecoded=int64_t(LastAudioFrameDuration*double(SoundTrackBloc->SamplingRate))*DstSampleSize;
                        //memset(BufferForDecoded+AudioLenDecoded,0,SizeDecoded);
                        //AudioLenDecoded+=SizeDecoded;
                        //qDebug()<<"    =>Make NULL Audio frame"<<SizeDecoded<<"bytes added - Buffer:"<<AudioLenDecoded<<"/"<<MaxAudioLenDecoded;
                        // if error, we skip the frame and exit the while loop
                        PacketTemp.size=0;
                    } else if (SizeDecoded>0) {
                        #ifdef LIBAV_07
                        FrameDuration=double(SizeDecoded)/(double(SrcSampleSize)*double(AudioStream->codec->sample_rate));
                        #else
                        SizeDecoded  =Frame->nb_samples*SrcSampleSize;
                        FrameDuration=double(Frame->nb_samples)/double(AudioStream->codec->sample_rate);
                        #endif

                        // If wanted position <= CurrentPosition+Packet duration then add this packet to the queue
                        if ((FramePosition+FrameDuration)>=dPosition) {
                            int64_t Delta=0;
                            // if dPosition start in the midle of the pack, then calculate delta
                            if (dPosition>FramePosition) {
                                Delta=round((dPosition-FramePosition)*AudioStream->codec->sample_rate)*SrcSampleSize;
                                if (Delta<0) Delta=0;
                            }
                            // Append decoded data to BufferForDecoded buffer
                            #ifdef LIBAV_07
                            memcpy(BufferForDecoded+AudioLenDecoded,BufferToDecode+Delta,SizeDecoded-Delta);
                            #else
                            memcpy(BufferForDecoded+AudioLenDecoded,Frame->data[0]+Delta,SizeDecoded-Delta);
                            #endif
                            AudioLenDecoded+=(SizeDecoded-Delta);
                        }

                        PacketTemp.data        +=Len;
                        PacketTemp.size        -=Len;
                        FramePosition           =FramePosition+FrameDuration;
                        LastAudioReadedPosition =int(FramePosition*1000);    // Keep NextPacketPosition for determine next time if we need to seek
                    }
                    #ifndef LIBAV_07
                    av_free(Frame);
                    #endif
                }
            }

            // Continue with a new one
            av_free_packet(StreamPacket); // Free the StreamPacket that was allocated by previous call to av_read_frame
            delete StreamPacket;
            StreamPacket=NULL;

            // Check if we need to continue loop
            //Continue=(AudioLenDecoded<AudioDataWanted);
            Continue=FramePosition<dPosition+AudioLengthWanted;
        }
    }

    //**********************************************************************
    // Transfert data from BufferForDecoded to Buffer using audio_resample
    //**********************************************************************
    if (AudioLenDecoded>0) {
        if ((AudioStream->codec->sample_fmt!=AV_SAMPLE_FMT_S16)||(AudioStream->codec->channels!=2)||(AudioStream->codec->sample_rate!=48000)) {
            // Resample sound to wanted freq. using ffmpeg audio_resample function
	    AVAudioResampleContext *avr = avresample_alloc_context();
            uint8_t *BufSampled = (uint8_t*)av_malloc(MaxAudioLenDecoded);
	    int ret;

	    av_opt_set_int(avr, "in_channel_layout", AudioStream->codec->channel_layout, 0);
	    av_opt_set_int(avr, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0);
	    av_opt_set_int(avr, "in_sample_rate", AudioStream->codec->sample_rate, 0);
	    av_opt_set_int(avr, "out_sample_rate", 48000, 0);
	    av_opt_set_int(avr, "in_sample_fmt", AudioStream->codec->sample_fmt, 0);
	    av_opt_set_int(avr, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);

	    avresample_open(avr);

            ret = avresample_convert(avr, &BufSampled, MaxAudioLenDecoded, MaxAudioLenDecoded / DstSampleSize,
                            &BufferForDecoded, AudioLenDecoded, AudioLenDecoded / SrcSampleSize);

            // Adjust volume
            if (Volume!=1) {
                int16_t *Buf1=(int16_t*)BufSampled;
                int32_t mix;
                for (int j = 0; j < ret; j++) {
                    Buf1[2 * j] = av_clip_int16(Buf1[2 * j] * Volume);
                    Buf1[2 * j + 1] = av_clip_int16(Buf1[2 * j + 1] * Volume);
                }
            }

            // Append data to SoundTrackBloc
            SoundTrackBloc->AppendData((int16_t*)BufSampled, ret * 2 * 2);
            avresample_free(&avr);
            av_free(BufSampled);        // Free allocated buffers

        } else {
            SoundTrackBloc->AppendData((int16_t*)BufferForDecoded,AudioLenDecoded);
        }
    }

    // Now ensure SoundTrackBloc have correct wanted packet (if no then add nullsound)
    //while (SoundTrackBloc->List.count()<SoundTrackBloc->NbrPacketForFPS) SoundTrackBloc->AppendNullSoundPacket();

    #ifdef LIBAV_07
    if (BufferToDecode)   av_free(BufferToDecode);
    #endif
    if (BufferForDecoded) av_free(BufferForDecoded);
}

#ifdef VIDEO_LIBAVFILTER
    //*********************************************************************************************************************
    // VIDEO FILTER PART : This code was adapt from xbmc sources files DVDVideoCodecFFmpeg.h/.cpp and AVPLAY.c
    //*********************************************************************************************************************

    unsigned int cVideoFile::SetFilters(unsigned int flags) {
        m_filters_next.clear();

        if (flags & FILTER_DEINTERLACE_YADIF) {
            if (flags & FILTER_DEINTERLACE_HALFED)  m_filters_next="yadif=0:-1";
                else                                m_filters_next="yadif=1:-1";

            if (flags & FILTER_DEINTERLACE_FLAGGED) m_filters_next += ":1";
            flags &= ~FILTER_DEINTERLACE_ANY | FILTER_DEINTERLACE_YADIF;
        }
        return flags;
    }

    int cVideoFile::VideoFilter_Open(QString filters) {
        int result;

        if (VideoFilterGraph) VideoFilter_Close();

        if (filters.isEmpty()) return 0;

        if (!(VideoFilterGraph=avfilter_graph_alloc())) {
            ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Open : unable to alloc filter graph"));
            return -1;
        }

        VideoFilterGraph->scale_sws_opts = av_strdup("flags=4");

        QString args=QString("%1:%2:%3:%4:%5:%6:%7")
            .arg(ffmpegVideoFile->streams[VideoStreamNumber]->codec->width)
            .arg(ffmpegVideoFile->streams[VideoStreamNumber]->codec->height)
            .arg(ffmpegVideoFile->streams[VideoStreamNumber]->codec->pix_fmt)
            .arg(ffmpegVideoFile->streams[VideoStreamNumber]->codec->time_base.num)
            .arg(ffmpegVideoFile->streams[VideoStreamNumber]->codec->time_base.den)
            .arg(ffmpegVideoFile->streams[VideoStreamNumber]->codec->sample_aspect_ratio.num)
            .arg(ffmpegVideoFile->streams[VideoStreamNumber]->codec->sample_aspect_ratio.den);

        #if LIBAVFILTER_VERSION_INT < AV_VERSION_INT(2,60,0)    // from 2.13 to 2.60

            AVFilter *srcFilter=avfilter_get_by_name("buffer");
            AVFilter *outFilter=avfilter_get_by_name("nullsink");

            if ((result=avfilter_graph_create_filter(&VideoFilterIn,srcFilter,"src",args.toLocal8Bit().constData(),NULL,VideoFilterGraph))<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Open : avfilter_graph_create_filter: src"));
                return result;
            }
            if ((result=avfilter_graph_create_filter(&VideoFilterOut,outFilter,"out",NULL,NULL,VideoFilterGraph))<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Open : avfilter_graph_create_filter: out"));
                return result;
            }

            AVFilterInOut *outputs = (AVFilterInOut *)av_malloc(sizeof(AVFilterInOut));
            AVFilterInOut *inputs  = (AVFilterInOut *)av_malloc(sizeof(AVFilterInOut));

        #elif LIBAVFILTER_VERSION_INT < AV_VERSION_INT(3,1,0)     // from 2.60 to 3.1

            AVFilter *srcFilter=avfilter_get_by_name("buffer");
            AVFilter *outFilter=avfilter_get_by_name("buffersink");

            if ((result=avfilter_graph_create_filter(&VideoFilterIn,srcFilter,"src",args.toLocal8Bit().constData(),NULL,VideoFilterGraph))<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Open : avfilter_graph_create_filter: src"));
                return result;
            }
            std::vector<PixelFormat> m_formats;
            m_formats.push_back(PIX_FMT_YUVJ420P);
            m_formats.push_back(PIX_FMT_NONE);      /* always add none to get a terminated list in ffmpeg world */
            AVBufferSinkParams *buffersink_params=av_buffersink_params_alloc();
            buffersink_params->pixel_fmts=&m_formats[0];
            #ifdef FF_API_OLD_VSINK_API
            if ((result=avfilter_graph_create_filter(&VideoFilterOut,outFilter,"out",NULL,(void*)buffersink_params->pixel_fmts,VideoFilterGraph))<0) {
            #else
            if ((result=avfilter_graph_create_filter(&VideoFilterOut,outFilter,"out",NULL,buffersink_params,VideoFilterGraph))<0) {
            #endif
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Open : avfilter_graph_create_filter: out"));
                return result;
            }
            av_free(buffersink_params);
            AVFilterInOut *outputs=avfilter_inout_alloc();
            AVFilterInOut *inputs =avfilter_inout_alloc();

        #else                                                   // from 3.1

            AVFilter *srcFilter=avfilter_get_by_name("buffer");
            AVFilter *outFilter=avfilter_get_by_name("buffersink");

            if ((result=avfilter_graph_create_filter(&VideoFilterIn,srcFilter,"src",args.toLocal8Bit().constData(),NULL,VideoFilterGraph))<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Open : avfilter_graph_create_filter: src"));
                return result;
            }
            if ((result=avfilter_graph_create_filter(&VideoFilterOut,outFilter,"out",NULL,NULL,VideoFilterGraph))<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Open : avfilter_graph_create_filter: out"));
                return result;
            }
            AVFilterInOut *outputs=avfilter_inout_alloc();
            AVFilterInOut *inputs =avfilter_inout_alloc();

        #endif

        outputs->name = av_strdup("in");
        outputs->filter_ctx = VideoFilterIn;
        outputs->pad_idx = 0;
        outputs->next = NULL;

        inputs->name = av_strdup("out");
        inputs->filter_ctx = VideoFilterOut;
        inputs->pad_idx = 0;
        inputs->next = NULL;

        if ((result=avfilter_graph_parse(VideoFilterGraph,m_filters.toLocal8Bit().constData(),inputs,outputs,NULL))<0) {
            ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Open : avfilter_graph_parse"));
            return result;
        }

        #if LIBAVFILTER_VERSION_INT < AV_VERSION_INT(2,23,0)
        //av_free(outputs);
        //av_free(inputs);
        #elif LIBAVFILTER_VERSION_INT < AV_VERSION_INT(3,1,0) // since 3.1, do not dispose them
        avfilter_inout_free(&outputs);
        avfilter_inout_free(&inputs);
        #endif

        if ((result=avfilter_graph_config(VideoFilterGraph,NULL))<0) {
            ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Open : avfilter_graph_config"));
            return result;
        }
        return result;
    }

    void cVideoFile::VideoFilter_Close() {
        if (VideoFilterGraph) {
            avfilter_graph_free(&VideoFilterGraph);
            // Disposed by avfilter_graph_free
            VideoFilterIn =NULL;
            VideoFilterOut=NULL;
        }
    }

    int cVideoFile::VideoFilter_Process() {
        #if LIBAVFILTER_VERSION_INT < AV_VERSION_INT(2,60,0)             // from 2.13 to 2.60

            #if LIBAVFILTER_VERSION_INT < AV_VERSION_INT(2,23,0)         // from 2.13 to 2.23
            int Ret=av_vsrc_buffer_add_frame(VideoFilterIn,FrameBufferYUV,FrameBufferYUV->pts,ffmpegVideoFile->streams[VideoStreamNumber]->codec->sample_aspect_ratio);
            if (Ret<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Process : av_vsrc_buffer_add_frame"));
                return VC_ERROR;
            }
            #else                                                       // from 2.23 to 2.60
            int Ret=av_vsrc_buffer_add_frame(VideoFilterIn,FrameBufferYUV,0);
            if (Ret<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Process : av_vsrc_buffer_add_frame"));
                return VC_ERROR;
            }
            #endif
            int NbrFrames;
            while ((NbrFrames=avfilter_poll_frame(VideoFilterOut->inputs[0]))>0) {
                if (VideoFilterOut->inputs[0]->cur_buf) {
                    avfilter_unref_buffer(VideoFilterOut->inputs[0]->cur_buf);
                    VideoFilterOut->inputs[0]->cur_buf = NULL;
                }

                if ((Ret=avfilter_request_frame(VideoFilterOut->inputs[0]))<0) {
                    ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Process : avfilter_request_frame"));
                    return VC_ERROR;
                }

                if (!VideoFilterOut->inputs[0]->cur_buf) {
                    ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Process : cur_buf"));
                    return VC_ERROR;
                }

                FrameBufferYUV->repeat_pict      = -(NbrFrames - 1);
                FrameBufferYUV->interlaced_frame = VideoFilterOut->inputs[0]->cur_buf->video->interlaced;
                FrameBufferYUV->top_field_first  = VideoFilterOut->inputs[0]->cur_buf->video->top_field_first;

                memcpy(FrameBufferYUV->linesize, VideoFilterOut->inputs[0]->cur_buf->linesize, 4*sizeof(int));
                memcpy(FrameBufferYUV->data    , VideoFilterOut->inputs[0]->cur_buf->data    , 4*sizeof(uint8_t*));
            }

        #elif LIBAVFILTER_VERSION_INT < AV_VERSION_INT(3,0,0)             // from 2.60 to 3.0

            int Ret=av_vsrc_buffer_add_frame(VideoFilterIn,FrameBufferYUV,0);
            if (Ret<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Process : av_vsrc_buffer_add_frame"));
                return VC_ERROR;
            }
            int NbrFrames;
            if ((NbrFrames=av_buffersink_poll_frame(VideoFilterOut))<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Process : av_buffersink_poll_frame"));
                return VC_ERROR;
            }
            while (NbrFrames>0) {
                AVFilterBufferRef *m_pBufferRef=NULL;
                Ret=av_buffersink_get_buffer_ref(VideoFilterOut,&m_pBufferRef,0);
                if (!m_pBufferRef) {
                    ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Process : cur_buf"));
                    return VC_ERROR;
                }
                FrameBufferYUV->repeat_pict     =-(NbrFrames-1);
                FrameBufferYUV->interlaced_frame=m_pBufferRef->video->interlaced;
                FrameBufferYUV->top_field_first =m_pBufferRef->video->top_field_first;
                memcpy(FrameBufferYUV->linesize,m_pBufferRef->linesize,4*sizeof(int));
                memcpy(FrameBufferYUV->data,    m_pBufferRef->data,    4*sizeof(uint8_t*));
                NbrFrames--;
                if (m_pBufferRef) {
                    avfilter_unref_buffer(m_pBufferRef);
                    m_pBufferRef = NULL;
                }
            }

        #elif LIBAVFILTER_VERSION_INT < AV_VERSION_INT(3,1,0)           // from 3.0 to 3.1

            int Ret=av_buffersrc_add_frame(VideoFilterIn,FrameBufferYUV,0);
            if (Ret<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Process : av_buffersrc_add_frame"));
                return VC_ERROR;
            }
            int NbrFrames;
            if ((NbrFrames=av_buffersink_poll_frame(VideoFilterOut))<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Process : av_buffersink_poll_frame"));
                return VC_ERROR;
            }
            while (NbrFrames>0) {
                AVFilterBufferRef *m_pBufferRef=NULL;
                Ret=av_buffersink_get_buffer_ref(VideoFilterOut,&m_pBufferRef,0);
                if (!m_pBufferRef) {
                    ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Process : cur_buf"));
                    return VC_ERROR;
                }
                FrameBufferYUV->repeat_pict     =-(NbrFrames-1);
                FrameBufferYUV->interlaced_frame=m_pBufferRef->video->interlaced;
                FrameBufferYUV->top_field_first =m_pBufferRef->video->top_field_first;
                memcpy(FrameBufferYUV->linesize,m_pBufferRef->linesize,4*sizeof(int));
                memcpy(FrameBufferYUV->data,    m_pBufferRef->data,    4*sizeof(uint8_t*));
                NbrFrames--;
                if (m_pBufferRef) {
                    avfilter_unref_buffer(m_pBufferRef);
                    m_pBufferRef = NULL;
                }
            }


        #else                                                           // from 3.1

            int Ret=av_buffersrc_write_frame(VideoFilterIn,FrameBufferYUV);
            if (Ret<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::VideoFilter_Process : av_buffersrc_write_frame"));
                return VC_ERROR;
            }
            while (Ret>=0) {
                AVFilterBufferRef *m_pBufferRef=NULL;
                Ret=av_buffersink_read(VideoFilterOut,&m_pBufferRef);
                if (Ret<0) break;
                avfilter_copy_buf_props(FrameBufferYUV,m_pBufferRef);
                FrameBufferYUV->opaque=m_pBufferRef;
            }
        #endif
        return VC_BUFFER;
    }

#endif

#ifdef AUDIO_LIBAVFILTER
    //*********************************************************************************************************************
    // AUDIO FILTER PART : This code was adapt from filtering_audio.c give with ffmpeg library
    //*********************************************************************************************************************
    //"aresample=48000,aconvert=s16:stereo"

    int cVideoFile::AudioFilter_Open(QString Filters) {
        if (AudioFilterGraph) AudioFilter_Close();

        QString             Args;
        int                 ret;
        AVCodecContext      *dec_ctx            =ffmpegAudioFile->streams[AudioStreamNumber]->codec;
        AVRational          time_base           =ffmpegAudioFile->streams[AudioStreamNumber]->time_base;

        if (!(AudioFilterGraph=avfilter_graph_alloc())) {
            ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::AudioFilter_Open : unable to alloc filter graph"));
            return -1;
        }

        #if LIBAVFILTER_VERSION_INT >= AV_VERSION_INT(2,60,0)    // from 2.13 to 2.60
        if (!dec_ctx->channel_layout) dec_ctx->channel_layout = av_get_default_channel_layout(dec_ctx->channels);
        #endif

        Args=QString("time_base=%1/%2:sample_rate=%3:sample_fmt=%4:channel_layout=0x%5").arg(time_base.num).arg(time_base.den).arg(dec_ctx->sample_rate).arg(av_get_sample_fmt_name(dec_ctx->sample_fmt)).arg(dec_ctx->channel_layout);

        #if (LIBAVFILTER_VERSION_INT>=AV_VERSION_INT(2,60,0)) && (LIBAVFILTER_VERSION_INT<AV_VERSION_INT(3,1,0))     // from 2.60 to 3.1

            AVFilter *srcFilter=avfilter_get_by_name("abuffer");
            AVFilter *outFilter=avfilter_get_by_name("ffabuffersink");

            if ((result=avfilter_graph_create_filter(&AudioFilterIn,srcFilter,"src",Args.toLocal8Bit().constData(),NULL,AudioFilterGraph))<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::AudioFilter_Open : avfilter_graph_create_filter: src"));
                return result;
            }

            const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16, AVSampleFormat(-1) };

            /* buffer audio sink: to terminate the filter chain. */
            AVABufferSinkParams *abuffersink_params=av_abuffersink_params_alloc();
            abuffersink_params->sample_fmts = sample_fmts;
            if (ret=(avfilter_graph_create_filter(&AudioFilterOut,outFilter,"out",NULL,abuffersink_params,AudioFilterGraph))<0) {
                av_free(abuffersink_params);
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::AudioFilter_Open : Cannot create audio buffer sink"));
                return ret;
            }
            av_free(abuffersink_params);

            AVFilterInOut *outputs=avfilter_inout_alloc();
            AVFilterInOut *inputs =avfilter_inout_alloc();

        #else                                                   // from 3.1

            AVFilter *srcFilter=avfilter_get_by_name("abuffer");
            AVFilter *outFilter=avfilter_get_by_name("ffabuffersink");

            if ((result=avfilter_graph_create_filter(&AudioFilterIn,srcFilter,"src",Args.toLocal8Bit().constData(),NULL,AudioFilterGraph))<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::AudioFilter_Open : avfilter_graph_create_filter: src"));
                return result;
            }
            if ((result=avfilter_graph_create_filter(&AudioFilterOut,outFilter,"out",NULL,NULL,AudioFilterGraph))<0) {
                ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::AudioFilter_Open : avfilter_graph_create_filter: out"));
                return result;
            }
            AVFilterInOut *outputs=avfilter_inout_alloc();
            AVFilterInOut *inputs =avfilter_inout_alloc();

        #endif

        /* Endpoints for the filter graph. */
        outputs->name      =av_strdup("in");
        outputs->filter_ctx=AudioFilterIn;
        outputs->pad_idx   =0;
        outputs->next      =NULL;

        inputs->name       =av_strdup("out");
        inputs->filter_ctx =AudioFilterOut;
        inputs->pad_idx    =0;
        inputs->next       =NULL;

        #if LIBAVFILTER_VERSION_INT < AV_VERSION_INT(2,23,0)
        if ((ret=avfilter_graph_parse(AudioFilterGraph,Filters.toLocal8Bit().constData(),inputs,outputs,NULL))<0) {
        #elif LIBAVFILTER_VERSION_INT < AV_VERSION_INT(3,1,0)
        if ((ret=avfilter_graph_parse(AudioFilterGraph,Filters.toLocal8Bit().constData(),&inputs,&outputs,NULL))<0) {
        #elif LIBAVFILTER_VERSION_INT < AV_VERSION_INT(3,17,0)
        if ((ret=avfilter_graph_parse(AudioFilterGraph,Filters.toLocal8Bit().constData(),inputs,outputs,NULL))<0) {
        #else
        if ((ret=avfilter_graph_parse(AudioFilterGraph,Filters.toLocal8Bit().constData(),&inputs,&outputs,NULL))<0) {
        #endif
            ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::AudioFilter_Open : avfilter_graph_parse"));
            return ret;
        }

        #if LIBAVFILTER_VERSION_INT < AV_VERSION_INT(2,23,0)
        //av_free(outputs);
        //av_free(inputs);
        #elif LIBAVFILTER_VERSION_INT < AV_VERSION_INT(3,1,0) // since 3.1, do not dispose them
        avfilter_inout_free(&outputs);
        avfilter_inout_free(&inputs);
        #endif

        if ((ret=avfilter_graph_config(VideoFilterGraph,NULL))<0) {
            ToLog(LOGMSG_CRITICAL,QString("Error in cVideoFile::AudioFilter_Open : avfilter_graph_config"));
            return ret;
        }

        return 0;
    }

    void cVideoFile::AudioFilter_Close() {
        if (AudioFilterGraph) {
            avfilter_graph_free(&AudioFilterGraph);
            // Disposed by avfilter_graph_free
            AudioFilterIn =NULL;
            AudioFilterOut=NULL;
        }
    }

#endif

//====================================================================================================================
// Read a video frame from current stream
//====================================================================================================================

#define MAXELEMENTSINOBJECTLIST 500
int MAXCACHEIMAGE=1;

QImage *cVideoFile::ReadVideoFrame(bool PreviewMode,qlonglong Position,bool DontUseEndPos,bool Deinterlace) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::ReadVideoFrame");

    // Ensure file was previously open
    if (((ffmpegVideoFile==NULL)||(VideoDecoderCodec==NULL))&&(!OpenCodecAndFile())) return NULL;

    double dEndFile =double(QTime(0,0,0,0).msecsTo(DontUseEndPos?Duration:EndPos))/1000;    // End File Position in double format
    double dPosition=double(Position)/1000;                                                 // Position in double format

    if (dEndFile==0) {
        ToLog(LOGMSG_CRITICAL,"Error in cVideoFile::ReadVideoFrame : dEndFile=0 ?????");
        return NULL;
    }

    // Adjust position if input file have a start_time value
    if (start_time)  {
        dPosition+=double(start_time)/double(AV_TIME_BASE);
        Position  =int(dPosition*1000);
    }

    // Ensure Position is not > EndPosition, in that case, change Position to lastposition
    if ((dPosition>0)&&(dPosition>=dEndFile)) {
        Position=QTime(0,0,0,0).msecsTo(EndPos);
        dPosition=double(Position)/1000;
    }

    for (int i=0;i<CacheImage.count();i++) if (CacheImage.at(i).Position==Position) {
        return new QImage(CacheImage.at(i).Image.copy());
    }

    // Allocate structure for YUV image
    if (FrameBufferYUV==NULL) FrameBufferYUV=avcodec_alloc_frame();
    if (FrameBufferYUV==NULL) return NULL;

    bool            DataInBuffer        =false;
    QImage          *RetImage           =NULL;
    AVStream        *VideoStream        =ffmpegVideoFile->streams[VideoStreamNumber];
    AVPacket        *StreamPacket       =NULL;

    /*if ((FrameBufferYUVReady)&&(FrameBufferYUVPosition==Position)) {
        return ConvertYUVToRGB(PreviewMode);
    }*/

    // Cac difftime between asked position and previous end decoded position
    qlonglong DiffTimePosition=-1;
    if (FrameBufferYUVReady) DiffTimePosition=Position-FrameBufferYUVPosition;


    // Calc if we need to seek to a position
    if ((Position==0)||(DiffTimePosition<0)||(DiffTimePosition>1500)) { // Allow 1,5 sec diff

        // Seek to nearest previous key frame
        ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::ReadVideoFrame => do a seek");

        // Flush all buffers
        for (unsigned int i=0;i<ffmpegVideoFile->nb_streams;i++)  {
            AVCodecContext *codec_context = ffmpegVideoFile->streams[i]->codec;
            if (codec_context && codec_context->codec) avcodec_flush_buffers(codec_context);
        }

        FrameBufferYUVReady    = false;
        FrameBufferYUVPosition = 0;

        if (!IsMTS) {
            int64_t seek_target=av_rescale_q(int64_t(Position*1000),AV_TIME_BASE_Q,ffmpegVideoFile->streams[VideoStreamNumber]->time_base);
            if (av_seek_frame(ffmpegVideoFile,VideoStreamNumber,seek_target,AVSEEK_FLAG_BACKWARD)<0) {
                // Try in AVSEEK_FLAG_ANY mode
                if (av_seek_frame(ffmpegVideoFile,VideoStreamNumber,seek_target,AVSEEK_FLAG_ANY)<0) {
                    ToLog(LOGMSG_CRITICAL,"Error in cVideoFile::ReadVideoFrame : Seek error");
                }
            }
        } else {
            // Seek to nearest previous key frame
            if (av_seek_frame(ffmpegVideoFile,-1,int64_t(Position*1000-1000000),0)<0) {
                // Try in AVSEEK_FLAG_ANY mode
                if (av_seek_frame(ffmpegVideoFile,-1,int64_t(Position*1000-1000000),AVSEEK_FLAG_ANY)<0) {
                    ToLog(LOGMSG_CRITICAL,"Error in cVideoFile::ReadVideoFrame : Seek error");
                }
            }
        }
    } else {
        DataInBuffer=true;
    }

    //*************************************************************************************************************************************
    // Decoding process : Get StreamPacket until endposition is reach (if sound is wanted) or until image is ok (if image only is wanted)
    //*************************************************************************************************************************************
    bool    Continue        =true;
    bool    IsVideoFind     =false;
    double  FrameTimeBase   =av_q2d(VideoStream->time_base);;
    double  FramePosition   =0;

    while (Continue) {
        StreamPacket=new AVPacket();
        av_init_packet(StreamPacket);
        StreamPacket->flags|=AV_PKT_FLAG_KEY;  // HACK for CorePNG to decode as normal PNG by default

        if (av_read_frame(ffmpegVideoFile,StreamPacket)==0) {

            if (StreamPacket->stream_index==VideoStreamNumber) {
                #if LIBAVFILTER_VERSION_INT>=AV_VERSION_INT(3,1,0)
                if (FrameBufferYUV->opaque) {
                    avfilter_unref_buffer((AVFilterBufferRef *)FrameBufferYUV->opaque);
                    FrameBufferYUV->opaque=NULL;
                }
                #endif

                int FrameDecoded=0;
                if (avcodec_decode_video2(VideoStream->codec,FrameBufferYUV,&FrameDecoded,StreamPacket)<0)
                    ToLog(LOGMSG_INFORMATION,"IN:cVideoFile::ReadVideoFrame : avcodec_decode_video2 return an error");

                if (FrameDecoded>0) {
                    DataInBuffer=true;
                    int64_t pts=AV_NOPTS_VALUE;
                    if ((FrameBufferYUV->pkt_dts==(int64_t)AV_NOPTS_VALUE)&&(FrameBufferYUV->pkt_pts!=(int64_t)AV_NOPTS_VALUE)) pts = FrameBufferYUV->pkt_pts; else pts = FrameBufferYUV->pkt_dts;
                    if (pts==(int64_t)AV_NOPTS_VALUE) pts = 0;
                    FramePosition=double(pts)*FrameTimeBase;

                    // Create image
                    if ((FramePosition>=dPosition)||(FramePosition>=dEndFile)) {

                        //*****************************************************************************************************************
                        // Video filter part
                        //*****************************************************************************************************************
                        #ifdef VIDEO_LIBAVFILTER
                        if ((VideoFilterGraph==NULL)&&(Deinterlace)) {
                            SetFilters(FILTER_DEINTERLACE_YADIF);
                            m_filters=m_filters_next;
                            VideoFilter_Open(m_filters);
                        } else if ((VideoFilterGraph!=NULL)&&(!Deinterlace)) VideoFilter_Close();
                        if ((VideoFilterGraph)&&(Deinterlace)) VideoFilter_Process();
                        #endif
                        //*****************************************************************************************************************
                        FrameBufferYUVReady   =true;                            // Keep actual value for FrameBufferYUV
                        FrameBufferYUVPosition=int(FramePosition*1000);         // Keep actual value for FrameBufferYUV
                        RetImage              =ConvertYUVToRGB(PreviewMode);    // Create RetImage from YUV Buffer
                        IsVideoFind           =(RetImage!=NULL);
                    }

                }

            }
            // Check if we need to continue loop
            Continue=(IsVideoFind==false)&&(FramePosition<dEndFile);

        } else {

            // if error in av_read_frame(...) then may be we have reach the end of file !
            Continue=false;
            // Create image
            if (DataInBuffer) {

                FrameBufferYUVReady   =true;                            // Keep actual value for FrameBufferYUV
                FrameBufferYUVPosition=int(FramePosition*1000);         // Keep actual value for FrameBufferYUV
                RetImage              =ConvertYUVToRGB(PreviewMode);    // Create RetImage from YUV Buffer
                IsVideoFind           =(RetImage!=NULL);

                if (IsVideoFind) dEndFileCachePos=dEndFile;         // keep position for future use
            }
        }

        if (IsVideoFind) {
            ObjectGeometry=IMAGE_GEOMETRY_UNKNOWN;
            double RatioHW=double(RetImage->width())/double(RetImage->height());
            if ((RatioHW>=1.45)&&(RatioHW<=1.55))           ObjectGeometry=IMAGE_GEOMETRY_3_2;
            else if ((RatioHW>=0.65)&&(RatioHW<=0.67))      ObjectGeometry=IMAGE_GEOMETRY_2_3;
            else if ((RatioHW>=1.32)&&(RatioHW<=1.34))      ObjectGeometry=IMAGE_GEOMETRY_4_3;
            else if ((RatioHW>=0.74)&&(RatioHW<=0.76))      ObjectGeometry=IMAGE_GEOMETRY_3_4;
            else if ((RatioHW>=1.77)&&(RatioHW<=1.79))      ObjectGeometry=IMAGE_GEOMETRY_16_9;
            else if ((RatioHW>=0.56)&&(RatioHW<=0.58))      ObjectGeometry=IMAGE_GEOMETRY_9_16;
            else if ((RatioHW>=2.34)&&(RatioHW<=2.36))      ObjectGeometry=IMAGE_GEOMETRY_40_17;
            else if ((RatioHW>=0.42)&&(RatioHW<=0.44))      ObjectGeometry=IMAGE_GEOMETRY_17_40;
        }

        // Continue with a new one
        if (StreamPacket!=NULL) {
            av_free_packet(StreamPacket); // Free the StreamPacket that was allocated by previous call to av_read_frame
            delete StreamPacket;
            StreamPacket=NULL;
        }
    }

    if ((!IsVideoFind)&&(!RetImage)) {
        ToLog(LOGMSG_CRITICAL,QString("No video image return for position %1 => return black frame").arg(Position));
        RetImage =new QImage(ffmpegVideoFile->streams[VideoStreamNumber]->codec->width,ffmpegVideoFile->streams[VideoStreamNumber]->codec->height,QImage::Format_ARGB32_Premultiplied);
        RetImage->fill(0);
    } else {
        if (PreviewMode) {
            while (CacheImage.count()>=MAXCACHEIMAGE) CacheImage.removeFirst();
            CacheImage.append(cImageInCache(Position,RetImage));
        }
    }

    dEndFileCachePos=dEndFile;  // keep position for future use

    return RetImage;
}

//====================================================================================================================
//#define PIXFMT      PIX_FMT_BGRA
//#define QTPIXFMT    QImage::Format_ARGB32_Premultiplied
#define PIXFMT      PIX_FMT_RGB24
#define QTPIXFMT    QImage::Format_RGB888

QImage *cVideoFile::ConvertYUVToRGB(bool PreviewMode) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::ConvertYUVToRGB");

    int W   =ffmpegVideoFile->streams[VideoStreamNumber]->codec->width;
    int H   =ffmpegVideoFile->streams[VideoStreamNumber]->codec->height;
    if (ffmpegVideoFile->streams[VideoStreamNumber]->codec->lowres==1) {
        W/=2;
        H/=2;
    }
    int NewW=W;
    int NewH=H;
    // Reduce image size for preview mode
    if (PreviewMode && (H>576)) { if ((H==1088)&&(W=1920)) { NewH=542; NewW=960; } else { NewH=540; NewW=NewH*(double(W)/double(H)); } }    // H=540
    //if (PreviewMode && (H>270)) { if ((H==1088)&&(W=1920)) { NewH=271; NewW=480; } else { NewH=270; NewW=NewH*(double(W)/double(H)); } }    // H=270

    QImage   RetImage(NewW,NewH,QTPIXFMT);
    AVFrame *FrameBufferRGB =avcodec_alloc_frame();  // Allocate structure for RGB image

    if (FrameBufferRGB!=NULL) {

        avpicture_fill(
                (AVPicture *)FrameBufferRGB,        // Buffer to prepare
                RetImage.bits(),                    // Buffer which will contain the image data
                PIXFMT,                             // The format in which the picture data is stored (see http://wiki.aasimon.org/doku.php?id=ffmpeg:pixelformat)
                NewW,                               // The width of the image in pixels
                NewH                                // The height of the image in pixels
        );

        // Get a converter from libswscale
        struct SwsContext *img_convert_ctx=sws_getContext(
            W,H,ffmpegVideoFile->streams[VideoStreamNumber]->codec->pix_fmt,        // Src Widht,Height,Format
            NewW,NewH,PIXFMT,                                                             // Destination Width,Height,Format
            SWS_FAST_BILINEAR/*SWS_BICUBIC*/,                                       // flags
            NULL,NULL,NULL);                                                        // src Filter,dst Filter,param

        if (img_convert_ctx!=NULL) {
            int ret = sws_scale(
                img_convert_ctx,                                                    // libswscale converter
                FrameBufferYUV->data,                                               // Source buffer
                FrameBufferYUV->linesize,                                           // Source Stride ?
                0,                                                                  // Source SliceY:the position in the source image of the slice to process, that is the number (counted starting from zero) in the image of the first row of the slice
                H,                                                                  // Source SliceH:the height of the source slice, that is the number of rows in the slice
                FrameBufferRGB->data,                                               // Destination buffer
                FrameBufferRGB->linesize                                            // Destination Stride
            );
            if (ret>0) {
                if      ((ApplicationConfig->Crop1088To1080)&&(RetImage.height()==1088)&&(RetImage.width()==1920))  RetImage=RetImage.copy(0,4,1920,1080);
                else if ((ApplicationConfig->Crop1088To1080)&&(RetImage.height()==542)&&(RetImage.width()==960))    RetImage=RetImage.copy(0,2,960,540);
                //else if ((ApplicationConfig->Crop1088To1080)&&(RetImage.height()==271)&&(RetImage.width()==480)) RetImage=RetImage.copy(0,1,480,270);
                //FinalImage=new QImage(RetImage.convertToFormat(QImage::Format_ARGB32_Premultiplied)); // Force to ARGB32
            }
            sws_freeContext(img_convert_ctx);
        }

        // free FrameBufferRGB because we don't need it in the future
        av_free(FrameBufferRGB);
    }

    //return FinalImage;
    return new QImage(RetImage);
}

//====================================================================================================================
//DontUseEndPos default=false
QImage *cVideoFile::ImageAt(bool PreviewMode,qlonglong Position,qlonglong StartPosToAdd,cSoundBlockList *SoundTrackBloc,bool Deinterlace,
                            double Volume,bool ForceSoundOnly,bool DontUseEndPos) {

    ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::ImageAt");

    if (!IsValide) return NULL;
    if (!IsOpen) OpenCodecAndFile();

    // Load a video frame
    QImage *LoadedImage=NULL;

    if ((SoundTrackBloc)&&(SoundTrackBloc->NbrPacketForFPS)&&(SoundTrackBloc->List.count()<SoundTrackBloc->NbrPacketForFPS))
        ReadAudioFrame(PreviewMode,Position+StartPosToAdd,SoundTrackBloc,Volume,DontUseEndPos);


    if ((!MusicOnly)&&(!ForceSoundOnly)) {
        LoadedImage=ReadVideoFrame(PreviewMode,Position+StartPosToAdd,DontUseEndPos,Deinterlace);
        if (LoadedImage) {

            // If preview mode and image size > PreviewMaxHeight, reduce Cache Image
            if ((PreviewMode)&&(ImageHeight>PREVIEWMAXHEIGHT)) {
                QImage *NewImage=new QImage(LoadedImage->scaledToHeight(PREVIEWMAXHEIGHT));
                delete LoadedImage;
                LoadedImage =NewImage;
            }

            // Scale image if anamorphous
            if (AspectRatio!=1) {
                ImageWidth =int(double(LoadedImage->width())*AspectRatio);
                ImageHeight=LoadedImage->height();
                QImage *NewLoadedImage=new QImage(LoadedImage->scaled(ImageWidth,ImageHeight,Qt::IgnoreAspectRatio,Qt::SmoothTransformation));
                delete LoadedImage;
                LoadedImage=NewLoadedImage;
            }
        }

    }

    return LoadedImage;
}

//====================================================================================================================

bool cVideoFile::OpenCodecAndFile() {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cVideoFile::OpenCodecAndFile");

    // Ensure file was previously checked
    if (!IsValide) return false;
    if (!IsInformationValide) GetFullInformationFromFile();

    // Clean memory if a previous file was loaded
    CloseCodecAndFile();

    //**********************************

    // Open audio stream
    if (AudioStreamNumber!=-1) {
        // if file exist then Open video file and get a LibAVFormat context and an associated LibAVCodec decoder
        if (avformat_open_input(&ffmpegAudioFile,FileName.toLocal8Bit(),NULL,NULL)!=0) return false;

        ffmpegAudioFile->flags|=AVFMT_FLAG_GENPTS;       // Generate missing pts even if it requires parsing future NbrFrames.

        if (avformat_find_stream_info(ffmpegAudioFile,NULL)<0) {
            #ifdef LIBAV_07
            av_close_input_file(ffmpegAudioFile);
            #endif
            #ifdef LIBAV_08
            avformat_close_input(&ffmpegAudioFile);
            #endif
            return false;
        }

        // Setup STREAM options
        ffmpegAudioFile->streams[AudioStreamNumber]->discard=AVDISCARD_DEFAULT;

        // Find the decoder for the audio stream and open it
        AudioDecoderCodec=avcodec_find_decoder(ffmpegAudioFile->streams[AudioStreamNumber]->codec->codec_id);
        IsVorbis=(strcmp(AudioDecoderCodec->name,"vorbis")==0);

        // Setup decoder options
        ffmpegAudioFile->streams[AudioStreamNumber]->codec->debug_mv         =0;                    // Debug level (0=nothing)
        ffmpegAudioFile->streams[AudioStreamNumber]->codec->debug            =0;                    // Debug level (0=nothing)
        ffmpegAudioFile->streams[AudioStreamNumber]->codec->workaround_bugs  =1;                    // Work around bugs in encoders which sometimes cannot be detected automatically : 1=autodetection
        ffmpegAudioFile->streams[AudioStreamNumber]->codec->idct_algo        =FF_IDCT_AUTO;         // IDCT algorithm, 0=auto
        ffmpegAudioFile->streams[AudioStreamNumber]->codec->skip_frame       =AVDISCARD_DEFAULT;    // ???????
        ffmpegAudioFile->streams[AudioStreamNumber]->codec->skip_idct        =AVDISCARD_DEFAULT;    // ???????
        ffmpegAudioFile->streams[AudioStreamNumber]->codec->skip_loop_filter =AVDISCARD_DEFAULT;    // ???????
        ffmpegAudioFile->streams[AudioStreamNumber]->codec->error_concealment=3;

        if ((AudioDecoderCodec==NULL)||(avcodec_open2(ffmpegAudioFile->streams[AudioStreamNumber]->codec,AudioDecoderCodec,NULL)<0)) return false;
        IsOpen=true;
    }

    // Open video stream
    if ((VideoStreamNumber!=-1)&&(!MusicOnly)) {
        IsMTS=(FileName.endsWith(".mts",Qt::CaseInsensitive) || FileName.endsWith(".m2ts",Qt::CaseInsensitive));

        // if file exist then Open video file and get a LibAVFormat context and an associated LibAVCodec decoder
        if (avformat_open_input(&ffmpegVideoFile,FileName.toLocal8Bit(),NULL,NULL)!=0) return false;

        ffmpegVideoFile->flags|=AVFMT_FLAG_GENPTS;       // Generate missing pts even if it requires parsing future NbrFrames.

        if (avformat_find_stream_info(ffmpegVideoFile,NULL)<0) {
            #ifdef LIBAV_07
            av_close_input_file(ffmpegVideoFile);
            #endif
            #ifdef LIBAV_08
            avformat_close_input(&ffmpegVideoFile);
            #endif
            return false;
        }

        // Setup STREAM options
        ffmpegVideoFile->streams[VideoStreamNumber]->discard=AVDISCARD_DEFAULT;

        // Find the decoder for the video stream and open it
        VideoDecoderCodec=avcodec_find_decoder(ffmpegVideoFile->streams[VideoStreamNumber]->codec->codec_id);

        // Setup decoder options

        ffmpegVideoFile->streams[VideoStreamNumber]->codec->debug_mv         =0;                    // Debug level (0=nothing)
        ffmpegVideoFile->streams[VideoStreamNumber]->codec->debug            =0;                    // Debug level (0=nothing)
        ffmpegVideoFile->streams[VideoStreamNumber]->codec->workaround_bugs  =1;                    // Work around bugs in encoders which sometimes cannot be detected automatically : 1=autodetection
        ffmpegVideoFile->streams[VideoStreamNumber]->codec->idct_algo        =FF_IDCT_AUTO;         // IDCT algorithm, 0=auto
        ffmpegVideoFile->streams[VideoStreamNumber]->codec->skip_frame       =AVDISCARD_DEFAULT;    // ???????
        ffmpegVideoFile->streams[VideoStreamNumber]->codec->skip_idct        =AVDISCARD_DEFAULT;    // ???????
        ffmpegVideoFile->streams[VideoStreamNumber]->codec->skip_loop_filter =AVDISCARD_DEFAULT;    // ???????
        ffmpegVideoFile->streams[VideoStreamNumber]->codec->error_concealment=3;

        // h264 specific
        ffmpegVideoFile->streams[VideoStreamNumber]->codec->thread_count     =getCpuCount();
        ffmpegVideoFile->streams[VideoStreamNumber]->codec->thread_type      =FF_THREAD_SLICE;
        //ffmpegVideoFile->streams[VideoStreamNumber]->codec->skip_loop_filter =AVDISCARD_BIDIR;

        // Hack to correct wrong frame rates that seem to be generated by some codecs
        if (ffmpegVideoFile->streams[VideoStreamNumber]->codec->time_base.num>1000 && ffmpegVideoFile->streams[VideoStreamNumber]->codec->time_base.den==1) ffmpegVideoFile->streams[VideoStreamNumber]->codec->time_base.den=1000;

        if ((VideoDecoderCodec==NULL)||(avcodec_open2(ffmpegVideoFile->streams[VideoStreamNumber]->codec,VideoDecoderCodec,NULL)<0)) {
            CloseCodecAndFile();
            return false;
        }

        // Get Aspect Ratio
        AspectRatio=double(ffmpegVideoFile->streams[VideoStreamNumber]->codec->sample_aspect_ratio.num)/double(ffmpegVideoFile->streams[VideoStreamNumber]->codec->sample_aspect_ratio.den);

        if (ffmpegVideoFile->streams[VideoStreamNumber]->sample_aspect_ratio.num!=0)
            AspectRatio=double(ffmpegVideoFile->streams[VideoStreamNumber]->sample_aspect_ratio.num)/double(ffmpegVideoFile->streams[VideoStreamNumber]->sample_aspect_ratio.den);

        if (AspectRatio==0) AspectRatio=1;

        // Special case for DVD mode video without PAR
        if ((AspectRatio==1)&&(ffmpegVideoFile->streams[VideoStreamNumber]->codec->coded_width==720)&&(ffmpegVideoFile->streams[VideoStreamNumber]->codec->coded_height==576))
            AspectRatio=double((576/3)*4)/720;

        IsOpen=true;

        // Try to load one image to be sure we can make something with this file

        qlonglong Position=0;
        if (QTime(0,0,0,0).msecsTo(Duration)>500) Position=500;   // If video is > 0.5 sec then get image at 0.5 sec
        QImage *Img =ImageAt(true,Position,0,NULL,false,1,false,false);
        if (Img) {
            // Get information about size image
            ImageWidth =ffmpegVideoFile->streams[VideoStreamNumber]->codec->coded_width;    //Img->width();
            ImageHeight=ffmpegVideoFile->streams[VideoStreamNumber]->codec->coded_height;   //Img->height();
            // Compute image geometry
            ObjectGeometry=IMAGE_GEOMETRY_UNKNOWN;
            double RatioHW=double(ImageWidth)/double(ImageHeight);
            if ((RatioHW>=1.45)&&(RatioHW<=1.55))           ObjectGeometry=IMAGE_GEOMETRY_3_2;
            else if ((RatioHW>=0.65)&&(RatioHW<=0.67))      ObjectGeometry=IMAGE_GEOMETRY_2_3;
            else if ((RatioHW>=1.32)&&(RatioHW<=1.34))      ObjectGeometry=IMAGE_GEOMETRY_4_3;
            else if ((RatioHW>=0.74)&&(RatioHW<=0.76))      ObjectGeometry=IMAGE_GEOMETRY_3_4;
            else if ((RatioHW>=1.77)&&(RatioHW<=1.79))      ObjectGeometry=IMAGE_GEOMETRY_16_9;
            else if ((RatioHW>=0.56)&&(RatioHW<=0.58))      ObjectGeometry=IMAGE_GEOMETRY_9_16;
            else if ((RatioHW>=2.34)&&(RatioHW<=2.36))      ObjectGeometry=IMAGE_GEOMETRY_40_17;
            else if ((RatioHW>=0.42)&&(RatioHW<=0.44))      ObjectGeometry=IMAGE_GEOMETRY_17_40;
            // Icon
            if (Icon16.isNull()) {
                QImage Final=(ApplicationConfig->Video_ThumbWidth==162?ApplicationConfig->VideoMask_162:ApplicationConfig->Video_ThumbWidth==150?ApplicationConfig->VideoMask_150:ApplicationConfig->VideoMask_120).copy();
                QImage ImgF;
                if (Img->width()>Img->height()) ImgF=Img->scaledToWidth(ApplicationConfig->Video_ThumbWidth-2,Qt::SmoothTransformation);
                    else                        ImgF=Img->scaledToHeight(ApplicationConfig->Video_ThumbHeight*0.7,Qt::SmoothTransformation);
                QPainter Painter;
                Painter.begin(&Final);
                Painter.drawImage(QRect((Final.width()-ImgF.width())/2,(Final.height()-ImgF.height())/2,ImgF.width(),ImgF.height()),ImgF);
                Painter.end();
                LoadIcons(&Final);
            }
            delete Img;

        } else {
            CloseCodecAndFile();
            return false;
        }
    }

    return IsOpen;
}

//*********************************************************************************************************************************************
// Base object for music definition
//*********************************************************************************************************************************************

cMusicObject::cMusicObject(cBaseApplicationConfig *ApplicationConfig):cVideoFile(OBJECTTYPE_MUSICFILE,ApplicationConfig) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cMusicObject::cMusicObject");

    Volume=1.0;                           // Volume as % from 1% to 150%
}

//====================================================================================================================

void cMusicObject::SaveToXML(QDomElement &domDocument,QString ElementName,QString PathForRelativPath,bool ForceAbsolutPath) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cMusicObject::SaveToXML");

    QDomDocument    DomDocument;
    QDomElement     Element=DomDocument.createElement(ElementName);
    QString         TheFileName;

    if (PathForRelativPath!="") {
        if (ForceAbsolutPath) TheFileName=QDir(QFileInfo(PathForRelativPath).absolutePath()).absoluteFilePath(FileName);
            else TheFileName=QDir(QFileInfo(PathForRelativPath).absolutePath()).relativeFilePath(FileName);
    } else TheFileName=FileName;

    Element.setAttribute("FilePath",TheFileName);
    Element.setAttribute("StartPos",StartPos.toString());
    Element.setAttribute("EndPos",  EndPos.toString());
    Element.setAttribute("Volume",  QString("%1").arg(Volume,0,'f'));

    domDocument.appendChild(Element);
}

//====================================================================================================================

bool cMusicObject::LoadFromXML(QDomElement domDocument,QString ElementName,QString PathForRelativPath,QStringList *AliasList,bool *ModifyFlag) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cMusicObject::LoadFromXML");

    if ((domDocument.elementsByTagName(ElementName).length()>0)&&(domDocument.elementsByTagName(ElementName).item(0).isElement()==true)) {
        QDomElement Element=domDocument.elementsByTagName(ElementName).item(0).toElement();

        FileName=Element.attribute("FilePath","");
        if (PathForRelativPath!="") FileName=QDir::cleanPath(QDir(PathForRelativPath).absoluteFilePath(FileName));
        if (LoadMedia(FileName,AliasList,ModifyFlag)) {
            StartPos=QTime().fromString(Element.attribute("StartPos"));
            EndPos  =QTime().fromString(Element.attribute("EndPos"));
            Volume  =Element.attribute("Volume").toDouble();
            return true;
        } else return false;
    } else return false;
}

//====================================================================================================================

bool cMusicObject::LoadMedia(QString &TheFilename,QStringList *AliasList,bool *ModifyFlag) {
    ToLog(LOGMSG_DEBUGTRACE,"IN:cMusicObject::LoadMedia");

    IsValide=(GetInformationFromFile(TheFilename,AliasList,ModifyFlag))&&(OpenCodecAndFile());
    return IsValide;
}