ProjectModel.cpp 80.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108
#include <QSize>
#include <QFile>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QDebug>
#include <QMediaPlayer>
#include <QProgressDialog>
#include <QRegularExpression>
#include <QDir>
#include <QProcess>

#include <string>
#include <regex>
#include <iostream>

#include "ProjectModel.h"
#include "Season.h"
#include "Scene.h"
#include "Shot.h"
#include "ResultsDialog.h"

using namespace std;
using namespace arma;

/////////////////
// constructor //
/////////////////

ProjectModel::ProjectModel(QObject *parent)
  : QAbstractItemModel(parent),
    m_name(QString()),
    m_baseName(QString())
{
  m_series = new Series;
  m_movieAnalyzer = new MovieAnalyzer;
  connect(m_movieAnalyzer, SIGNAL(setResolution(const QSize &)), this, SLOT(setResolution(const QSize &)));
  connect(m_movieAnalyzer, SIGNAL(setFps(qreal)), this, SLOT(setFps(qreal)));
  connect(m_movieAnalyzer, SIGNAL(appendVideoFrame(int, qint64)), this, SLOT(appendVideoFrame(int, qint64)));
  connect(m_movieAnalyzer, SIGNAL(insertShot(qint64, Segment::Source)), this, SLOT(insertShot(qint64, Segment::Source)));
  connect(m_movieAnalyzer, SIGNAL(labelSimShot(qint64, int, Segment::Source)), this, SLOT(labelSimShot(qint64, int, Segment::Source)));
  connect(m_movieAnalyzer, SIGNAL(setSpeaker(qint64, qint64, const QString &, VideoFrame::SpeakerSource)), this, SLOT(setSpeaker(qint64, qint64, const QString &, VideoFrame::SpeakerSource)));
  connect(m_movieAnalyzer, SIGNAL(playSegments(QList<QPair<qint64, qint64>>)), this, SLOT(playSeg(QList<QPair<qint64, qint64>>)));
  connect(this, SIGNAL(setDiarData(const arma::mat, const arma::mat, const arma::mat)), m_movieAnalyzer, SLOT(setDiarData(const arma::mat, const arma::mat, const arma::mat)));
  connect(this, SIGNAL(setDiarData(const arma::mat, const arma::mat, const arma::mat, QMap<QString, QList<QPair<qreal, qreal>>>)), m_movieAnalyzer, SLOT(setDiarData(const arma::mat, const arma::mat, const arma::mat, QMap<QString, QList<QPair<qreal, qreal>>>)));
}

////////////////
// destructor //
////////////////

ProjectModel::~ProjectModel()
{
  delete m_series;
}

/////////////////////////
// save / open methods //
/////////////////////////

bool ProjectModel::save(const QString &fName)
{
  QFile saveFile(fName + ".json");
  // QFile saveFile(fName + ".dat");

  if (!saveFile.open(QIODevice::WriteOnly)) {
    qWarning("Couldn't open save file.");
    return false;
  }

  QJsonObject projObject;
  projObject["name"] = m_name;

  QJsonObject seriesObject;
  m_series->write(seriesObject);
  projObject["series"] = seriesObject;

  QJsonDocument saveDoc(projObject);
  saveFile.write(saveDoc.toJson());
  // saveFile.write(saveDoc.toBinaryData());
  
  return true;
}

bool ProjectModel::load(const QString &fName)
{
  QFile loadFile(fName);

  if (!loadFile.open(QIODevice::ReadOnly)) {
    qWarning("Couldn't open save file.");
    return false;
  }

  QByteArray saveData = loadFile.readAll();

  QJsonDocument loadDoc(QJsonDocument::fromJson(saveData));
  // QJsonDocument loadDoc(QJsonDocument::fromBinaryData(saveData));
  QJsonObject projObject = loadDoc.object();
  
  m_name = projObject["name"].toString();
  QJsonObject seriesObject = projObject["series"].toObject();
  
  m_series->read(seriesObject);

  QList<qint64> subStarts;
  QList<qint64> subEnds;

  retrieveSubPositionsLabels(subStarts, subEnds, m_subRefLbl);

  for (int i(0); i < subStarts.size(); i++)
    m_subBound.push_back(QPair<qint64, qint64>(subStarts[i], subEnds[i]));
  
  retrieveShotUtterances();
  retrieveShotPatterns();
  
  return true;
}

//////////////////////////////////////////
// reimplementation of abstract methods //
//  inherited from QAbstractItemModel   //
//////////////////////////////////////////

QModelIndex ProjectModel::index(int row, int column, const QModelIndex &parent) const
{
  if (!hasIndex(row, column, parent))
    return QModelIndex();

  Segment *parentSegment;

  if (!parent.isValid())
    parentSegment = m_series;
  else
    parentSegment = static_cast<Segment *>(parent.internalPointer());

  Segment *childSegment = parentSegment->child(row);

  if (childSegment )
    return createIndex(row, column, childSegment);
  else
    return QModelIndex();
}

QModelIndex ProjectModel::parent(const QModelIndex &child) const
{
  if (!child.isValid())
    return QModelIndex();
  
  Segment *childSegment = static_cast<Segment *>(child.internalPointer());
  Segment *parentSegment = childSegment->parent();

  if (parentSegment == m_series)
    return QModelIndex();

  return createIndex(parentSegment->row(), 0, parentSegment);
}

int ProjectModel::rowCount(const QModelIndex &parent) const
{
  Segment *parentSegment;

  if (!parent.isValid())
    parentSegment = m_series;
  else
    parentSegment = static_cast<Segment *>(parent.internalPointer());

  return parentSegment->childCount();
}

int ProjectModel::columnCount(const QModelIndex &parent) const
{
  Q_UNUSED(parent)

  return 2;
}

QVariant ProjectModel::data(const QModelIndex &index, int role) const
{
  if (!index.isValid())
    return QVariant();

  Segment *segment = static_cast<Segment *>(index.internalPointer());

  switch (role) {
  case Qt::DisplayRole:
    if (index.column() == 0)
      return segment->display();
    else
      return segment->getFormattedPosition();
    break;
  case Qt::ForegroundRole:
    if (index.column() == 1) {
      QBrush grayForeground(Qt::gray);
      return grayForeground;
    }
    break;
  case Qt::FontRole:
    QFont font;
    if (segment->getSource() == Segment::Automatic)
      font.setItalic(true);
    else if (segment->getSource() == Segment::Both)
      font.setBold(true);
    return font;
    break;
  }
   
  return QVariant();
}

QVariant ProjectModel::headerData(int section, Qt::Orientation orientation, int role) const
{
  if (orientation == Qt::Horizontal && role == Qt::DisplayRole && section == 0)
    return m_series->display();

  return QVariant();
}

Qt::ItemFlags ProjectModel::flags(const QModelIndex &index) const
{
  if (!index.isValid())
    return 0;
  
  return QAbstractItemModel::flags(index);
}

QModelIndex ProjectModel::indexFromSegment(Segment *segment) const
{
  if (segment->parent() == m_series)
    return index(0, 0);

  return index(segment->row(), 0, indexFromSegment(segment->parent()));
}

int ProjectModel::getDepth() const
{
  return m_series->getHeight();
}

QModelIndex ProjectModel::getShotParentIndex() const
{
  Segment *segment = m_series;

  while (!dynamic_cast<Shot *>(segment))
    segment = segment->child(0);

  segment = segment->parent();

  return indexFromSegment(segment);
}

///////////////
// modifiers //
///////////////

void ProjectModel::setModel(const QString &name, const QString &seriesName, int seasNbr, 
			    int epNbr, const QString &epName, const QString &epFName)
{
  m_name = name;
  m_series->setName(seriesName);
  Season *season = new Season(seasNbr, m_series);
  m_series->appendChild(season);
  m_episode = new Episode(epNbr, epFName, season, epName);
  season->appendChild(m_episode);
  m_movieAnalyzer->extractVideoFrames(epFName);
}

bool ProjectModel::appendModel(int seasNbr, int epNbr, const QString &epName, const QString &epFName)
{
  QList<Segment *> seasonList = m_series->getChildren();
  int i(0);

  while (i < seasonList.size() && seasNbr < seasonList[i]->getNumber())
    i++;

  // new season
  if (i == seasonList.size()) {
    Season *season = new Season(seasNbr, m_series);
    m_series->appendChild(season);
    m_episode = new Episode(epNbr, epFName, season, epName);
    season->appendChild(m_episode);
    m_movieAnalyzer->extractVideoFrames(epFName);
  }
  // same season
  else {
    QList<Segment *> episodeList = seasonList[i]->getChildren();
    int j(0);
    
    while (j < episodeList.size() && episodeList[i]->getNumber() != epNbr)
      j++;

    // new episode
    if (j == episodeList.size()) {
      m_episode = new Episode(epNbr, epFName, seasonList[i], epName);
      seasonList[i]->appendChild(m_episode);

      m_movieAnalyzer->extractVideoFrames(epFName);
    }
    // episode already recorded
    else
      return false;
  }

  return true;
}

bool ProjectModel::insertSubtitles(const QString &subFName)
{
  QJsonObject subObject;
  qint64 position;
  qint64 start;
  QString text;
  qint64 end;
  QStringList sources;
  QList<int> absLength;
  QList<qreal> relLength;
  qreal proportion;
  int totLength;
  qreal startShift(-0.38);
  qreal endShift(-0.5);

  int j;
  Segment *segment;
  VideoFrame *vFrame;

  // regular expression to detect subtitles corresponding to noise
  std::regex noiseSource("\\(.*\\)");

  // regular expression to detect subtitles with multiple speakers 
  std::regex multSources("-.+<br />-.+");

  // regular expression to detect speaker turn into subtitle
  std::regex spkTurn("(- *)(.*)");

  eraseSubtitles(m_series);
  clearSpeaker(m_series, VideoFrame::Ref);

  QFile loadFile(subFName);

  if (!loadFile.open(QIODevice::ReadOnly)) {
    qWarning("Couldn't open subtitles file.");
    return false;
  }

  QByteArray saveData = loadFile.readAll();

  QJsonDocument loadDoc(QJsonDocument::fromJson(saveData));
  QJsonArray subArray = loadDoc.array();
  
  for (int i(0); i < subArray.size(); i++) {

    sources.clear();
    absLength.clear();
    relLength.clear();
    totLength = 0;
    proportion = 0.0;

    subObject = subArray[i].toObject();
    start = (subObject["start"].toDouble() + startShift) * 1000;
    if (start < 0)
      start = 0;
    start = qRound(start / 10.0) * 10;
    end = (subObject["end"].toDouble() + endShift) * 1000;
    end = qRound(end / 10.0) * 10;
    text = subObject["text"].toString();
 
    // case of multiple source in current subtitle
    if (regex_match(text.toStdString(), multSources)) {

      // split subtitle contents
      sources = text.split("<br />");
      
      // removing hyphenation indicating speaker turn
      for (int k(0); k < sources.size(); k++) {
	sources[k] = sources[k].replace(0, 1, "");
	while (sources[k].indexOf(" ") == 0)
	  sources[k] = sources[k].replace(0, 1, "");
      }

      // estimate absolute length of each contents
      for (int k(0); k < sources.size(); k++) {
	absLength.push_back((sources[k]).count(" ") + 1);
	totLength += absLength[k];
      }

      // estimate relative length of each contents
      for (int k(0); k < sources.size(); k++)
	relLength.push_back(absLength[k] / static_cast<qreal>(totLength));

      // boundaries of each interval
      for (int k(1); k < sources.size(); k++)
	relLength[k] += relLength[k-1];
    }
    
    segment = m_series;

    while (!(vFrame = dynamic_cast<VideoFrame *>(segment))) {

      // video frame at start position
      j = segment->childIndexFromPosition(start);
      
      // select possible children
      segment = segment->child(j);
    }

    position = segment->getPosition();

    int k = 0;
    int prev = 0;

    while (position <= end) {

      segment = m_series;

      while (!(vFrame = dynamic_cast<VideoFrame *>(segment))) {

	// video frame at start position
	j = segment->childIndexFromPosition(position);
      
	// select possible children
	segment = segment->child(j);
      }

      proportion = (static_cast<qreal>(position) - start) / (end - start);

      if (relLength.size() >= 1) {
	while (relLength[k] < proportion)
	  k++;

	if (prev == k) {
	  vFrame->setSub(sources[k]);

	  if (!regex_match(sources[k].toStdString(), noiseSource))
	    vFrame->setSpeaker("S", VideoFrame::Ref);
	}
	
	prev = k;
      }
      
      else {
	vFrame->setSub(text);
	
	if (!regex_match(text.toStdString(), noiseSource))
	  vFrame->setSpeaker("S", VideoFrame::Ref);
      }

      position += 40;
    }
  }

  return true;
}

bool ProjectModel::localSpkDiar(bool baseline, UtteranceTree::DistType dist, bool norm, UtteranceTree::AgrCrit agr, UtteranceTree::PartMeth partMeth, bool weight, bool sigma)
{
  if (baseline)
    m_movieAnalyzer->localSpkDiarBaseline(m_shotPatterns, m_subBound, m_shotUtterances, m_strictShotPattBound, m_baseName);
  else
    m_movieAnalyzer->localSpkDiar(m_subBound, m_shotPatterns, m_strictShotPattBound, dist, norm, agr, partMeth, weight, sigma, m_baseName);

  return true;
}

bool ProjectModel::globalSpkDiar()
{
  m_movieAnalyzer->globalSpkDiar(m_baseName);

  return true;
}

bool ProjectModel::speakerDiarization(const QString &diarFName, VideoFrame::SpeakerSource source)
{
  qint64 start, position, end;
  QString speakerLabel;
  Segment *segment;
  VideoFrame *vFrame;
  int i(0);

  clearSpeaker(m_series, source);

  QFile file(diarFName);

  if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    return false;

  QTextStream in(&file);

  // parse hypotheses file

  while (!in.atEnd()) {

    QString line = in.readLine();
    QStringList data = line.split(" ");

    start = data[0].toDouble() * 1000;
    end = data[1].toDouble() * 1000;
    speakerLabel = data[2];

    segment = m_series;

    while (!(vFrame = dynamic_cast<VideoFrame *>(segment))) {

      // video frame at start position
      i = segment->childIndexFromPosition(start);
      
      // select possible children
      segment = segment->child(i);
    }

    position = segment->getPosition();

    while (position <= end) {

      segment = m_series;

      while (!(vFrame = dynamic_cast<VideoFrame *>(segment))) {

	// video frame at start position
	i = segment->childIndexFromPosition(position);
      
	// select possible children
	segment = segment->child(i);
      }

      vFrame->setSpeaker(speakerLabel, source);

      position += 40;
    }
  }

  return true;
}

void ProjectModel::extractShots(QString fName, int histoType, int nVBins, int nHBins, int nSBins, int metrics, qreal threshold1, qreal threshold2, int nVBlock, int nHBlock, bool iterate)
{
  qint64 posInit = 0;
  QList<Segment *> toRemove;

  resetShotsToManual(m_series, toRemove);
  for (int j(0); j < toRemove.count(); j++)
    removeShot(toRemove[j], Segment::Automatic);
  emit modelChanged();

  if (iterate) {

    // number of HSV tuples considered
    int nHsvTuples(1);

    // number of iterations
    int nIter = nHBlock * nHsvTuples * threshold1 * (threshold1 - 1) / 2;
    
    // optimal values oberved so far for the
    int nBlockMax(0);  // number of image blocks
    int nHMax(0);      // hue channel
    int nSMax(0);      // saturation channel     
    int nVMax(0);      // value channel
    int thresh1Max(0); // disimilarity treshold
    int thresh2Max(0); // similarity threshold

    // current and maximum F-Score observed so far
    qreal fScore(0);
    qreal fScoreMax(0);

    // iteration counter to update progress bar
    int cnt(0);

    // progress bar initialization
    QProgressDialog progress(tr("Extracting shots..."), tr("Cancel"), 0, nIter);
    progress.setWindowModality(Qt::WindowModal);

    // loop over the number of blocks
    while (nHBlock >= 1) {

      int currNHBins(nHBins);
      int currNSBins(nSBins);
      int currNVBins(nVBins);

      // loop over HSV possible values
      for (int i(0); i < nHsvTuples; i++) {

	int thresh1 = threshold1;

	// loop over disimilarity threshold between frames
	while (thresh1 >= 1) {

	  threshold2 = thresh1;

	  // loop over similarity threshold between frames
	  while (threshold2 >= 1) {

	    insertShot(posInit, Segment::Manual);

	    // extracting shots
	    m_movieAnalyzer->extractShots(fName, histoType, currNVBins, currNHBins, currNSBins, metrics, thresh1, threshold2, nHBlock, nHBlock, false);
	    
	    // evaluating extraction and updating optimal values
	    if ((fScore = evaluateShotDetection(false, thresh1, threshold2)) > fScoreMax) {
	      fScoreMax = fScore;
	      nBlockMax = nHBlock;
	      nHMax = currNHBins;
	      nSMax = currNSBins;
	      nVMax = currNVBins;
	      thresh1Max = thresh1;
	      thresh2Max = threshold2;
	  }

	    // displaying current results
	    qDebug() << nHBlock << currNHBins << currNSBins << currNVBins << thresh1 << threshold2 << fScore;

	    // removing inserted shots
	    toRemove.clear();
	    resetShotsToManual(m_series, toRemove);
	    for (int j(0); j < toRemove.count(); j++)
	      removeShot(toRemove[j], Segment::Automatic);
    
	    threshold2--;

	    progress.setValue(++cnt);
	  }

	  thresh1--;
	}
	
	currNHBins /= 2;
	currNSBins /= 2;
	currNVBins /= 2;
      }

      nHBlock--;
    }

    progress.setValue(nIter);

    // setting optimal parameters
    nVBlock = nBlockMax;
    nHBlock = nBlockMax;
    nHBins = nHMax;
    nSBins = nSMax;
    nVBins = nVMax;
    threshold1 = thresh1Max;
    threshold2 = thresh2Max;
  }
  
  insertShot(posInit, Segment::Manual);
  m_movieAnalyzer->extractShots(fName, histoType, nVBins, nHBins, nSBins, metrics, threshold1, threshold2, nVBlock, nHBlock);
  evaluateShotDetection(true, threshold1, threshold2);
}

void ProjectModel::labelSimilarShots(QString fName, int histoType, int nVBins, int nHBins, int nSBins, int metrics, qreal maxDist, int windowSize, int nVBlock, int nHBlock, bool iterate)
{
  resetAutoCameraLabels(m_series);
  
  QList<qint64> shotPositions;
  retrieveShotPositions(m_series, shotPositions);
  
  if (iterate) {

    // number of HSV tuples considered
    int nHsvTuples(1);

    // number of iterations
    int nIter = nHBlock * nHsvTuples * maxDist * windowSize / 16;
    
    // optimal values oberved so far for the
    int nBlockMax(0);  // number of image blocks
    int nHMax(0);      // hue channel
    int nSMax(0);      // saturation channel     
    int nVMax(0);      // value channel
    int thresh1Max(0); // disimilarity threshold
    int thresh2Max(0); // window size

    // current and maximum F-Score observed so far
    qreal fScore(0);
    qreal fScoreMax(0);

    // iteration counter to update progress bar
    int cnt(0);

    // progress bar initialization
    QProgressDialog progress(tr("Retrieving similar shots..."), tr("Cancel"), 0, nIter);
    progress.setWindowModality(Qt::WindowModal);

    // loop over the number of blocks
    while (nHBlock >= 1) {

      int currNHBins(nHBins);
      int currNSBins(nSBins);
      int currNVBins(nVBins);

      // loop over HSV possible values
      for (int i(0); i < nHsvTuples; i++) {

	int threshold1 = static_cast<int>(maxDist);

	// loop over disimilarity threshold between frames
	while (threshold1 >= 1) {

	  int threshold2(windowSize);

	  // loop over window size
	  while (threshold2 >= 1) {

	    // retrieving similar shots
	    m_movieAnalyzer->labelSimilarShots(fName, histoType, currNVBins, currNHBins, currNSBins, metrics, threshold1, threshold2, shotPositions, nHBlock, nHBlock, false);

	    // evaluating extraction
	    if ((fScore = evaluateSimShotDetection(false, threshold1, threshold2)) >= fScoreMax) {
	      fScoreMax = fScore;
	      nBlockMax = nHBlock;
	      nHMax = currNHBins;
	      nSMax = currNSBins;
	      nVMax = currNVBins;
	      thresh1Max = threshold1;
	      thresh2Max = threshold2;
	    }

	    // displaying current results
	      
	    qDebug() << nHBlock << currNHBins << currNSBins << currNVBins << threshold1 << threshold2 << fScore;

	    // resetting shot similarities
	    resetAutoCameraLabels(m_series);
	    
	    threshold2--;

	    progress.setValue(++cnt);
	  }

	  threshold1--;
	}
	
	currNHBins /= 2;
	currNSBins /= 2;
	currNVBins /= 2;
      }

      nHBlock--;
    }

    progress.setValue(nIter);

    // setting optimal parameters
    nVBlock = nBlockMax;
    nHBlock = nBlockMax;
    nHBins = nHMax;
    nSBins = nSMax;
    nVBins = nVMax;
    maxDist = thresh1Max;
    windowSize = thresh2Max;
  }

  m_movieAnalyzer->labelSimilarShots(fName, histoType, nVBins, nHBins, nSBins, metrics, maxDist, windowSize, shotPositions, nVBlock, nHBlock, true);
  evaluateSimShotDetection(true, maxDist, windowSize);
}

qreal ProjectModel::evaluateShotDetection(bool displayResults, qreal thresh1, qreal thresh2) const
{
  Segment *season;
  Segment *episode;
  Segment *segment;

  int tp(0);
  int fp(0);
  int tn(0);
  int fn(0);
  int nShots(0);
  int nVideoFrames(0);

  qreal precision;
  qreal recall;
  qreal fScore;
  qreal accuracy;

  for (int i(0); i < m_series->childCount(); i++) {
    season = m_series->child(i);

    for (int j(0); j < season->childCount(); j++) {
      episode = season->child(j);
      
      for (int k(0); k < episode->childCount(); k++) {
	segment = episode->child(k);

	// no scene level
	if (dynamic_cast<Shot *>(segment)) {
	  nVideoFrames += segment->childCount();
	  nShots++; 
	  switch (segment->getSource()) {
	  case Segment::Both:
	    tp++;
	    break;
	  case Segment::Manual:
	    fn++;
	    break;
	  case Segment::Automatic:
	    fp++;
	    break;
	  }
	}
      }
    }
  }
  
  // decrement first frame
  nVideoFrames--;
  nShots--;
  fn--;
  tn = nVideoFrames - (tp + fp + fn);

  precision = computePrecision(tp, fp);
  recall = computeRecall(tp, fn);
  fScore = computeFScore(recall, precision);
  accuracy = computeAccuracy(tp, fp, fn, tn);

  if (displayResults) {
    ResultsDialog *dialog = new ResultsDialog(thresh1, thresh2, tp, fp, fn, tn, precision, recall, fScore, accuracy);
    dialog->exec();
  }

  return fScore;
}

qreal ProjectModel::evaluateSimShotDetection(bool displayResults, qreal thresh1, qreal thresh2) const
{
  int tp(0);
  int fp(0);
  int tn(0);
  int fn(0);

  qreal precision;
  qreal recall;
  qreal fScore;
  qreal accuracy;

  QList<int> autCamLabels;
  QList<int> manCamLabels;
  
  retrieveSimCamLabels(m_series, autCamLabels, manCamLabels);

  for (int i(0); i < autCamLabels.size(); i++) {

    if (manCamLabels[i] == -1 && autCamLabels[i] != -1)
      fp++;
    else if (manCamLabels[i] != -1 && autCamLabels[i] == -1)
      fn++;
    else if (manCamLabels[i] == -1 && autCamLabels[i] == -1)
      tn++;
    else {

      QList<int> manIdxSim;
      QList<int> autIdxSim;

      // lists of shots similar to current one, as manually and automatically annotated
      int j;
      for (j = 0; j < autCamLabels.size(); j++) {
	if (manCamLabels[i] == manCamLabels[j])
	  manIdxSim.push_back(j);
	if (autCamLabels[i] == autCamLabels[j])
	  autIdxSim.push_back(j);
      }
      
      // size of longest list
      int maxList = (autCamLabels.size() > manCamLabels.size()) ? autCamLabels.size() : manCamLabels.size();
      
      // test for emptiness of the intersection of the two lists
      bool found = false;

      j = 0;
      while (j < maxList && !found)
	if (autIdxSim.contains(manIdxSim[j++]))
	  found = true;

      if (found)
	tp++;
      else
	fp++;
    }
  }

  precision = computePrecision(tp, fp);
  recall = computeRecall(tp, fn);
  fScore = computeFScore(recall, precision);
  accuracy = computeAccuracy(tp, fp, fn, tn);

  if (displayResults) {
    ResultsDialog *dialog = new ResultsDialog(thresh1, thresh2, tp, fp, fn, tn, precision, recall, fScore, accuracy);
    dialog->exec();
  }

  return fScore;
}

int ProjectModel::retrieveShotPrevPositions(qint64 position, QList<qint64> &shotPositions)
{
  retrieveShotPositions(m_series, shotPositions);

  int i(0);
  while (shotPositions[i] < position)
    i++;

  return i;
}

qreal ProjectModel::computePrecision(int tp, int fp) const
{
  if (tp == 0 && fp == 0)
    return 0.0;

  return static_cast<qreal>(tp) / (tp + fp);
}

qreal ProjectModel::computeRecall(int tp, int fn) const
{
  if (tp == 0 && fn == 0)
    return 0.0;

  return static_cast<qreal>(tp) / (tp + fn);
}

qreal ProjectModel::computeFScore(qreal precision, qreal recall) const
{
  if (precision == 0.0 || recall == 0.0)
    return 0.0;

  return 2 * precision * recall / (precision + recall);
}

qreal ProjectModel::computeAccuracy(int tp, int fp, int fn, int tn) const
{
  return (static_cast<qreal>(tp) + tn) / (tp + fp + fn + tn);
}

void ProjectModel::resetShotsToManual(Segment *segment, QList<Segment *> &toRemove)
{
  if ((dynamic_cast<Shot *>(segment))) {

    switch (segment->getSource()) {
    case Segment::Manual:
    case Segment::Both:
      segment->setSource(Segment::Manual);
      break;
    case Segment::Automatic:
      toRemove.push_back(segment);
      break;
    }
  }
  
  else
    for (int i(0); i < segment->childCount(); i++)
      resetShotsToManual(segment->child(i), toRemove);
}

void ProjectModel::resetAutoCameraLabels(Segment *segment)
{
  Shot *shot;
  if ((shot = dynamic_cast<Shot *>(segment)))
    shot->setCamera(-1, Shot::Automatic);
  
  else
    for (int i(0); i < segment->childCount(); i++)
      resetAutoCameraLabels(segment->child(i));
}

void ProjectModel::eraseSubtitles(Segment *segment)
{
  VideoFrame *vFrame;

  if ((vFrame = dynamic_cast<VideoFrame *>(segment)))
    vFrame->setSub(QString());
  else
    for (int i(0); i < segment->childCount(); i++)
      eraseSubtitles(segment->child(i));
}

void ProjectModel::clearSpeaker(Segment *segment, VideoFrame::SpeakerSource source)
{
  VideoFrame *vFrame;

  if ((vFrame = dynamic_cast<VideoFrame *>(segment)))
    vFrame->clearSpeaker(source);
  else
    for (int i(0); i < segment->childCount(); i++)
      clearSpeaker(segment->child(i), source);
}

void ProjectModel::reset()
{
  m_name = "";
}

void ProjectModel::retrieveShotUtterances()
{
  QList<QString> shotLabels;
  QList<qint64> shotPositions;
  QList<int> longUtt;
  QList<QMap<QString, qint64>> durShotByUtt;
  int j(0);                     // counter
  qint64 shotStart;
  qint64 shotEnd;
  qint64 uttDur;
  qint64 inter;
  qint64 minDur(200);

  retrieveShotLabels(m_series, shotLabels);
  retrieveShotPositions(m_series, shotPositions);

  // looping over the shots
  for (int i(0); i < shotLabels.size() - 1; i++) {
    if (shotLabels[i] != "") {

      shotStart = shotPositions[i];
      
      if (i < shotPositions.size() - 1)
	shotEnd = shotPositions[i+1];
      else
	shotEnd = shotStart;
      
      // setting utterance position
      while (j > 0 && m_subBound[j].first > shotStart)
	j--;
      while (j < m_subBound.size() && m_subBound[j].second <= shotStart)
	j++;

      // utterance longer than shot: do not process yet
      if (m_subBound[j].first < shotStart && m_subBound[j].second > shotEnd) {
	longUtt.push_back(j);
	continue;
      }

      // first utterance is between two shots
      if (m_subBound[j].first < shotStart && m_subBound[j].second > shotStart) {
	uttDur = m_subBound[j].second - m_subBound[j].first;

	// the major part of the utterance is covered by the shot
	if (m_subBound[j].second - shotStart >= uttDur / 2) {
	  QPair<int, qreal> pair(j, uttDur / 1000.0);

	  if (uttDur >= minDur)
	    m_shotUtterances[shotLabels[i]].push_back(pair);
	}

	j++;
      }

      // utterances entirely contained in the shot
      while (j < m_subBound.size() && m_subBound[j].second < shotEnd) {

	uttDur = m_subBound[j].second - m_subBound[j].first;

	QPair<int, qreal> pair(j, uttDur / 1000.0);

	if (uttDur >= minDur)
	  m_shotUtterances[shotLabels[i]].push_back(pair);

	j++;
      }

      // last utterance is between two shots
      if (m_subBound[j].first < shotEnd) {
	uttDur = m_subBound[j].second - m_subBound[j].first;

	// the major part of the utterance is covered by the shot
	if (shotEnd - m_subBound[j].first > uttDur / 2) {
	  QPair<int, qreal> pair(j, uttDur / 1000.0);

	  if (uttDur >= minDur)
	    m_shotUtterances[shotLabels[i]].push_back(pair);
	}

	j++;
      }
    }
  }
  
  // processing case of utterances longer than a shot
  j = 0;

  for (int i(0); i < longUtt.size(); i++) {
    
    QMap<QString, qint64> shots;

    // setting shot position
    while (j > 0 && shotPositions[j] >= m_subBound[longUtt[i]].first)
      j--;
    while (j < shotPositions.size() - 1 && shotPositions[j+1] <= m_subBound[longUtt[i]].first)
      j++;

    // computing duration of the utterance/shot intersection
    while (j < shotPositions.size() - 1 && shotPositions[j] < m_subBound[longUtt[i]].second) {
	
      // first shot partially included in utterance
      if (shotPositions[j] < m_subBound[longUtt[i]].first)
	inter = shotPositions[j+1] - m_subBound[longUtt[i]].first;

      // shot is a subset of the utterance
      else if (shotPositions[j+1] <= m_subBound[longUtt[i]].second)
	inter = shotPositions[j+1] - shotPositions[j];

      // last shot partially included in utterance
      else
	inter = m_subBound[longUtt[i]].second - shotPositions[j];

      if (shotLabels[j] != "") {
	if (shots.contains(shotLabels[j]))
	  shots[shotLabels[j]] += inter;
	else
	  shots[shotLabels[j]] = inter;
      }

      j++;
    }

    // assigning utterance to shot
    QMap<QString, qint64>::const_iterator it = shots.begin();
    int max(0);
    QString bestShotLabel;

    // detetermining best shot label
    while (it != shots.end()) {
      qint64 inter = it.value();

      if (inter > max) {
	bestShotLabel = it.key();
	max = inter;
      }
      it++;
    }

    // updating list of utterances assigned to shot
    QPair<int, qreal> pair(longUtt[i], (m_subBound[longUtt[i]].second - m_subBound[longUtt[i]].first) / 1000.0);
    m_shotUtterances[bestShotLabel].push_back(pair);
  }
}

void ProjectModel::retrieveShotPatterns()
{
  QList<QString> shotLabels;
  QList<qint64> shotPositions;

  QString patternLabel;
  QString prevPatternLabel;
  QString firstLabel;
  QString secondLabel;
  QPair<qint64, qint64> pattBounds;     // boundaries of pattern in ms
  QPair<qint64, qint64> strictPattBounds; // normalized boundaries of pattern in ms
  QList<QString> lblWindow;             // last four shot labels: used to detect shot pattern
  QList<QString> lblWindow1;            // last four shot labels: used to detect shot pattern
  QList<QString> lblWindow2;            // last four shot labels: used to detect shot pattern
  QString label;
  bool inPattern(false);                // indicates if currently visiting a pattern
  int pattSize(3);                      // pattern minimum size
  int j(0);

  retrieveShotLabels(m_series, shotLabels);
  retrieveShotPositions(m_series, shotPositions);

  /**************************/
  /* retrieve shot patterns */
  /**************************/

  // looping over the shots
  for (int i(0); i < shotLabels.size() - 1; i++) {

    label = shotLabels[i]; // current shot label

    // updating shot label window
    lblWindow.push_back(label);
    if (lblWindow.size() > pattSize)
      lblWindow.pop_front();
	  
    // new pattern detected
    if (!inPattern && testShotPattern(lblWindow, pattSize)) {

      // initializing pattern boundaries
      pattBounds.first = -1;
      pattBounds.second = -1;
      strictPattBounds.first = shotPositions[i-(pattSize-1)];
      strictPattBounds.second = shotPositions[i+1];
	    
      // setting spoken segment position
      while (j > 0 && m_subBound[j].first > shotPositions[i-(pattSize-1)])
	j--;
      while (j < m_subBound.size() && m_subBound[j].second < shotPositions[i-(pattSize-1)])
	j++;
	  
      // setting pattern label
      firstLabel = lblWindow[0];
      secondLabel = lblWindow[1];
      patternLabel = normalizedPattern(firstLabel, secondLabel);

      inPattern = true;
    }

    // end of pattern
    if (inPattern && !testShotPattern(lblWindow, pattSize)) {
      m_shotPattBound[patternLabel].push_back(pattBounds);
      m_strictShotPattBound[patternLabel].push_back(strictPattBounds);
      inPattern = false;
    }

    // moving into current pattern
    if (inPattern && testShotPattern(lblWindow, pattSize)) {

      // adjust normalized pattern boundaries
      strictPattBounds.second = shotPositions[i+1];

      // writing out positions and durations of spoken segments covered by the pattern
      while (j < m_subBound.size() && m_subBound[j].first < shotPositions[i+1]) {
	// setting subtitles ref and weights contained in pattern
	QPair<int, qreal> pair(j, (m_subBound[j].second-m_subBound[j].first) / 1000.0);
	
	if (m_shotUtterances[firstLabel].contains(pair) || m_shotUtterances[secondLabel].contains(pair)) {
	
	  m_shotPatterns[patternLabel].push_back(pair);

	  // adjusting pattern boundaries
	  // first time in the pattern
	  if (pattBounds.first == -1 && pattBounds.second == -1) {
	    pattBounds.first = m_subBound[j].first;
	    pattBounds.second = m_subBound[j].second;
	  }

	  // utterance begins before first shot of the pattern
	  if (m_subBound[j].first < pattBounds.first)
	    pattBounds.first = m_subBound[j].first;

	  // utterance ends after last shot of the pattern
	  if (m_subBound[j].second > pattBounds.second)
	    pattBounds.second = m_subBound[j].second;
	}
	j++;
      }

      // updating flag
      inPattern = testShotPattern(lblWindow, pattSize);
    }
  }

  // processing last pattern
  if (inPattern) {
    m_shotPattBound[patternLabel].push_back(pattBounds);
    m_strictShotPattBound[patternLabel].push_back(strictPattBounds);
    inPattern = false;
  }

  /*********************************/
  /* retrieve marginal expressions */
  /*     of the shot patterns      */
  /*********************************/

  j = 0;

  // looping over the shots
  for (int i(0); i < shotLabels.size() - 2; i++) {

    label = shotLabels[i]; // current shot label

    // setting pattern label
    firstLabel = shotLabels[i];
    secondLabel = shotLabels[i+1];
    patternLabel = normalizedPattern(firstLabel, secondLabel);

    // initializing pattern boundaries
    pattBounds.first = -1;
    pattBounds.second = -1;
    strictPattBounds.first = shotPositions[i];
    strictPattBounds.second = shotPositions[i+2];

    // extending the pattern
    if (m_shotPatterns.contains(patternLabel)) {

      // setting spoken segment position
      while (j > 0 && m_subBound[j].first > shotPositions[i])
	j--;
      while (j < m_subBound.size() && m_subBound[j].second < shotPositions[i])
	j++;

      // writing out positions and durations of spoken segments covered by the pattern
      while (j < m_subBound.size() && m_subBound[j].first < shotPositions[i+2]) {

	QPair<int, qreal> pair(j, (m_subBound[j].second-m_subBound[j].first) / 1000.0);

	if (!m_shotPatterns[patternLabel].contains(pair) &&
	    (m_shotUtterances[firstLabel].contains(pair) ||
	     m_shotUtterances[secondLabel].contains(pair))) {

	  // add current utterance
	  m_shotPatterns[patternLabel].push_back(pair);

	  // adjusting pattern boundaries
	  // first time in the pattern
	  if (pattBounds.first == -1 && pattBounds.second == -1) {
	    pattBounds.first = m_subBound[j].first;
	    pattBounds.second = m_subBound[j].second;
	  }
	  
	  // utterance begins before first shot of the pattern
	  if (m_subBound[j].first < pattBounds.first)
	    pattBounds.first = m_subBound[j].first;

	  // utterance ends after last shot of the pattern
	  if (m_subBound[j].second > pattBounds.second)
	    pattBounds.second = m_subBound[j].second;
	}
	
	j++;
      }

      // updating pattern boundaries
      if (pattBounds.first != -1 || pattBounds.second != -1) {
	m_shotPattBound[patternLabel].push_back(pattBounds);
	m_strictShotPattBound[patternLabel].push_back(strictPattBounds);
      }
    }
  }

  // processing last pattern
  if (pattBounds.first != -1 || pattBounds.second != -1) {
	m_shotPattBound[patternLabel].push_back(pattBounds);
	m_strictShotPattBound[patternLabel].push_back(strictPattBounds);
  }

  /******************************/
  /* merge interleaved patterns */
  /******************************/

  /*
  // for each pattern, retrieve list of patterns with one shot label in common
  QMap<QString, QStringList> relatedPatterns;

  // iterators over shot patterns
  QMap<QString, QList<QPair<int, qreal>>>::const_iterator it1 = m_shotPatterns.begin();
  QMap<QString, QList<QPair<int, qreal>>>::const_iterator it2;

  // first loop over pattern labels
  while (it1 != m_shotPatterns.end()) {

    firstLabel = it1.key();
    it2 = m_shotPatterns.begin();

    // second loop over pattern labels
    while (it2 != m_shotPatterns.end()) {
      secondLabel = it2.key();
      
      if (firstLabel != secondLabel && interPatterns(firstLabel, secondLabel)) {
	if (!relatedPatterns.contains(secondLabel) || !relatedPatterns[secondLabel].contains(firstLabel))
	  relatedPatterns[firstLabel].push_back(secondLabel);
      }
      
      it2++;
    }
    it1++;
  }


  // iteratively merge shot patterns with one shot label in common
  // iterator over shot patterns with related patterns
  QMap<QString, QStringList>::const_iterator it = relatedPatterns.begin();

  QString newLabel1;
  QString newLabel2;
  QList<QPair<int, qreal>> newList;

  // extended names of the labels
  QString compFirstLabel;
  QString compSecondLabel;

  // looping over pattern labels
  while (it != relatedPatterns.end()) {
    
    firstLabel = it.key();
    QStringList patterns = it.value();

    // looping over related patterns
    for (int i(0); i < patterns.size(); i++) {

      // updating possibly enhanced pattern name
      compFirstLabel = completePatternLabel(firstLabel, m_shotPatterns);

      // related enhanced pattern name
      secondLabel = patterns[i];
      compSecondLabel = completePatternLabel(patterns[i], m_shotPatterns);

      // new label obtained by merging the complete first label
      // and the second label considered by himself
      newLabel1 = mergePatterns(compFirstLabel, secondLabel, m_shotPatterns[compFirstLabel], m_shotPatterns[secondLabel], newList);

      // inserting new pattern and possibly removing previous ones
      m_shotPatterns[newLabel1] = newList;

      m_shotPattBound[newLabel1] = m_shotPattBound[compFirstLabel];
      m_shotPattBound[newLabel1].append(m_shotPattBound[secondLabel]);

      m_strictShotPattBound[newLabel1] = m_strictShotPattBound[compFirstLabel];
      m_strictShotPattBound[newLabel1].append(m_strictShotPattBound[secondLabel]);

      if (newLabel1 != compFirstLabel) {
	m_shotPatterns.remove(compFirstLabel);
	m_shotPattBound.remove(compFirstLabel);
	m_strictShotPattBound.remove(compFirstLabel);
      }

      if (newLabel1 != secondLabel) {
	m_shotPatterns.remove(secondLabel);
	m_shotPattBound.remove(secondLabel);
	m_strictShotPattBound.remove(secondLabel);
      }

      // new label obtained by merging the possibly different complete labels
      if (compFirstLabel != compSecondLabel) {
	
	// merging step
	newLabel2 = mergePatterns(newLabel1, compSecondLabel, m_shotPatterns[newLabel1], m_shotPatterns[compSecondLabel], newList);

	// inserting new pattern and possibly removing previous ones
	m_shotPatterns[newLabel2] = newList;

	m_shotPattBound[newLabel2] = m_shotPattBound[newLabel1];
	m_shotPattBound[newLabel2].append(m_shotPattBound[compSecondLabel]);

	m_strictShotPattBound[newLabel2] = m_strictShotPattBound[newLabel1];
	m_strictShotPattBound[newLabel2].append(m_strictShotPattBound[compSecondLabel]);

	if (newLabel2 != newLabel1) {
	  m_shotPatterns.remove(newLabel1);
	  m_shotPattBound.remove(newLabel1);
	  m_strictShotPattBound.remove(newLabel1);
	}

	if (newLabel1 != compSecondLabel) {
	  m_shotPatterns.remove(compSecondLabel);
	  m_shotPattBound.remove(compSecondLabel);
	  m_strictShotPattBound.remove(compSecondLabel);
	}
      }
    }
    it++;
  }
  */

  /**********************************/
  /* update shot pattern boundaries */
  /**********************************/

  mergePatternBoundaries(m_shotPattBound);
  mergePatternBoundaries(m_strictShotPattBound);
}

void ProjectModel::mergePatternBoundaries(QMap<QString, QList<QPair<qint64, qint64>>> &shotPattBound)
{
  QMap<QString, QList<QPair<qint64, qint64>>>::const_iterator it = shotPattBound.begin();
  QString pattLabel;
  qint64 start;
  qint64 end;
  QPair<qint64, qint64> newPair;
  bool modif(true);

  // looping over the patterns
  while (it != shotPattBound.end()) {

    modif = true;
    pattLabel = it.key();

    QList<QPair<qint64, qint64>> list = it.value();

    // try to merge pattern boundaries until there remains no more one
    while (modif) {
      
      modif = false;

      // list of merged pattern boundaries
      QList<QPair<qint64, qint64>> newList;
      QVector<bool> merged(list.size(), false);

      // first loop over pattern boundaries
      for (int i(0); i < list.size(); i++) {
	
	if (!merged[i]) {

	  start = list[i].first;
	  end = list[i].second;

	  // second loop over pattern boundaries
	  for (int j(i+1); j < list.size(); j++) {

	    if (!merged[j]) {

	      // second pattern interleaves first one at the beginning
	      if (list[j].first < start && list[j].second >= start) {
		newPair = QPair<qint64, qint64>(list[j].first, end);
		newList.push_back(newPair);
		merged[i] = true;
		merged[j] = true;
		modif = true;
	      }

	      // second pattern interleaves first one at the end
	      else if (list[j].first <= end && list[j].second > end) {
		newPair = QPair<qint64, qint64>(start, list[j].second);
		newList.push_back(newPair);
		merged[i] = true;
		merged[j] = true;
		modif = true;
	      }
	      // second pattern covers first one
	      else if (list[j].first < start && list[j].second > end) {
		merged[i] = true;
		modif = true;
	      }
	      // second pattern is included in first one
	      else if (list[j].first >= start && list[j].second <= end) {
		merged[j] = true;
		modif = true;
	      }
	    }
	  }
	}
      }

      // add remaining pattern boundaries to new list
      for (int i(0); i < list.size(); i++)
	if (!merged[i])
	  newList.push_back(list[i]);
    
      qSort(newList);
      list = newList;
    }

    shotPattBound[pattLabel] = list;
    it++;
  }
}

bool ProjectModel::interPatterns(QString firstLabel, QString secondLabel)
{
  // remove aditional characters
  QRegularExpression openPar(QRegularExpression::escape("("));
  QRegularExpression closePar(QRegularExpression::escape(")"));

  firstLabel.replace(openPar, "");
  firstLabel.replace(closePar, "");
  secondLabel.replace(openPar, "");
  secondLabel.replace(closePar, "");

  // split parts of each pattern
  QStringList firstLabels = firstLabel.split("_");
  QStringList secondLabels = secondLabel.split("_");

  QList<QStringList> labels1;
  QList<QStringList> labels2;

  // retrieve list of shots contained in each pattern part
  labels1.push_back(firstLabels[0].split("|"));
  labels1.push_back(firstLabels[1].split("|"));
  labels2.push_back(secondLabels[0].split("|"));
  labels2.push_back(secondLabels[1].split("|"));

  // test if patterns share a shot label
  int i(0);
  int j(0);
  int k(0);

  while (i < 2) {
    j = 0;
    while (j < labels1[i].size()) {
      k = 0;
      while (k < 2) {
	if (labels2[k].contains(labels1[i][j]))
	  return true;
	k++;
      }
      j++;
    }
    i++;
  }

  return false;
}

QString ProjectModel::normalizedPattern(const QString &firstLabel, const QString &secondLabel)
{
  QString pattern;

  if (QString::compare(firstLabel, secondLabel) < 0)
    pattern = firstLabel + "_" + secondLabel;
  else
    pattern = secondLabel + "_" + firstLabel;

  return pattern;
}

QString ProjectModel::mergePatterns(QString firstLabel, QString secondLabel, QList<QPair<int, qreal>> list1, QList<QPair<int, qreal>> list2, QList<QPair<int, qreal>> &mergedList)
{
  QString newPattLabel;

  // remove aditional characters
  QRegularExpression openPar(QRegularExpression::escape("("));
  QRegularExpression closePar(QRegularExpression::escape(")"));

  firstLabel.replace(openPar, "");
  firstLabel.replace(closePar, "");
  secondLabel.replace(openPar, "");
  secondLabel.replace(closePar, "");

  // split parts of each pattern
  QStringList firstLabels = firstLabel.split("_");
  QStringList secondLabels = secondLabel.split("_");

  QList<QStringList> labels1;
  QList<QStringList> labels2;

  // retrieve list of shots contained in each pattern part
  labels1.push_back(firstLabels[0].split("|"));
  labels1.push_back(firstLabels[1].split("|"));
  labels2.push_back(secondLabels[0].split("|"));
  labels2.push_back(secondLabels[1].split("|"));

  // retrieving equivalent lists
  bool found = false;

  int i(0);
  int j(0);
  int k(0);

  while (i < 2 && !found) {
    j = 0;
    while (j < labels1[i].size() && !found) {
      k = 0;
      while (k < 2 && !found) {
	if (labels2[k].contains(labels1[i][j]))
	  found = true;
	k++;
      }
      j++;
    }
    i++;
  }

  i--;
  k--;

  QStringList eqClass1 = appendStringList(labels1[(i+1)%2], labels2[(k+1)%2]);
  qSort(eqClass1);

  QStringList eqClass2 = appendStringList(labels1[i], labels2[k]);
  qSort(eqClass2);

  // formatting new pattern label
  QString newLabel1 = eqClass1.join("|");
  QString newLabel2 = eqClass2.join("|");

  if (eqClass1.size() > 1)
    newLabel1 = "(" + newLabel1 + ")";

  if (eqClass2.size() > 1)
    newLabel2 = "(" + newLabel2 + ")";

  newPattLabel = normalizedPattern(newLabel1, newLabel2);

  // merging the two lists
  mergedList = list1;

  for (int i(0); i < list2.size(); i++)
    if (!mergedList.contains(list2[i]))
      mergedList.append(list2[i]);

  qSort(mergedList);

  return newPattLabel;
}

QStringList ProjectModel::appendStringList(const QStringList &list1, const QStringList &list2)
{
  QStringList conc(list1);

  for (int i(0); i < list2.size(); i++)
    if (!list1.contains(list2[i]))
      conc.append(list2[i]);

  return conc;
}

QString ProjectModel::completePatternLabel(const QString &label, QMap<QString, QList<QPair<int, qreal>>> shotPatterns)
{
  QString completeLabel;
  QString currLabel;
  QStringList shotLabels(label.split("_"));
  QStringList currShotLabels;
  QRegularExpression left(shotLabels[0]);
  QRegularExpression right(shotLabels[1]);
  QRegularExpressionMatch matchLeft;
  QRegularExpressionMatch matchRight;
  bool found(false);

  QMap<QString, QList<QPair<int, qreal>>>::const_iterator it = shotPatterns.begin();

  while (it != shotPatterns.end() && !found) {
    currLabel = it.key();
    currShotLabels = currLabel.split("_");

    matchLeft = left.match(currShotLabels[0]);
    matchRight = right.match(currShotLabels[1]);

    if (matchLeft.hasMatch() && matchRight.hasMatch()) {
      completeLabel = currLabel;
      found = true;
    }
      
    matchLeft = left.match(currShotLabels[1]);
    matchRight = right.match(currShotLabels[0]);

    if (matchLeft.hasMatch() && matchRight.hasMatch()) {
      completeLabel = currLabel;
      found = true;
    }

    it++;
  }

  return completeLabel;
}

bool ProjectModel::testShotPattern(const QList<QString> &lblWindow, int pattSize)
{
  int i(2);

  if (!lblWindow.contains("") && lblWindow.size() == pattSize)
    while (i < pattSize) {
      if (lblWindow[i] != lblWindow[i-2])
	return false;
      i++;
    }
  else
    return false;

  return true;
}

void ProjectModel::retrieveShotLabels(Segment *segment, QList<QString> &shotLabels) const
{
  if ((dynamic_cast<Shot *>(segment)))
    shotLabels.push_back(segment->getLabel());

  for (int i(0); i < segment->childCount(); i++)
    retrieveShotLabels(segment->child(i), shotLabels);
}

void ProjectModel::retrieveSubPositionsLabels(QList<qint64> &subStarts, QList<qint64> &subEnds, QList<QString> &subRefLbl) const
{
  QList<VideoFrame *> vFrames;
  retrieveVFrames(m_series, vFrames);

  QString currSpeaker("");
  QString prevSpeaker("");
  QString currSub("");
  QString prevSub("");
  qint64 currPosition(0);
  qint64 prevPosition(0);
  
  // regular expression to detect subtitles corresponding to noise
  QRegularExpression noiseSource("\\(.*\\)");

  for (int i(0); i < vFrames.size(); i++) {

    currSpeaker = vFrames[i]->getSpeaker(VideoFrame::Ref);
    currPosition = vFrames[i]->getPosition();
    currSub = vFrames[i]->getSub();

    QRegularExpressionMatch match = noiseSource.match(currSub);

    if (!match.hasMatch()) {

      // speaker status changed
      if (currSpeaker != prevSpeaker || currSub != prevSub) {

	// end of utterance
	if (currSpeaker == "") {
	  subEnds.push_back(prevPosition);
	  subRefLbl.push_back(prevSpeaker);
	}

	// beginning of utterance
	else if (prevSpeaker == "")
	  subStarts.push_back(currPosition);
      
	// ending previous utterance and beginning new one
	else {
	  subEnds.push_back(prevPosition);
	  subRefLbl.push_back(prevSpeaker);
	  subStarts.push_back(currPosition);
	}
      }

      prevSpeaker = currSpeaker;
      prevPosition = currPosition;
      prevSub = currSub;
    }
  }

  // processing last utterance if ending at last video frame
  // if (!regex_match(currSub.toStdString(), noiseSource)) {
  if (prevSpeaker != "" || prevSub != "") {
    subEnds.push_back(prevPosition);
    subRefLbl.push_back(prevSpeaker);
  }
}

///////////////
// accessors //
///////////////

QString ProjectModel::getName() const
{
  return m_name;
}

QString ProjectModel::getBaseName() const
{
  return m_baseName;
}

QString ProjectModel::getSeriesName() const
{
  return m_series->getName();
}

///////////
// slots //
///////////

void ProjectModel::setSpkDiar(const QString &epFName)
{
  QString normName;
  QString baseName;
  QProcess process;
  QString program;
  QStringList arguments;
  QFileInfo info(epFName);

  // erasing previous speaker hypotheses
  clearSpeaker(m_series, VideoFrame::Hyp1);
  clearSpeaker(m_series, VideoFrame::Hyp2);

  // normalizing series name
  normName = m_series->getName();
  normName = normName.toLower();
  normName.replace(QRegularExpression("\\s+"), "_");
  
  // audio files possibly needed
  baseName = normName + "_" + info.baseName();
  m_baseName = baseName;

  // generating reference file
  QString workPath("spkDiarization/");
  QString locRefFName(workPath + "data/ref/local/" + m_baseName);
  QString segRefFName(workPath + "data/ref/seg/" + m_baseName);
  exportLocSpkRef(locRefFName);
  
  // converting reference .lbl files into .rttm ones
  program = "perl";

  arguments << workPath + "scripts/SpkMoulinette.pl" << locRefFName + ".lbl" << locRefFName + ".rttm";
  process.start(program, arguments);
  process.waitForFinished();
  arguments.clear();

  arguments << workPath + "scripts/SpkMoulinette.pl" << segRefFName + ".lbl" << segRefFName + ".rttm";
  process.start(program, arguments);
  process.waitForFinished();
  arguments.clear();

  // removing previous local score
  QFile::remove(workPath + "score/local/" + m_baseName + ".nistres");
}

void ProjectModel::extractIVectors(bool ubm, const QString &epFName)
{
  QString workPath("spkDiarization/");
  QProcess process;
  QString program;
  QString args;
  QStringList arguments;
  QFileInfo info(epFName);
  int out;
  QString waveFile;
  QString sphFile;
  QString lstLine;
  QString sphSubFile;
  qreal startSec, endSec;
  QMap<QString, QList<int>> spkIdx;

  waveFile = workPath + "data/sph/" + m_baseName + ".wav";
  sphFile = workPath + "data/sph/" + m_baseName + ".sph";

  qDebug() << "Extracting speech segments...";

  // creating audio files corresponding to speech segments
  QFile lstFile(workPath + "data/data.lst");
  QFile totVarFile(workPath + "ndx/totalvariability.ndx");
  QFile ivExtFile(workPath + "ndx/ivExtractor.ndx");
    
  if (!lstFile.open(QIODevice::WriteOnly | QIODevice::Text))
    return;

  if (!totVarFile.open(QIODevice::WriteOnly | QIODevice::Text))
    return;

  if (!ivExtFile.open(QIODevice::WriteOnly | QIODevice::Text))
    return;

  QTextStream lstOut(&lstFile);
  QTextStream totVarOut(&totVarFile);
  QTextStream ivExtOut(&ivExtFile);

  for (int i(0); i < m_subBound.size(); i++) {

    if (m_subRefLbl[i] != "S")
      spkIdx[m_subRefLbl[i]].push_back(i);
    
    lstLine = m_baseName + "_" + QString::number(m_subBound[i].first / 10) + "_" + QString::number(m_subBound[i].second / 10);

    startSec = m_subBound[i].first / 1000.0;
    endSec = m_subBound[i].second / 1000.0;

    lstOut << lstLine << endl;
    totVarOut << lstLine << endl;
    ivExtOut << lstLine << " " << lstLine << endl;

    sphSubFile = workPath + "data/sph/" + lstLine + ".sph";
    
    if (!QFile::exists(sphSubFile)) {

      // creating main audio file if needed
      if (!QFile::exists(sphFile)) {

	qDebug() << "Extracting .wav file...";
	program = "avconv";
	args = " -i " + epFName + " -map 0:1 -vn -acodec pcm_s16le -ar 16000 -ac 2 " + waveFile;
	out = std::system(qPrintable(program + args));
	qDebug() << "Done.";

	qDebug() << "Converting .wav file to .sph...";
	program = "sox";
	arguments << waveFile << sphFile;
	process.start(program, arguments);
	process.waitForFinished();
	arguments.clear();
	qDebug() << "Done.";

	QFile::remove(waveFile);
      }
      
      program = "sox";
      arguments << sphFile << sphSubFile << "trim" << QString::number(startSec) << "=" + QString::number(endSec);
      process.start(program, arguments);
      process.waitForFinished();
      arguments.clear();
    }
  }

  qDebug() << "Done.";

  qDebug() << "Parameterizing speech segments...";

  // parameterizing speech segments
  program = "sh";
  arguments << workPath + "01_RUN_feature_extraction.sh";
  process.start(program, arguments);
  process.waitForFinished();
  arguments.clear();

  qDebug() << "Done.";

  qDebug() << "Normalizing parameters...";

  // normalizing parameters
  program = "sh";
  arguments << workPath + "02a_RUN_spro_front-end.sh";
  process.start(program, arguments);
  process.waitForFinished();
  arguments.clear();

  qDebug() << "Done.";

  qDebug() << "Estimating total variability matrix...";

  // estimating total variability matrix
  program = "sh";
  arguments << workPath + "04_RUN_tv_estimation.sh";
  process.start(program, arguments);
  process.waitForFinished();
  arguments.clear();

  qDebug() << "Done.";

  qDebug() << "Extracting i-vector / speech segment...";

  // extracting i-vectors
  program = "sh";
  arguments << workPath + "05_RUN_i-vector_extraction.sh";
  process.start(program, arguments);
  process.waitForFinished();
  arguments.clear();

  qDebug() << "Done.";

  qDebug() << "Gathering i-vectors into X matrix...";

  // generating X matrix
  program = "sh";
  arguments << workPath + "06_RUN_X_mat_generate.sh";
  process.start(program, arguments);
  process.waitForFinished();
  arguments.clear();

  qDebug() << "Done.";

  // initializing X matrix (one i-vec by utterance)
  mat X;
  X.load(QString("spkDiarization/iv/X.dat").toStdString(), raw_ascii);

  // generating covariance matrices
  mat Sigma = cov(X);
  m_W = genWMat(spkIdx, X);

  emit setDiarData(X, Sigma, m_W);
  
  qDebug() << "Cleaning directories...";

  // cleaning directories
  program = "sh";
  arguments << workPath + "00_RUN_clean_directories.sh";
  process.start(program, arguments);
  process.waitForFinished();
  arguments.clear();

  qDebug() << "Done.";
}

void ProjectModel::extractSpkIVectors(const QString &epFName, bool refSpk)
{
  QString workPath = "spkDiarization/";
  QFile lblFile;
  QProcess process;
  QString program;
  QStringList arguments;
  QString args;
  int out;
  QMap<QString, QList<QPair<qreal, qreal>>> speakers;
  qreal start, end;
  QString speakerLabel;
  QString sphFile;
  QString waveFile;
  QString sphSubFile;
  
  waveFile = workPath + "data/sph/" + m_baseName + ".wav";
  sphFile = workPath + "data/sph/" + m_baseName + ".sph";

  // initializing list of local speakers as hypothesized
  if (refSpk)
    lblFile.setFileName(workPath + "data/ref/seg/" + m_baseName + ".lbl");
  else
    lblFile.setFileName(workPath + "lblLocalSegmentation/" + m_baseName + ".lbl");

  if (!lblFile.open(QIODevice::ReadOnly | QIODevice::Text))
    return;

  QTextStream in(&lblFile);
  QMap<QString, int> nSpeakers;

  // regular expression to retrieve pattern name
  QRegularExpression re("(.+\\d+\\)?)_.+");
  QString pattLabel;

  // parsing hypotheses file
  while (!in.atEnd()) {

    QString line = in.readLine();
    QStringList data = line.split(" ");

    start = data[0].toDouble();
    end = data[1].toDouble();
    speakerLabel = data[2];

    QRegularExpressionMatch match = re.match(speakerLabel);
    if (match.hasMatch())
      pattLabel = match.captured(1);

    if (!speakers.contains(speakerLabel))
      nSpeakers[pattLabel]++;

    // if (nSpeakers[pattLabel] <= 2 && nSpeakers.size() <= 4)
    speakers[speakerLabel].push_back(QPair<qreal, qreal>(start, end));
  }

  /*
  QMap<QString, int>::const_iterator it1 = nSpeakers.begin();

  while (it1 != nSpeakers.end()) {

    qDebug() << it1.key() << it1.value();

    it1++;
  }
  */

  // generating audio files corresponding to speech segments
  sphFile = workPath + "data/sph/" + m_baseName + ".sph";
  program = "sox";

  QMap<QString, QList<QPair<qreal, qreal>>>::const_iterator it = speakers.begin();

  while (it != speakers.end()) {

    speakerLabel = it.key();
    // qDebug() << speakerLabel;

    QList<QPair<qreal, qreal>> boundaries = it.value();

    qSort(boundaries);
    speakers[speakerLabel] = boundaries;

    for (int i(0); i < boundaries.size(); i++) {
      
      sphSubFile = workPath + "data/sph/" + m_baseName + "_" + QString::number(boundaries[i].first * 100) + "_" + QString::number(boundaries[i].second * 100) + ".sph";

      if (!QFile::exists(sphSubFile)) {

	// creating main audio file if needed
	if (!QFile::exists(sphFile)) {

	  qDebug() << "Extracting .wav file...";
	  program = "avconv";
	  args = " -i " + epFName + " -map 0:1 -vn -acodec pcm_s16le -ar 16000 -ac 2 " + waveFile;
	  out = std::system(qPrintable(program + args));
	  qDebug() << "Done.";

	  qDebug() << "Converting .wav file to .sph...";
	  program = "sox";
	  arguments << waveFile << sphFile;
	  process.start(program, arguments);
	  process.waitForFinished();
	  arguments.clear();
	  qDebug() << "Done.";

	  QFile::remove(waveFile);
	}

	arguments << sphFile << sphSubFile << "trim" << QString::number(boundaries[i].first) << "=" + QString::number(boundaries[i].second);
	process.start(program, arguments);
	process.waitForFinished();
	arguments.clear();
      }
    }

    it++;
  }

  qDebug() << "Generating audio files corresponding to local speakers...";

  // generating audio files corresponding to hyhpothesized speakers
  QFile lstFile(workPath + "data/data.lst");
  QFile totVarFile(workPath + "ndx/totalvariability.ndx");
  QFile ivExtFile(workPath + "ndx/ivExtractor.ndx");

  if (!lstFile.open(QIODevice::WriteOnly | QIODevice::Text))
    return;
  if (!totVarFile.open(QIODevice::WriteOnly | QIODevice::Text))
    return;
  if (!ivExtFile.open(QIODevice::WriteOnly | QIODevice::Text))
    return;

  QTextStream lstOut(&lstFile);  
  QTextStream totVarOut(&totVarFile);
  QTextStream ivExtOut(&ivExtFile);

  it = speakers.begin();

  while (it != speakers.end()) {

    speakerLabel = it.key();
    QList<QPair<qreal, qreal>> boundaries = it.value();

    for (int i(0); i < boundaries.size(); i++) {
      sphSubFile = workPath + "data/sph/" + m_baseName + "_" + QString::number(boundaries[i].first * 100) + "_" + QString::number(boundaries[i].second * 100) + ".sph";
      arguments << sphSubFile;
    }

    arguments << workPath + "data/sph/" + m_baseName + "_" + speakerLabel + ".sph";
    lstOut << m_baseName + "_" + speakerLabel << endl;
    totVarOut << m_baseName + "_" + speakerLabel << endl;
    ivExtOut << m_baseName + "_" + speakerLabel << " " << m_baseName + "_" + speakerLabel << endl;

    process.start(program, arguments);
    process.waitForFinished();
    arguments.clear();

    it++;
  }

  qDebug() << "Done.";

  // deleting sph file
  QFile::remove(sphFile);

  qDebug() << "Parameterizing speakers...";

  // parameterizing speaker models
  program = "sh";
  arguments << workPath + "01_RUN_feature_extraction.sh";
  process.start(program, arguments);
  process.waitForFinished();
  arguments.clear();

  qDebug() << "Done.";

  qDebug() << "Normalizing parameters...";

  // normalizing parameters
  program = "sh";
  arguments << workPath + "02a_RUN_spro_front-end.sh";
  process.start(program, arguments);
  process.waitForFinished();
  arguments.clear();

  qDebug() << "Done.";

  qDebug() << "Estimating total variability matrix...";

  // estimating total variability matrix
  program = "sh";
  arguments << workPath + "04_RUN_tv_estimation.sh";
  process.start(program, arguments);
  process.waitForFinished();
  arguments.clear();

  qDebug() << "Done.";

  qDebug() << "Extracting i-vector / speaker...";

  // extracting i-vectors
  program = "sh";
  arguments << workPath + "05_RUN_i-vector_extraction.sh";
  process.start(program, arguments);
  process.waitForFinished();
  arguments.clear();

  qDebug() << "Done.";

  qDebug() << "Gathering i-vectors into X matrix...";

  // generating X matrix
  program = "sh";
  arguments << workPath + "06_RUN_X_mat_generate.sh";
  process.start(program, arguments);
  process.waitForFinished();
  arguments.clear();

  qDebug() << "Done.";

  // initializing X matrix (one i-vec by utterance)
  mat X;
  X.load(QString("spkDiarization/iv/X.dat").toStdString(), raw_ascii);

  // covariance matrices
  mat Sigma = cov(X);

  emit setDiarData(X, Sigma, m_W, speakers);

  qDebug() << "Cleaning directories...";

  // cleaning directories
  program = "sh";
  arguments << workPath + "00_RUN_clean_directories.sh";
  process.start(program, arguments);
  process.waitForFinished();
  arguments.clear();

  qDebug() << "Done.";
}

void ProjectModel::setResolution(const QSize &resolution)
{
  m_episode->setResolution(resolution);
}

void ProjectModel::setFps(qreal fps)
{
  m_episode->setFps(fps);
}

void ProjectModel::appendVideoFrame(int id, qint64 position)
{
  VideoFrame *vFrame = new VideoFrame(id, position, m_episode);
  m_episode->appendChild(vFrame);
}

void ProjectModel::initShotLevel(Segment *segment)
{
  Segment *firstVideoFrame = getFirstVideoFrame(segment);
  insertShot(firstVideoFrame, Segment::Manual);
}

void ProjectModel::insertShot(qint64 position, Segment::Source source)
{
  int i(-1);

  // retrieve video frame from the position specified
  Segment *segment = m_series;

  while (!dynamic_cast<VideoFrame *>(segment)) {

    // closest segment index to current position
    i = segment->childIndexFromPosition(position);

    // select possible children
    segment = segment->child(i);
  }

  if (!shotLevelCreated(segment)) {
    Segment *firstVideoFrame = getFirstVideoFrame(segment);
    insertShot(firstVideoFrame, source);
  }

  insertShot(segment, source);
}

void ProjectModel::insertShot(Segment *segment, Segment::Source source)
{
  // no shot already inserted
  if (!shotLevelCreated(segment)) {

    // retrieve episode level
    Segment *grandParent = segment->parent();

    // creating new shot
    Segment *newParent = new Shot(segment->getPosition(), Shot::Cut, grandParent, source);

    // updating list of frames
    QList<Segment *> children = grandParent->getChildren();
    int size = children.size();
    for (int i = 0; i < size; i++)
      children[i]->setParent(newParent);

    // assigning to created shot the list of frames
    newParent->setChildren(children);

    // assigning shot to episode
    grandParent->clearChildren();
    grandParent->appendChild(newParent);

    emit modelChanged();
  }

  // at least one shot already inserted
  else {
    Segment *prevParent = segment->parent();
    Segment *grandParent = prevParent->parent();
      
    // no shot already added at this position
    if (segment->getPosition() != prevParent->getPosition()) {

      Segment *newParent = new Shot(segment->getPosition(), Shot::Cut, grandParent, source);

      QList<Segment *> subList1;
      QList<Segment *> subList2;

      prevParent->splitChildren(subList1, subList2, segment->row(), newParent);
      prevParent->clearChildren();
      prevParent->setChildren(subList1);
      newParent->setChildren(subList2);

      grandParent->insertChild(prevParent->row() + 1, newParent);

      if (source == Segment::Manual)
	emit positionChanged(segment->getPosition());
      emit modelChanged();
    }

    // shot already added at this position
    else if (prevParent->getSource() != source) {
      prevParent->setSource(Segment::Both);

      if (source == Segment::Manual)
	emit positionChanged(segment->getPosition());

      emit modelChanged();
    }
  }
}

void ProjectModel::removeShot(Segment *segment, Segment::Source source)
{
  Segment *parent = segment->parent();

  // row of current shot
  int row = segment->row();

  // shot to delete must not be the first one
  if (row != 0) {
    Segment *prevSegment = segment->parent()->child(row-1);
    QList<Segment *> prevSegmentChildren = prevSegment->getChildren();
    QList<Segment *> segmentChildren = segment->getChildren();

    prevSegmentChildren.append(segmentChildren);
      
    // setting parent of merged lists elements
    int size = prevSegmentChildren.size();
    for (int i = 0; i < size; i++)
      prevSegmentChildren[i]->setParent(prevSegment);

    prevSegment->clearChildren();
    prevSegment->setChildren(prevSegmentChildren);

    parent->removeChild(row);

    if (source == Segment::Manual)
      emit positionChanged(prevSegment->getPosition());
    emit modelChanged();
  }
}

void ProjectModel::labelSimShot(qint64 position, int nCamera, Segment::Source source)
{
  int i(-1);

  // retrieve shot from the position specified
  Segment *segment = m_series;
  Shot *shot;

  while (!(shot = dynamic_cast<Shot *>(segment))) {

    // closest segment index to current position
    i = segment->childIndexFromPosition(position);

    // select possible children
    segment = segment->child(i);
  }

  shot->setCamera(nCamera, source);
}

void ProjectModel::processSegmentation(bool checked, bool annot)
{
  if (checked || annot) {
    depthFirstToShots(m_series);
    emit segmentationRetrieved();
    depthFirstToSpokenFrames(m_series, VideoFrame::Ref);
    emit segmentationRetrieved();
    depthFirstToSpokenFrames(m_series, VideoFrame::Hyp1);
    emit segmentationRetrieved();
  }
  
  emit viewSegmentation(checked, annot);
}

void ProjectModel::retrieveSpeakers(bool checked)
{
  if (checked) {
    QList<QString> speakers;
    retrieveSpeakersList(m_series, speakers, VideoFrame::Ref);

    emit speakersRetrieved(speakers);
  }
}

void ProjectModel::setSpeaker(qint64 start, qint64 end, const QString &speaker, VideoFrame::SpeakerSource source)
{
  for (int position(start); position <= end; position += 40) {
    
    // retrieve video frame from the current position
    Segment *segment = m_series;
    VideoFrame *frame;

    while (!(frame = dynamic_cast<VideoFrame *>(segment))) {

      // closest segment index to current position
      int i = segment->childIndexFromPosition(position);

      // select possible children
      segment = segment->child(i);
    }

    frame->setSpeaker(speaker, source);
  }
}

void ProjectModel::resetSpeaker(qint64 prevStart, qint64 prevEnd, qint64 start, qint64 end, bool resetSub, VideoFrame::SpeakerSource source)
{
  QString speaker;
  QString sub;

  for (int position(prevStart); position <= prevEnd; position += 40) {
    
    // retrieve video frame from the current position
    Segment *segment = m_series;
    VideoFrame *frame;

    while (!(frame = dynamic_cast<VideoFrame *>(segment))) {

      // closest segment index to current position
      int i = segment->childIndexFromPosition(position);

      // select possible children
      segment = segment->child(i);
    }

    speaker = frame->getSpeaker(source);
    sub = frame->getSub();

    frame->setSpeaker("", source);
    if (resetSub)
      frame->setSub("");
  }

  for (int position(start); position <= end; position += 40) {
    
    // retrieve video frame from the current position
    Segment *segment = m_series;
    VideoFrame *frame;

    while (!(frame = dynamic_cast<VideoFrame *>(segment))) {

      // closest segment index to current position
      int i = segment->childIndexFromPosition(position);

      // select possible children
      segment = segment->child(i);
    }

    frame->setSpeaker(speaker, source);
    if (resetSub)
      frame->setSub(sub);
  }
}

void ProjectModel::exportSubtitles(const QString &fName)
{
  QFile subFile(fName + ".csv");

  if (!subFile.open(QIODevice::WriteOnly | QIODevice::Text))
    return;

  QTextStream subOut(&subFile);

  QList<VideoFrame *> spkVFrames;
  retrieveSpokenVFrames(m_series, spkVFrames, VideoFrame::Ref);

  qint64 start(spkVFrames[0]->getPosition());
  qint64 position(start);
  QString sub(spkVFrames[0]->getSub());

  for (int i(1); i < spkVFrames.size(); i++) {
    if (spkVFrames[i]->getSub() != sub) {
      subOut << start << "\t" << position << "\t" << sub << "\n";
      start = spkVFrames[i]->getPosition();
    }
    sub = spkVFrames[i]->getSub();
    position = spkVFrames[i]->getPosition();
  }

  subOut << start << "\t" << position << "\t" << sub << "\n";
}

void ProjectModel::exportGlobSpkRef(const QString &fName)
{
  QFile lblFile(fName + ".lbl");
  QString label;
  bool labeled(false);
  qreal start;
  qreal end;
  qreal globStart(m_subBound[m_subBound.size()-1].second / 1000.0);
  qreal globEnd(m_subBound[0].first / 1000.0);

  if (!lblFile.open(QIODevice::WriteOnly | QIODevice::Text))
    return;

  QTextStream lblOut(&lblFile);

  // test if utterances have been labelled
  int i(0);

  qDebug() << m_subRefLbl.size();

  while (i < m_subRefLbl.size() && !labeled) {
    labeled = (m_subRefLbl[i] != "S");
    i++;
  }

  // export .lbl file
  for (int i(0); i < m_subRefLbl.size(); i++) {
    label = m_subRefLbl[i];
    label.replace(QRegularExpression(" "), "_");
    start = m_subBound[i].first / 1000.0;
    end =  m_subBound[i].second / 1000.0;

    if (labeled) {

      lblOut << start << " " << end << " " << label << "\n";

      // updating global speech boundaries
      if (start < globStart)
	globStart = start;
      if (end > globEnd)
	globEnd = end;
    }

    else {

      lblOut << start << " " << end << " " << "speech" << "\n";

      // updating global speech boundaries
      if (start < globStart)
	globStart = start;
      if (end > globEnd)
	globEnd = end;
    }
  }

  // export .uem file
  QFile uemFile(fName + ".uem");

  QRegularExpression re(".*/(.+_.+)");
  QRegularExpressionMatch match = re.match(fName);
  QString baseName;
      
  if (match.hasMatch())
    baseName = match.captured(1);

  if (!uemFile.open(QIODevice::WriteOnly | QIODevice::Text))
    return;

  QTextStream uemOut(&uemFile);
  uemOut << baseName << " " << 1 << " " << globStart << " " << globEnd << "\n";
}

void ProjectModel::exportLocSpkRef(const QString &fName)
{
  QMap<QString, QList<QPair<int, qreal>>>::const_iterator it(m_shotPatterns.begin());
  QList<QPair<int, qreal>> currSubs;
  int uttIdx;
  qreal start;
  qreal end;
  QString pattLabel;
  QString spkLabel;
  bool labeled(false);
  qreal globStart(m_subBound[m_subBound.size()-1].second / 1000.0);
  qreal globEnd(m_subBound[0].first / 1000.0);
  
  QString locFName = fName;
  QString segFName = fName;
  segFName.replace(QRegularExpression("local"), "seg");

  QFile locFile(locFName + ".lbl");
  QFile segFile(segFName + ".lbl");

  if (!locFile.open(QIODevice::WriteOnly | QIODevice::Text))
    return;

  if (!segFile.open(QIODevice::WriteOnly | QIODevice::Text))
    return;
  
  QTextStream locOut(&locFile);
  QTextStream segOut(&segFile);

  // test if utterances have been labelled
  int i(0);

  while (i < m_subRefLbl.size() && !labeled) {
    labeled = (m_subRefLbl[i] != "S");
    i++;
  }

  // export .lbl file
  while (it != m_shotPatterns.end()) {

    pattLabel = it.key();
    currSubs = it.value();

    for (int i(0); i < currSubs.size(); i++) {

      // index of current utterance
      uttIdx = currSubs[i].first;

      // adjusting utterance boundaries to shot pattern ones
      QPair<qint64, qint64> pair = adjustSubBoundaries(m_subBound[uttIdx].first, m_subBound[uttIdx].second, m_strictShotPattBound[pattLabel]);

      // setting utterance boundaries
      start = static_cast<qreal>(pair.first) / 1000.0;
      end = static_cast<qreal>(pair.second) / 1000.0;

      // speaker label
      spkLabel = m_subRefLbl[uttIdx];
      spkLabel.replace(QRegularExpression(" "), "_");
      
      // write out data
      if (labeled) {

	segOut << start << " " << end << " " << (pattLabel + "_" + spkLabel ) << "\n";
	locOut << start << " " << end << " " << spkLabel << "\n";
	
	
	// updating global speech boundaries
	if (start < globStart)
	  globStart = start;
	if (end > globEnd)
	  globEnd = end;
      }
    }
    
    it++;
  }

  // export .uem file
  QFile uemFile(fName + ".uem");

  QRegularExpression re(".*/(.+_.+)");
  QRegularExpressionMatch match = re.match(fName);
  QString baseName;
      
  if (match.hasMatch())
    baseName = match.captured(1);

  if (!uemFile.open(QIODevice::WriteOnly | QIODevice::Text))
    return;

  QTextStream uemOut(&uemFile);
  uemOut << baseName << " " << 1 << " " << globStart << " " << globEnd << "\n";
}

QPair<qint64, qint64> ProjectModel::adjustSubBoundaries(qint64 subStart, qint64 subEnd, QList<QPair<qint64, qint64>> shotPattBound)
{
  bool found(false);
  int i(0);

  while (i < shotPattBound.size() && !found) {

    // truncate utterance at the beginning
    if (subStart < shotPattBound[i].first && subEnd > shotPattBound[i].first) {
      subStart = shotPattBound[i].first;
      found = true;
    }

    // utterance included in shot
    else if (subStart >= shotPattBound[i].first && subEnd <= shotPattBound[i].second)
      found = true;

    // truncate utterance at the end
    else if (subStart < shotPattBound[i].second && subEnd > shotPattBound[i].second) {
      subEnd = shotPattBound[i].second;
      found = true;
    }
    i++;
  }

  return QPair<qint64, qint64>(subStart, subEnd);
}

void ProjectModel::improveSpkDiar()
{
  QMap<QString, int> speakers;
  QMap<QString, QMap<QString, int>> speakerList;
  QMap<QString, QMap<QString, int>>::const_iterator shotIt;
  int totSegment;

  nFramesByCamLabel(m_series, speakerList, Segment::Automatic, VideoFrame::Hyp2);

  shotIt = speakerList.constBegin();
  QMap<QString, int>::const_iterator spkIt;

  while (shotIt != speakerList.constEnd()) {
    QString label = shotIt.key();
    speakers = shotIt.value();
    
    totSegment = 0;

    qDebug() << label;

    spkIt = speakers.constBegin();
    while (spkIt != speakers.constEnd()) {
      totSegment += spkIt.value();
      spkIt++;
    }

    spkIt = speakers.constBegin();
    while (spkIt != speakers.constEnd()) {
			     
      qDebug() << spkIt.key() << spkIt.value() / static_cast<qreal>(totSegment) * 100;

      spkIt++;
    }

    qDebug() << "";
			   
    shotIt++;
  }
}

void ProjectModel::retrieveShotSub(qint64 position)
{
  QMap<QString, QList<QPair<qint64, qint64>>>::const_iterator it = m_shotPattBound.begin();
  QList<QPair<qint64, qint64>> bounds;
  QList<QPair<int, qreal>> subFeatures;
  QList<QPair<int, qreal>> subFeaturesShot1;
  QList<QPair<int, qreal>> subFeaturesShot2;
  QString pattLabel;
  QStringList shotLabels;
  QStringList labels1;
  QStringList labels2;
  bool found(false);

  // retrieving current shot pattern
  while (!found && it != m_shotPattBound.end()) {
    bounds = it.value();

    int i(0);
    while (!found && i < bounds.size()) {
      if (position >= bounds[i].first && position <= bounds[i].second) {
	pattLabel = it.key();
	subFeatures = m_shotPatterns[pattLabel];
	found = true;
      }
      i++;
    }
    it++;
  }

  // remove aditional characters from pattern label
  QRegularExpression openPar(QRegularExpression::escape("("));
  QRegularExpression closePar(QRegularExpression::escape(")"));

  pattLabel.replace(openPar, "");
  pattLabel.replace(closePar, "");

  // split the pattern into its two components
  shotLabels = pattLabel.split("_");

  if (shotLabels.size() == 2) {
     labels1 = shotLabels[0].split("|");
     labels2 = shotLabels[1].split("|");
  }

  // retrieving utterances of each pattern shot
  for (int i(0); i < subFeatures.size(); i++) {

    // loop over first series of equivalent shots
    for (int j(0); j < labels1.size(); j++)
      if (m_shotUtterances[labels1[j]].contains(subFeatures[i]))
	subFeaturesShot1.push_back(subFeatures[i]);

    // loop over second series of equivalent shots
    for (int j(0); j < labels2.size(); j++)
      if (m_shotUtterances[labels2[j]].contains(subFeatures[i]))
	subFeaturesShot2.push_back(subFeatures[i]);
  }

  emit getCurrentPattern(subFeatures);
  emit getPatternFirstShot(subFeaturesShot1);
  emit getPatternSecondShot(subFeaturesShot2);
}

void ProjectModel::currentSub(qint64 position)
{
  bool found(false);
  int iSup(m_subBound.size()-1);
  int iInf(0);
  int iMed(-1);
  
  while (!found && iSup >= iInf) {
    iMed = (iSup + iInf) / 2;
    if (position >= m_subBound[iMed].first && position <= m_subBound[iMed].second)
      found = true;
    else if (position < m_subBound[iMed].first)
      iSup = iMed - 1;
    else if (position > m_subBound[iMed].second)
      iInf = iMed + 1;
  }

  if (!found)
    iMed = -1;

  emit currentSubtitle(iMed);
}

void ProjectModel::playSubtitle(QList<int> utter)
{
  QList<QPair<qint64, qint64>> utterances;

  for (int i(0); i < utter.size(); i++)
    utterances.push_back(QPair<qint64, qint64>(m_subBound[utter[i]].first, m_subBound[utter[i]].second));
  emit playSegments(utterances);
}

void ProjectModel::playSeg(QList<QPair<qint64, qint64>> segments)
{
  emit playSegments(segments);
}

///////////////////////////////////////
// test if shot level already exists //
///////////////////////////////////////

bool ProjectModel::shotLevelCreated(Segment *segment)
{
  Shot *shot = 0;

  // searching among parent segments
  while (segment != 0 && !(shot = dynamic_cast<Shot *>(segment)))
    segment = segment->parent();

  if (segment == 0)
    return false;

  return true;
}

/////////////////////////
// returns first frame //
/////////////////////////

Segment * ProjectModel::getFirstVideoFrame(Segment *segment)
{
  VideoFrame *frame = 0;

  // segment is already a frame
  if ((frame = dynamic_cast<VideoFrame *>(segment)))
    return frame->parent()->child(0);

  // segment is not a frame: retrieving first frame among children
  else
    while (!(frame = dynamic_cast<VideoFrame *>(segment)))
      segment = segment->child(0);

  return frame;
}

void ProjectModel::depthFirstToShots(Segment *segment) const
{
  if ((dynamic_cast<Shot *>(segment)))
    emit getShot(segment);

  for (int i(0); i < segment->childCount(); i++)
    depthFirstToShots(segment->child(i));
}

void ProjectModel::depthFirstToSpokenFrames(Segment *segment, VideoFrame::SpeakerSource source) const
{
  VideoFrame *vFrame;
  QString speaker;

  if ((vFrame = dynamic_cast<VideoFrame *>(segment)))
    emit getSpokenFrame(vFrame->getPosition(), vFrame->getSub(), vFrame->getSpeaker(source));

  for (int i(0); i < segment->childCount(); i++)
    depthFirstToSpokenFrames(segment->child(i), source);
}

void ProjectModel::retrieveShotPositions(Segment *segment, QList<qint64> &shotPositions) const
{
  if ((dynamic_cast<Shot *>(segment)))
    shotPositions.push_back(segment->getPosition());

  for (int i(0); i < segment->childCount(); i++)
    retrieveShotPositions(segment->child(i), shotPositions);
}

void ProjectModel::retrieveSimCamLabels(Segment *segment, QList<int> &autCamLabels, QList<int> &manCamLabels) const
{
  if ((dynamic_cast<Shot *>(segment))) {
    autCamLabels.push_back(segment->getCamera(Segment::Automatic));
    manCamLabels.push_back(segment->getCamera(Segment::Manual));
  }

  for (int i(0); i < segment->childCount(); i++)
    retrieveSimCamLabels(segment->child(i), autCamLabels, manCamLabels);
}

void ProjectModel::nFramesByCamLabel(Segment *segment, QMap<QString, QMap<QString, int>> &speakerList, Segment::Source vSource, VideoFrame::SpeakerSource sSource) const
{
  Shot *shot;
  QString label;
  QMap<QString, int> shotSpeakers;
  QMap<QString, int> currSpeakers;
  QMap<QString, int>::const_iterator it;

  if ((shot = dynamic_cast<Shot *>(segment))) {

    label = "C" + QString::number(shot->getCamera(vSource));

    if (label != "C-1" && !(shotSpeakers = shot->getSpeakerList(sSource)).isEmpty()) {
      currSpeakers = speakerList.value(label);
      
      it = shotSpeakers.constBegin();

      while (it != shotSpeakers.constEnd()) {
	currSpeakers.insert(it.key(), currSpeakers.value(it.key()) + it.value());
	it++;
      }

      speakerList.insert(label, currSpeakers);
    }
  }

  for (int i(0); i < segment->childCount(); i++)
    nFramesByCamLabel(segment->child(i), speakerList, vSource, sSource);
}

void ProjectModel::retrieveSpokenVFrames(Segment *segment, QList<VideoFrame *> &spkVFrames, VideoFrame::SpeakerSource source) const
{
  VideoFrame *frame;

  if ((frame = dynamic_cast<VideoFrame *>(segment)) && 
      !frame->getSpeaker(source).isEmpty() &&
      !frame->getSub().isEmpty())
    spkVFrames.push_back(frame);

  for (int i(0); i < segment->childCount(); i++)
    retrieveSpokenVFrames(segment->child(i), spkVFrames, source);
}

void ProjectModel::retrieveVFrames(Segment *segment, QList<VideoFrame *> &vFrames) const
{
  VideoFrame *frame;

  if ((frame = dynamic_cast<VideoFrame *>(segment)))
    vFrames.push_back(frame);

  for (int i(0); i < segment->childCount(); i++)
    retrieveVFrames(segment->child(i), vFrames);
}

void ProjectModel::retrieveSpeakersList(Segment *segment, QList<QString> &speakers, VideoFrame::SpeakerSource source) const
{
  VideoFrame *frame;

  if ((frame = dynamic_cast<VideoFrame *>(segment)))
    speakers.push_back(frame->getSpeaker(source));

  for (int i(0); i < segment->childCount(); i++)
    retrieveSpeakersList(segment->child(i), speakers, source);
}

arma::mat ProjectModel::genWMat(QMap<QString, QList<int>> spkIdx, const arma::mat &X)
{
  // computing W
  mat W;

  if (spkIdx.size() > 0) {
    
    int nUtter(m_subBound.size());
    umat spkRows = zeros<umat>(spkIdx.size(), nUtter);

    QMap<QString, QList<int>>::const_iterator it = spkIdx.begin();
  
    int i(0);

    while (it != spkIdx.end()) {

      QList<int> indices = it.value();

      for (int j(0); j < indices.size(); j++)
	spkRows(i, indices[j]) = 1;

      it++;
      i++;
    }

    int m(X.n_rows);
    int n(X.n_cols);
    int nSpk(spkRows.n_rows);
  
    W.zeros(n, n);

    // looping over the speakers
    for (int i(0); i < nSpk; i++) {
    
      // index of current speaker utterances in X matrix
      umat idx = find(spkRows.row(i));
    
      // number of current speaker utterances
      int nUtt(idx.n_rows);

      // submatrix of vectorized speaker utterances
      mat S = X.rows(idx);

      // speaker covariance matrix
      mat C = zeros(n, n);

      // mean vector of speaker utterance vectors
      mat mu = mean(S);

      // looping over speaker utterances
      for (int j(0); j < nUtt; j++) {
	mat dev = S.row(j) - mu;
	C += dev.t() * dev;
      }

      // updating W
      W += C;
    }

    // normalizing W
    W /= m;
  }
  
  else
    W = cov(X);

  return W;
}