merge_pip.cpp 30.3 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
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <string.h>
#include <list>
#include <deque>
#include "tools.h"
#include "AVTranscoder.h"
#include "ConfigFile.h"

bool only_print = false;
bool keep_tmp_files = false;
bool out_one_video = true;


class fileinfo {
public:
	float start_time;
	float end_time;
	string name;
	int index;
	unsigned int uid;
	media_type m_type;
	media_role m_role;
	int width;
	int height;
	int rotate; //degree,0,90,180 ...
};



vector<fileinfo>  media_files;

const char * MERGED_PREFIX = "";
const char * PIP_PREFIX = "pip_";

float get_file_duration(const char *mediafile, bool bVideo);

void run_shell_cmd(const char * cmd)
{
	if (only_print){
		printf("%s\n", cmd);
	}
	else
	{
		printf("run command:%s\n", cmd);
		system(cmd);
	}
}


char exe_path[1024] = { 0 };
#ifdef WIN32
#include <Windows.h>

int GetExePath()
{
	char path_buffer[MAX_PATH] = "";
	char drive[32] = "";
	char dir[256] = "";
	char fname[64] = "";
	char ext[32] = "";

	GetModuleFileNameA(NULL, path_buffer, 256);
	_splitpath(path_buffer, drive, dir, fname, ext);

	strcpy(exe_path, drive);
	strcat(exe_path, dir);
	return 0;
}
#else
#include <unistd.h>
int GetExePath()
{
	char path[1024];
	int cnt = readlink("/proc/self/exe", path, 1024);
	if (cnt < 0 || cnt >= 1024)
	{
		return -1;
	}
	
	for (int i = cnt; i >= 0; --i)
	{
		if (path[i] == '/')
		{
			path[i + 1] = '\0';
			break;
		}
	}
	strcpy(exe_path, path);
	return 0;
}
#endif

char cfg_path[1024];

void get_config_path(){

	GetExePath();
	strcpy(cfg_path, exe_path);

#if 0
	strcpy(cfg_path, getenv("HOME"));
	strcat(cfg_path, "/merge_av/");
#endif
}

const char * default_vcodec_param = "-vcodec libx264 -level 3.1 -preset veryfast -g 100 -r 20 -bf 0 -vsync cfr";
const char * default_acodec_param = "-acodec copy";
const char * default_av_codec_param = "-acodec aac -vcodec libx264 -level 3.1 -preset veryfast -g 100 -r 20 -bf 0 -vsync cfr";
//const char * default_pip_param = "-filter_complex \"[1:v]scale=w=96:h=72:force_original_aspect_ratio=decrease[b];[0:v][b]overlay=x=0:y=0\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2,volume=1";
const char * default_pip_param = "-filter_complex \"[1:v]scale=w=320:h=240:force_original_aspect_ratio=decrease[b];[0:v]scale=w=320:h=240,pad=320:480:0:0:#165a82[c],[c][b]overlay=x=0:y=240\" -filter_complex amix=inputs=2:duration=first:dropout_transition=2,volume=1";
const char * default_pip1_param = " -filter_complex \"scale=w=320:h=240,pad=320:480:0:0:#165a82\" -vcodec libx264 -level 3.1 -preset veryfast -g 100 -r 20 -bf 0 -vsync cfr -acodec copy";


char av_codec_param[1024];
char vcodec_param[1024];
char acodec_param[1024];
char pip_param[1024];
char pip1_param[1024];

void addinfo(float t, string name, bool bstart,media_role role,unsigned int uid){
	media_type mtype = name.substr(name.length() - 4, name.length()) == ".aac" ? mt_audio : mt_video;
	if (bstart) {
		fileinfo f;
		f.start_time = t;
		f.end_time = f.start_time;
		f.name = name;
		f.m_type = mtype;
		f.m_role = role;
		f.uid = uid;
		f.rotate = 0;

		media_files.push_back(f);
	}
	else {
		int i;
		for (i = 0; i < media_files.size(); i++) {
			if (media_files[i].name == name) {
				media_files[i].end_time = t;
				break;
			}
		}

		if (i == media_files.size())
		{
			printf("\nerror ,file : %s  close but not started!", name.c_str());
		}
	}
}

void addinfo(const char * name, const char * width, const char * height, const char * rotation){
	int i = 0;
	for (; i < media_files.size(); i++) {
		if (media_files[i].name == name) {
			media_files[i].width = atoi(width);
			media_files[i].height = atoi(height);
			media_files[i].rotate = atoi(rotation);
			break;
		}
	}

	if (i == media_files.size())
	{
		printf("\nerror ,file : %s  info but not found!", name);
	}
}

void addinfo(const char * name, const char * rotation){
	int i = 0;
	for (; i < media_files.size(); i++) {
		if (media_files[i].name == name) {
			if (media_files[i].end_time > media_files[i].start_time) {
				printf("\n%s: set rotate after media file is closed,ignore!", name);
			}
			else {
				media_files[i].rotate = atoi(rotation);
			}
			break;
		}
	}

	if (i == media_files.size())
	{
		printf("\nerror ,file : %s  set rotate but not found!", name);
	}
}

void split(string str, string separator, vector<string> &result, bool includeEmptyItem = false) {
	result.clear();
	string::size_type position = str.find(separator);
	string::size_type lastPosition = 0;
	int separatorLength = separator.length();

	while (position != str.npos) {
		string s = str.substr(lastPosition, position - lastPosition);
		if (!s.empty() || includeEmptyItem)
			result.push_back(s);
		lastPosition = position + separatorLength;
		position = str.find(separator, lastPosition);
	}
	result.push_back(str.substr(lastPosition, string::npos));
}

void split_audio(const char * audiofile, float audio_start, float duration, char * destfile)
{
	char buf[2048];
	sprintf(buf, "ffmpeg -y -i %s -ss %.3f -t %.3f %s %s", audiofile, audio_start, duration, acodec_param, destfile);
	run_shell_cmd(buf);
}

void split_av(const char * mediafile, float start, float duration, char * destfile)
{
	char buf[2048];
	sprintf(buf, "ffmpeg -y -i %s -ss %.3f -t %.3f %s %s", mediafile, start, duration, av_codec_param, destfile);
	run_shell_cmd(buf);
}

void split_av_for_1pip(const char * mediafile, float start, float duration, char * destfile)
{
	char buf[2048];
	sprintf(buf, "ffmpeg -y -i %s -ss %.3f -t %.3f %s %s", mediafile, start, duration, pip1_param, destfile);
	run_shell_cmd(buf);
}

void transcode_to_1pip(const char * mediafile, char * destfile)
{
	char buf[2048];
	sprintf(buf, "ffmpeg -y -i %s %s %s", mediafile, pip1_param, destfile);
	run_shell_cmd(buf);
}

void get_video_first_frame_jpeg(const char * video, const char * destfile)
{
	char buf[2048];
	sprintf(buf, "ffmpeg -y -i %s -vframes 1 -ss 0 -f mjpeg -an %s", video, destfile);
	run_shell_cmd(buf);
}


void merge_audio_pic(const char * audio, const char * picfile, const char * destfile)
{
	char buf[2048];
	sprintf(buf, "ffmpeg -y -loop 1 -i %s -i %s -loop 0 -shortest %s %s %s", picfile, audio, acodec_param, vcodec_param, destfile);
	run_shell_cmd(buf);
}


void merge_audio_video(const char * audio, const char * video, int rotate, const char * destfile)
{
	char buf[2048];
	if (0 == rotate) {
		sprintf(buf, "ffmpeg -y -i %s -i %s %s %s %s", audio, video, acodec_param, vcodec_param, destfile);
	}
	else {
		const char * vf = "";
		if (rotate == 180){
			vf = "-vf rotate=PI";
		}
		else if (rotate == 90) {
			vf = "-vf rotate=PI/2";
		}
		else if (rotate == 270) {
			vf = "-vf rotate=PI*3/2"; 
		}
		sprintf(buf, "ffmpeg -y -i %s -i %s %s %s %s %s", audio, video, acodec_param, vf, vcodec_param, destfile);
	}
	run_shell_cmd(buf);
}

void merge_video_pip(const char * ch0, const char * ch1, const char * destfile)
{
	char buf[2048];
	sprintf(buf, "ffmpeg -y -i %s -i %s %s %s %s", ch0, ch1, pip_param, av_codec_param, destfile);
	run_shell_cmd(buf);
}

void merge_video_silence(fileinfo video, const char * aacfile, const char * destfile)
{
	char buf[2048];
	sprintf(buf, "ffmpeg -y  -i %s -i %s -shortest %s %s %s", aacfile, video.name.c_str(), acodec_param, vcodec_param, destfile);
	run_shell_cmd(buf);
}


void concate_files(vector<string > merged_files, const char * destfile)
{
	char buf[2048];
#ifdef WIN32
	sprintf(buf, "copy /B %s ", merged_files[0].c_str());

	for (int i = 1; i < merged_files.size(); i++) {
		strcat(buf, " + /B ");
		strcat(buf, merged_files[i].c_str());
	}
	strcat(buf, " ");
#else
	strcpy(buf, "cat  ");

	for (int i = 0; i < merged_files.size(); i++) {
		strcat(buf, " ");
		strcat(buf, merged_files[i].c_str());
	}
	strcat(buf, "> ");
#endif // WIN32
	strcat(buf, destfile);
	run_shell_cmd(buf);
}

void adjust_dest_timecode(const char * src, const char * dest)
{
	char buf[2048];
	sprintf(buf, "ffmpeg -y -i %s -acodec copy -vcodec copy %s", src, dest);
	run_shell_cmd(buf);
}

#ifndef WIN32
#include <unistd.h>
#endif


void remove_file(const char * file)
{
#ifdef WIN32
	_unlink(file);
#else
	unlink(file);
#endif
}

void removefiles(vector<string> files)
{
	for (int i = 0; i < files.size(); i++) {
		remove_file(files[i].c_str());
	}
}

float parse_ffmpeg_duration(const char * file)
{
	FILE * fp = fopen(file, "rb");
	if (!fp) {
		printf("\nOpen %s error\n", file);
		return -1.0;
	}
	fseek(fp, 0l, SEEK_END);
	long file_len = ftell(fp);
	fseek(fp, 0l, SEEK_SET);

	char * content = new char[file_len + 1];
	fread(content, 1, file_len, fp);
	fclose(fp);

	content[file_len] = 0;

	if (!keep_tmp_files) {
		remove_file(file);
	}

	char * pDuration = strstr(content, "Duration:");
	if (!pDuration){
		printf("\ncan't find 'Duration:' in %s\n", file);
		delete content;
		return -1.0;
	}

	char * pComma = strstr(pDuration, ",");
	if (!pDuration){
		printf("\ncan't find ',' after 'Duration:' in %s\n", file);
		delete content;
		return -1.0;
	}
	int len = pComma - pDuration - 10;
	strncpy(content, pDuration + 10, len);
	content[len] = 0;
	vector <string > hms;
	split(content, ":", hms);

	delete content;

	if (hms.size() != 3) {
		printf("\nerro parsing duration  in %s, the duration string is:%s\n", file, content);
		return -1.0;
	}

	int hour = atoi(hms[0].c_str());
	int minute = atoi(hms[1].c_str());
	float sec = atof(hms[2].c_str());
    
	return hour * 3600 + minute * 60 + sec;
}

float get_mp4_duration(const char *mediafile, bool bVideo)
{
	char buf[2048];

	if (bVideo){
		sprintf(buf, "ffmpeg -y -i %s -vcodec copy -an %s.ts", mediafile, mediafile);
	}
	else {
		sprintf(buf, "ffmpeg -y -i %s -acodec copy -vn %s.ts", mediafile, mediafile);
	}
	run_shell_cmd(buf);

	if (bVideo){
		sprintf(buf, "ffmpeg -y -i %s.ts -vcodec copy -an %s.mkv", mediafile, mediafile);
}
	else {
		sprintf(buf, "ffmpeg -y -i %s.ts -acodec copy -vn %s.mkv", mediafile, mediafile);
	}
	run_shell_cmd(buf);

#ifdef WIN32
	sprintf(buf, "ffmpeg -i %s.mkv > %s.txt 2>&1", mediafile, mediafile);
#else
	sprintf(buf, "ffmpeg -i %s.mkv &> %s.txt", mediafile, mediafile);
#endif

	run_shell_cmd(buf);

	if (!keep_tmp_files) {
		char buf[2048];
		sprintf(buf, "%s.ts", mediafile);
		remove_file(buf);
		sprintf(buf, "%s.mkv", mediafile);
		remove_file(buf);
	}


	sprintf(buf, "%s.txt", mediafile);
	return parse_ffmpeg_duration(buf);
}

#ifdef WIN32
#define strcasecmp _stricmp 
#endif

float get_file_duration(const char *mediafile, bool bVideo)
{
	char buf[2048];
	int len = strlen(mediafile);
	if (len > 3) {
		if (!strcasecmp(mediafile + len - 4, ".mp4")) {
			return get_mp4_duration(mediafile, bVideo);
		}
	}
	if (bVideo){
		sprintf(buf, "ffmpeg -y -i %s -vcodec copy -an %s.mkv", mediafile, mediafile);
	}
	else {
		sprintf(buf, "ffmpeg -y -i %s -acodec copy -vn %s.mkv", mediafile, mediafile);
	}
	run_shell_cmd(buf);
#ifdef WIN32
	sprintf(buf, "ffmpeg -i %s.mkv > %s.txt 2>&1", mediafile, mediafile);
#else
	sprintf(buf, "ffmpeg -i %s.mkv &> %s.txt", mediafile, mediafile);
#endif

	run_shell_cmd(buf);

	if (!keep_tmp_files) {
		char buf[2048];
		sprintf(buf, "%s.mkv", mediafile);
		remove_file(buf);
	}


	sprintf(buf, "%s.txt", mediafile);
	return parse_ffmpeg_duration(buf);
}

void get_duration_from_video_file()
{
	bool tmp = only_print;
	only_print = false;

	for (int i = 0; i < media_files.size(); i++){
		if (media_files[i].m_type == mt_video) {
			float duration = get_file_duration(media_files[i].name.c_str(), true);
			if (duration >= 0.1) {
				printf("file:%s , duration in recording file: %.3f, duration parsed from file: %.3f\n", media_files[i].name.c_str(), media_files[i].end_time - media_files[i].start_time, duration);
				media_files[i].end_time = media_files[i].start_time + duration;
			}
		}
	}

	only_print = tmp;
}


void check_audio_duration()
{
	bool tmp = only_print;
	only_print = false;

	for (int i = 0; i < media_files.size(); i++){
		if (media_files[i].m_type == mt_audio) {
			fileinfo f = media_files[i];
			if (f.end_time - f.start_time < 0.1){//avoid no close 
				float duration = get_file_duration(f.name.c_str(), false);
				media_files[i].end_time = f.start_time + duration;
				printf("file:%s , duration in recording file maybe is not set, duration parsed from file: %.3f\n", f.name.c_str(), duration);
			}
		}
	}

	only_print = tmp;
}



list <media_info> sorted_media; //sorted media files only by start
list <media_info> sorted_media_with_end; //sorted media files with end in sort
vector<media_info>  media_infos;
vector<string > merged_files;
vector<string>  tmp_files;
int nf;//the index of processing target merged ts
char destfile[1024], audio_file[1024], pic_file[1024];
char blank_pic_file[1024];
char silence_aac_file[1024];

char out_info_file[1024];
FILE * fp_out_info = NULL;

void merge_pic_silence(const char * pic, float duration, const char * destfile)
{
	char buf[2048];
	sprintf(buf, "ffmpeg -y -loop 1 -i %s -i %s -loop 0 -t %.3f -shortest %s %s %s", pic, silence_aac_file, duration, acodec_param, vcodec_param, destfile);
	run_shell_cmd(buf);
}

int parse_ffmpeg_lastframe(const char * file)
{
	FILE * fp = fopen(file, "rb");
	if (!fp) {
		printf("\nOpen %s error\n", file);
		return -1.0;
	}
	fseek(fp, 0l, SEEK_END);
	long file_len = ftell(fp);
	fseek(fp, 0l, SEEK_SET);

	char * content = new char[file_len + 1];
	fread(content, 1, file_len, fp);
	fclose(fp);

	content[file_len] = 0;

	if (!keep_tmp_files) {
		remove_file(file);
	}

	char * pLastFrame = strstr(content, "frame=");
	if (!pLastFrame){
		printf("\ncan't find 'frame' in %s\n", file);
		delete content;
		return 0;
	}
	while (1){
		char * pFrame = strstr(pLastFrame + 6, "frame=");
		if (!pFrame){
			break;
		}
		pLastFrame = pFrame;
	}

	int frame = atoi(pLastFrame + 6);

	delete content;
	return frame;
}

void get_video_last_frame_jpeg(const char * video, const char * destfile) {
	char buf[2048];
	//first ,get 
	float duration = get_file_duration(video, true);
	if (duration > 0) {
		float start = 0;
		if (duration > 1) {
			start = duration - 1;
		}
#ifdef WIN32
		sprintf(buf, "ffmpeg -y -i %s -ss %.1f -an %s_last_%%d.jpg > %s.txt 2>&1", video, start, video,video);
#else
		sprintf(buf, "ffmpeg -y -i %s -ss %.1f -an %s_last_%%d.jpg &> %s.txt", video, start, video, video);
#endif
		run_shell_cmd(buf);
		sprintf(buf,"%s.txt", video);
		int last_frame = parse_ffmpeg_lastframe(buf);
		if (last_frame > 0) {
#ifdef WIN32
			sprintf(buf, "copy %s_last_%d.jpg %s", video,last_frame,destfile);
#else
			sprintf(buf, "cp %s_last_%d.jpg %s", video, last_frame,destfile);
#endif
			run_shell_cmd(buf);
			for (int i = 1; i <= last_frame; i++) {
				sprintf(buf, "%s_last_%d.jpg", video, i);
				tmp_files.push_back(buf);
			}
		}
	}
	else {
#ifdef WIN32
		sprintf(buf, "copy %s %s", blank_pic_file, destfile);
#else
		sprintf(buf, "cp %s %s", blank_pic_file, destfile);
#endif
	}
}


void add_media_info(media_info m)
{
	list<media_info>::iterator it = sorted_media.begin();
	for (; it != sorted_media.end(); it++){
		if (it->type_time > m.type_time){
			break;
		}
	}

	sorted_media.insert(it, m);
}

void add_media_info_with_end(media_info m)
{
	list<media_info>::iterator it = sorted_media_with_end.begin();
	for (; it != sorted_media_with_end.end(); it++){
		if (it->type_time > m.type_time){
			break;
		}
	}
	sorted_media_with_end.insert(it, m);
}

list<media_info> audio_files;

int count_audio_files(float mid)
{
	int files = 0;
	list<media_info>::iterator it = audio_files.begin();
	for (; it != audio_files.end(); it++){
		if (it->start_time < mid){
			if (it->end_time > mid) {
				files++;
			}
		}
		else {
			break;
		}
	}
	return files;
}

int max_audio = 1;
int width = 0;
int height = 0;
int width_teacher = 0;
int height_teacher = 0;
int width_student = 0;
int height_student = 0;
bool has_teacher = false;

void add_media_infos()
{
	sorted_media.clear();
	for (int i = 0; i < media_files.size(); i++) {
		fileinfo f = media_files[i];
		media_info m;
		m.index = i;
		m.name = f.name;
		m.start_time = f.start_time;
		m.end_time = f.end_time;
		m.m_type = f.m_type;
		m.t_type = tt_start;
		m.duration = f.end_time - f.start_time;
		m.type_time = m.start_time;
		m.width = f.width;
		m.height = f.height;
		m.rotate = f.rotate;
		m.m_role = f.m_role;
		m.uid = f.uid;
		m.start_time_ms = f.start_time * 1000;
		m.end_time_ms = f.end_time * 1000;
		add_media_info(m);
	}

	list<media_info>::iterator it = sorted_media.begin();
	int index = 0;
	for (; it != sorted_media.end(); it++,index++){
		it->sorted_index = index;
	}

	sorted_media_with_end = sorted_media;

	it = sorted_media.begin();
	for (; it != sorted_media.end(); it++){
		media_info m = *it;
		m.t_type = tt_end;
		m.type_time = m.end_time;
		add_media_info_with_end(m);
		if (it->m_type == mt_audio) {
				audio_files.push_back(*it);
		}
	}

	list<media_info> audio_type_files;

	it = sorted_media_with_end.begin();
	for (; it != sorted_media_with_end.end(); it++){
		if (it->m_type == mt_audio) {
			audio_type_files.push_back(*it);
		}
	}

	printf("\nsorted file info:");
	it = sorted_media_with_end.begin();
	for (; it != sorted_media_with_end.end();it++){
		if (it->m_type == mt_video) {
			printf("\n%2d %8.3f %s %s %4d %4d %3d", it->sorted_index, it->type_time, it->name.c_str(),  it->t_type == tt_start ? "start" : "end", it->width, it->height, it->rotate);
			if (it->rotate == 0 || it->rotate == 180) {
				if (width < it->width) {
					width = it->width;
				}
				if (height < it->height) {
					height = it->height;
				}
			}
			else {//set the image to landscape
				if (width < it->height) {
					width = it->height;
				}
				if (height < it->width) {
					height = it->width;
				}
			}
			if (it->m_role == mr_teacher) {
				has_teacher = true;
				if (it->rotate == 0 || it->rotate == 180) {
					if (width_teacher < it->width) {
						width_teacher = it->width;
					}
					if (height_teacher < it->height) {
						height_teacher = it->height;
					}
				}
				else {//set the image to landscape
					if (width_teacher < it->height) {
						width_teacher = it->height;
					}
					if (height_teacher < it->width) {
						height_teacher = it->width;
					}
				}
			}
			else {
				if (it->rotate == 0 || it->rotate == 180) {
					if (width_student < it->width) {
						width_student = it->width;
					}
					if (height_student < it->height) {
						height_student = it->height;
					}
				}
				else {//set the image to landscape
					if (width_student < it->height) {
						width_student = it->height;
					}
					if (height_student < it->width) {
						height_student = it->width;
					}
				}
			}
		}
		else {
			printf("\n%2d %8.3f %s %s", it->sorted_index, it->type_time, it->name.c_str(), it->t_type == tt_start ? "start" : "end");
		}
	}
	printf("\n-------------------------\n");

	it = audio_type_files.begin();
	if (it != audio_type_files.end()) {
		media_info last = *it;

		for (it++; it != audio_type_files.end(); it++) {
			if (it->t_type == tt_end) {
				if (last.t_type == tt_start) {
					float mid = (it->type_time + last.type_time) / 2;
					int files_with_mid = count_audio_files(mid);
					if (files_with_mid > max_audio) {
						max_audio = files_with_mid;
					}
				}
			}
			else {
				last = *it;
			}
		}
	}
}

void unifiy_start_time()
{
	float min_start = media_files[0].start_time;
	//get the min start
	for (int i = 1; i < media_files.size(); i++) {
		if (min_start > media_files[i].start_time) {
			min_start = media_files[i].start_time;
		}
	}

	//all the file start sub the min start
	for (int i = 0; i < media_files.size(); i++) {
		media_files[i].start_time -= min_start;
		media_files[i].end_time -= min_start;
	}
}

void init_merge_av()
{
	strcpy(blank_pic_file, cfg_path);
	strcat(blank_pic_file, "blank.jpg");

	strcpy(silence_aac_file, cfg_path);
	strcat(silence_aac_file, "silence.aac");

	check_audio_duration();
	get_duration_from_video_file();
	add_media_infos();

	merged_files.clear();
	tmp_files.clear();
}

void init_merge_pip()
{
	unifiy_start_time();

	add_media_infos();

	merged_files.clear();
	tmp_files.clear();
}



int get_output_file_name(const char * filename, const char * prefix,char * outputfile){
	char mainname[128];
	const char * p = strstr(filename, ".");
	if (p) {
		strncpy(mainname, filename, p - filename);
		mainname[p - filename] = 0;
	}
	else {
		strcpy(mainname, filename);
	}
	
	sprintf(outputfile, "%s%s.ts",prefix, mainname);
	return 0;
}


void save_out_info(const char * out_mediafile, const char * firstfile,double duration)
{
	if (!fp_out_info) {
		fp_out_info = fopen(out_info_file, "wt");
	}
	if (fp_out_info) {
		fprintf(fp_out_info, "%s  %s  %.3lf\n", out_mediafile, firstfile, duration);
		fclose(fp_out_info);
		fp_out_info = NULL;
	}
}


#define get_sub_str_to_x(x , source, len, result) strncpy(x, source, len); x[len] = 0; source += len; result = atoi(x);
time_t time_sec_1970_base = 0;
float get_uid_start_time_from_filename(const char * filename, unsigned int &uid)
{
	int year, month, day, hour, min, sec, minsec;
	char buf[5];
	//const char * start = strstr(filename, "_"); // used for parsing file name like uid_138471401_20181109095932880.txt
	const char * start = filename; //used for parsing file name like 138471401_20181109095932789.aac
	const char * end = strstr(start + 1, "_");
	if (end) {//get the next
		*(char *)end = 0;
		uid = atoi(start + 1);
		*(char *)end = '_';

		start = end;
	}
	else {
		*(char *)start = 0;
		uid = atoi(filename);
		*(char *)start = '_';
	}
	start++;
	end = strstr(start, ".");

	get_sub_str_to_x(buf, start, 4, year);

	get_sub_str_to_x(buf, start, 2, month);

	get_sub_str_to_x(buf, start, 2, day);

	get_sub_str_to_x(buf, start, 2, hour);

	get_sub_str_to_x(buf, start, 2, min);

	get_sub_str_to_x(buf, start, 2, sec);

	get_sub_str_to_x(buf, start, 3, minsec);

	time_t t = calc_sec1970(year, month, day, hour, min, sec);

	if (!time_sec_1970_base) {
		time_sec_1970_base = calc_sec1970(year, month, day, 0, 0, 0);
	}

	t -= time_sec_1970_base;

	return (float)(t) + minsec / 1000.0;
}


int readfile(const char * filename, media_role role)
{
	ifstream fin(filename);
	if (!fin) {
		return -1;
	}

	unsigned int uid = 0;
	float start_time = 0.0f; 
	float start_time_offset = 0.0f;

	const int  LINE_LENGTH = 1000;
	char  str[LINE_LENGTH];
	while (fin.getline(str, LINE_LENGTH))
	{
		vector < string > res;
		split(str, " ", res);
		if (res.size() >= 3) {
			if (res[2] == "create"){
				if (!uid){
					start_time = get_uid_start_time_from_filename(res[1].c_str(), uid);
					start_time_offset = atof(res[0].c_str());
				}
				addinfo(start_time + atof(res[0].c_str()) - start_time_offset, res[1], true, role, uid);
			}
			else if (res[2] == "close") {
				addinfo(start_time + atof(res[0].c_str()) - start_time_offset, res[1], false, role, uid);
			}
			else if (res[2] == "info") {
				if (res.size() > 5) {
					const char * pInfoW = res[3].c_str();
					const char * pInfoH = res[4].c_str();
					const char * pInfoR = res[5].c_str();
					if (!strncmp(pInfoW, "width=", 6) && !strncmp(pInfoH, "height=", 7) && !strncmp(pInfoR, "rotation=", 9)){
						addinfo(res[1].c_str(), pInfoW + 6, pInfoH + 7, pInfoR + 9);
					}
					else {
						printf("error info: %s,", str);
					}
				}
			}
			else if (res[2] == "rotate") {
				if (res.size() > 3) {
					const char * pInfo = res[3].c_str();
					if (!strncmp(pInfo, "rotation=", 9)){
						addinfo(res[1].c_str(), pInfo + 9);
					}
					else
					{
						printf("error rotation: %s,", str);
					}
				}
			}
		}
	}
	return 0;
}

vector<string> all_input_files_for_pip;

CConfigFile _codec_config;

char user_codec_cfg[1024] = { 0 };

void load_codec_param()
{
	strcpy(acodec_param, default_acodec_param);
	strcpy(vcodec_param, default_vcodec_param);
	strcpy(av_codec_param, default_av_codec_param);
	strcpy(pip_param, default_pip_param);
	strcpy(pip1_param, default_pip1_param);

	char cfgfile[1024];

	strcpy(cfgfile, cfg_path);

	if (user_codec_cfg[0]) {
		strcat(cfgfile, user_codec_cfg);
	}
	else {
		strcat(cfgfile, "merge_pip_codec.cfg");
	}

	if (_codec_config.load(cfgfile) < 0) {
		printf("open codec config file fail: %s", cfgfile);
	}
	else {
		printf("open codec config file success: %s", cfgfile);
	}
}

void get_outinfo_file_name(char * input)
{
#if 0
	strcpy(out_info_file, input);
	char * p = strstr(out_info_file, ".");
	if (p) {
		*p = 0;
	}
	strcat(out_info_file, "_out.txt");
#else
	strcpy(out_info_file, "m_");
	strcat(out_info_file, input);
#endif
}

string get_outmedia_file_name(const char * input)
{
	char out_media_file[1024];
	strcpy(out_media_file, "m_");

	strcat(out_media_file, input);
	char * p = strstr(out_media_file, ".");
	if (p) {
		*p = 0;
	}
	strcat(out_media_file, ".mp4");
	return out_media_file;
}

int load_record_info(char * record_info)
{
	ifstream fin(record_info);
	if (!fin) {
		return -1;
	}

	const int  LINE_LENGTH = 1000;
	char  str[LINE_LENGTH];
	bool bInTeacher = false;
	bool bInStudent = false;
	int nstudent = 0;

	media_files.clear();

	while (fin.getline(str, LINE_LENGTH))
	{
		if (!strncmp(str, "teacher:", 8)){
			bInTeacher = true;
			bInStudent = false;
			continue;
		}
		else if (!strncmp(str, "student:", 8)){
			bInTeacher = false;
			bInStudent = true;
			continue;
		}
		else if (strlen(str) < 20){
			continue;//assume the file name > 20
		}
		else if (bInTeacher){
			readfile(str, mr_teacher);
		}
		else if (bInStudent){
			readfile(str, mr_student);
		}
	}

	unifiy_start_time();

	add_media_infos();

	return 0;
}

#define MIN_TIME_INTERVAL 25

int process_av_files(char * record_info, int piptype, bool one2one_same_size, int64_t max_duration)
{
	time_t start, end;
	time(&start);
	load_record_info(record_info);

	get_outinfo_file_name(record_info);

	av_register_all();
	avfilter_register_all();

	bool one2one = max_audio <= 2;

	if (has_teacher == false && max_audio == 2) {
		one2one = false;
	}

	if (1 == piptype) {
		one2one = true;
		printf("using one2one layout\n");
	}
	else if(2 == piptype){
		one2one = false;
		printf("using one2many layout\n");
	}
	else {
		if (one2one) {
			printf("using one2one layout,because detected max %d audio\n",max_audio);
		}
		else {
			if (max_audio == 2 && has_teacher == false) {
				printf("using one2many layout,because detected max %d audio,but no teacher\n", max_audio);
			}
			else {
				printf("using one2many layout,because detected max %d audio\n", max_audio);
			}
		}
	}

	CAVTranscoder videoTranscoder(one2one, one2one_same_size, width_teacher, height_teacher, width_student, height_student, has_teacher, max_audio);
	videoTranscoder.set_max_audio(max_audio);

	int64_t cur_time = 0;
	bool has_file = sorted_media.size()!=0;
	std::string out_media_file,first_media_file;

	int64_t nextfile_start_time_ms;
	int encode_loop_count = 0;

	if (has_file) {
		media_info info = sorted_media.front();
		first_media_file = info.name;
		nextfile_start_time_ms = info.start_time_ms;

		out_media_file = get_outmedia_file_name(record_info);
		printf("open output file:%s\n", out_media_file.c_str());
		int ret = videoTranscoder.open_output_file(out_media_file.c_str());
		if (ret) {
			printf("open output file:%s  fail!\n", out_media_file.c_str());
			return ret;
		}
		else {
			printf("open output file:%s  success!\n", out_media_file.c_str());
		}
	}

	while (has_file){
		while (has_file){
			if (nextfile_start_time_ms - cur_time < MIN_TIME_INTERVAL) {
				media_info info = sorted_media.front();
				sorted_media.pop_front();
				videoTranscoder.add(info);
				has_file = sorted_media.size() != 0;
				if (has_file) {
					nextfile_start_time_ms = sorted_media.front().start_time_ms;
				}
			}
			else {
				break;
			}
		}

		cur_time = (int64_t) videoTranscoder.transcode();

		if (cur_time >= max_duration){
			printf("\n max duration reached, stop now");
			break;
		}


		encode_loop_count++;
		if (encode_loop_count == 1200) {
			encode_loop_count = 0;
			printf("\n encoded : %d s\n", cur_time / 1000);
		}
	}

	while (!videoTranscoder.all_processed()){
		if (cur_time >= max_duration){
			break;
		}
		cur_time = videoTranscoder.transcode();
		encode_loop_count++;
		if (encode_loop_count == 1200) {
			encode_loop_count = 0;
			printf("\n encoded : %d s\n", cur_time / 1000);
		}
	}

	videoTranscoder.close();

	save_out_info( out_media_file.c_str(), first_media_file.c_str(),((double)cur_time)/1000.0);

	time(&end);

	printf("\nfinished,used %"PRIu64" s, encoded %.0lf s, the speed ratio is %.3lfX\n", end - start, (double)cur_time / 1000, cur_time / 1000.0 / (end - start));

	return 0;
}

int main(int argc, char * argv[])
{
	if (argc < 2) {
		printf("   merge_pip 2.0.10\n");
		printf("   merge video files to one pip video according to record info file,\nusage:");
		printf("\n   %s record_info_filename [-t {0,1,2}]  [-c codec.cfg] [-s {1,0}]", argv[0]);
		printf("\n\n");
		return -1;
	}

	int piptype = 0;
	bool one2one_same_size = true;
	int64_t max_duration = INT64_MAX;
	for (int i = 2; i < argc; i++){
		if (!strcmp(argv[i], "-t")){
			i++;
			if (i > argc) {
				printf("error,should be 0, 1 or 2 after -t");
				return -2;
			}
			piptype = atoi(argv[i]);
		}
		else if (!strcmp(argv[i], "-c")){
			i++;
			if (i > argc) {
				printf("error,should have codec config file name after -c");
				return -2;
			}
			strcpy(user_codec_cfg,argv[i]);
		}
		else if (!strcmp(argv[i], "-s")){
			i++;
			if (i > argc) {
				printf("error,should be 1 or 0 after -s");
				return -2;
			}
			one2one_same_size = argv[i][0] == '1';
		}
		else if (!strcmp(argv[i], "-d")){
			i++;
			if (i > argc) {
				printf("error,should be 1 or 0 after -d");
				return -2;
			}
			max_duration = atoi(argv[i]);
		}
	}


	get_config_path();

	load_codec_param();

	return process_av_files(argv[1], piptype, one2one_same_size, max_duration);
}