merge_av.cpp 12.8 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
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <string.h>


bool only_print = false;
bool keep_tmp_files = false;
using   namespace  std;

class fileinfo {
public:
	float start_time;
	float end_time;
	string start_time_str;
	string end_time_str;
	string name;
};

enum media_type{
	type_audio = 0,
	type_video = 1,
};
vector<fileinfo>  media_files[2];

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

	if (!only_print){
		system(cmd);
	}
}

#ifdef WIN32
#include <Windows.h>

char exe_path[MAX_PATH] = { 0 };

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;
}
#endif

char cfg_path[1024];

void get_config_path(){
#ifdef WIN32
	GetExePath();
	strcpy(cfg_path, exe_path);
#else
	strcpy(cfg_path, getenv("HOME"));
	strcat(cfg_path, "/merge_av/");
#endif
}

const char * default_vcodec_param = "-vcodec libx264 -level 3.1 -preset veryfast -g 40 -r 20";
const char * default_acodec_param = "-acodec copy";

char vcodec_param[1024];
char acodec_param[1024];

bool first_time_set = false;
float start_time = 0.0f;

void addinfo(string t, string name, bool bstart){
	media_type mtype = name.substr(name.length() - 4, name.length()) == ".aac" ? type_audio : type_video;
	if (bstart) {
		fileinfo f;
		f.start_time = atof(t.c_str());
		f.end_time = f.start_time;
		f.start_time_str = t;
		f.end_time_str = t;
		f.name = name;

		if (!first_time_set) {
			first_time_set = true;
			start_time = f.start_time;
		}

		f.start_time -= start_time;

		media_files[mtype].push_back(f);
	}
	else {
		vector<fileinfo>  & files = media_files[mtype];
		int i;
		for (i = 0; i < files.size(); i++) {
			if (files[i].name == name) {
				files[i].end_time = atof(t.c_str());
				files[i].end_time_str = t;
				files[i].end_time -= start_time;
				break;
			}
		}

		if (i == files.size())
		{
			cout << "\nerror ,file : " << name << "  close but not started!";
		}
	}
}

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(fileinfo audio, float audio_start, float duration, char * destfile)
{
	char buf[2048];
	sprintf(buf, "ffmpeg -y -i %s -ss %.3f -t %.3f %s %s", audio.name.c_str(), audio_start, duration, acodec_param, destfile);
	run_shell_cmd(buf);
}

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

void merge_audio_pic(fileinfo audio, int nf, fileinfo video, const char * destfile)
{
	char buf[2048];
	sprintf(buf, "ffmpeg -y -loop 1 -i %s.jpg -i %d_%s -loop 0 -shortest %s %s %s", video.name.c_str(), nf, audio.name.c_str(), acodec_param, vcodec_param, destfile);
	run_shell_cmd(buf);
}

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

void merge_audio_pic(fileinfo 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.name.c_str(), acodec_param, vcodec_param, destfile);
	run_shell_cmd(buf);
}

void megre_audio_video(fileinfo audio, int nf, fileinfo video, const char * destfile)
{
	char buf[2048];
	sprintf(buf, "ffmpeg -y -i %d_%s -i %s %s %s %s", nf, audio.name.c_str(), 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 get_video_duration(const char *videofile)
{
	char buf[2048];
	sprintf(buf, "ffmpeg -y -i %s -vcodec copy -an %s.mkv", videofile, videofile);
	run_shell_cmd(buf);
#ifdef WIN32
	sprintf(buf, "ffmpeg -i %s.mkv > %s.txt 2>&1", videofile, videofile);
#else
	sprintf(buf, "ffmpeg -i %s.mkv &> %s.txt", videofile, videofile);
#endif

	run_shell_cmd(buf);

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

	sprintf(buf, "%s.txt", videofile);

	FILE * fp = fopen(buf, "rb");
	if (!fp) {
		printf("\nOpen %s error\n", buf);
		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) {
		char buf[2048];
		sprintf(buf, "%s.txt", videofile);
		remove_file(buf);
	}

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

	char * pComma = strstr(pDuration, ",");
	if (!pDuration){
		printf("\ncan't find ',' after 'Duration:' in %s\n", buf);
		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", buf, content);
		delete 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;
}

void get_duration_from_video_file()
{
	vector<fileinfo>  & filesvideo = media_files[type_video];
	vector<string>  tmp_files;

	bool tmp = only_print;
	only_print = false;


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

	only_print = tmp;
}

int process_files(const char * output_dest_file)
{
	vector<fileinfo>  & filesaudio = media_files[type_audio];
	vector<fileinfo>  & filesvideo = media_files[type_video];
	vector<string > merged_files;
	vector<string>  tmp_files;
	int nv = 0;
	int nf = 0;
	char destfile[1024];
	char blank_pic_file[1024];

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

	get_duration_from_video_file();

	if (filesvideo.size()) {//has video files
		for (int i = 0; i < filesaudio.size(); i++){  //
			fileinfo audio = filesaudio[i];
			float audio_start = 0;

			for (; nv < filesvideo.size(); nv++) {
				fileinfo video = filesvideo[nv];

				if (video.start_time - audio_start > 0.100) {

					sprintf(destfile, "%d_%s", nf, audio.name.c_str());
					split_audio(audio, audio_start, video.start_time - audio_start, destfile);
					tmp_files.push_back(destfile);

					audio_start = video.start_time;

					sprintf(destfile, "%s.jpg", video.name.c_str());
					get_video_first_frame_jpeg(video, destfile);
					tmp_files.push_back(destfile);

					sprintf(destfile, "%d.ts", nf);
					merge_audio_pic(audio, nf, video, destfile);
					merged_files.push_back(destfile);
					nf++;
				}
				if (nv != filesvideo.size() - 1) {// not the last one
					sprintf(destfile, "%d_%s", nf, audio.name.c_str());
					split_audio(audio, video.start_time, video.end_time - video.start_time, destfile);
					tmp_files.push_back(destfile);

					audio_start = video.end_time;
					sprintf(destfile, "%d.ts", nf);
					megre_audio_video(audio, nf, video, destfile);
					merged_files.push_back(destfile);
					nf++;
				}
				else {
					
					sprintf(destfile, "%d_%s", nf, audio.name.c_str());

					if (audio.end_time - video.end_time < 1.0) {
						split_audio(audio, video.start_time, audio.end_time - video.start_time, destfile);
						tmp_files.push_back(destfile);

						audio_start = video.end_time;

						sprintf(destfile, "%d.ts", nf);
						megre_audio_video(audio, nf, video, destfile);
						merged_files.push_back(destfile);
						nf++;
					}
					else{
						split_audio(audio, video.start_time, video.end_time - video.start_time, destfile);
						tmp_files.push_back(destfile);

						audio_start = video.end_time;

						sprintf(destfile, "%d.ts", nf);
						megre_audio_video(audio, nf, video, destfile);
						merged_files.push_back(destfile);
						nf++;

						sprintf(destfile, "%d_%s", nf, audio.name.c_str());
						split_audio(audio, video.end_time, audio.end_time - video.end_time, destfile);
						tmp_files.push_back(destfile);

						sprintf(destfile, "%d.ts", nf);
						merge_audio_pic(audio, nf, blank_pic_file, destfile);
						merged_files.push_back(destfile);
						nf++;
					}
				}
			}
		}
	}
	else {//only audio

		if (filesaudio.size() == 1){
			fileinfo audio = filesaudio[0];
			merge_audio_pic(audio, blank_pic_file, "dest.ts");
			return 0;
		}

		for (int i = 0; i < filesaudio.size(); i++){
			fileinfo audio = filesaudio[i];
			sprintf(destfile, "%d.ts", nf);
			merge_audio_pic(audio, blank_pic_file, destfile);
			merged_files.push_back(destfile);
			nf++;
		}
	}

	concate_files(merged_files, "m.ts");
	tmp_files.push_back("m.ts");

	adjust_dest_timecode("m.ts", output_dest_file);


	if (!keep_tmp_files) {
		removefiles(tmp_files);
		removefiles(merged_files);
	}

	return 0;
}


int readfile(char * filename)
{
	ifstream fin(filename);
	if (!fin) {
		return -1;
	}
	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"){
				addinfo(res[0], res[1], true);
			}
			else if (res[2] == "close") {
				addinfo(res[0], res[1], false);
			}
		}
	}
	return 0;
}


void load_codec_param()
{
	strcpy(acodec_param, default_acodec_param);
	strcpy(vcodec_param, default_vcodec_param);

	char cfgfile[1024];

	strcpy(cfgfile, cfg_path);
	strcat(cfgfile, "merge_av.cfg");

	ifstream fin(cfgfile);
	if (!fin) {
		return;
	}
	const int  LINE_LENGTH = 1000;
	char  str[LINE_LENGTH];
	str[0] = 0;
	if (fin.getline(str, LINE_LENGTH))
	{
		printf("\nload video codec from %s: %s\n", cfgfile, str);
		strcpy(vcodec_param, str);
	}
	str[0] = 0;
	if (fin.getline(str, LINE_LENGTH))
	{
		printf("load audio codec from %s: %s\n", cfgfile, str);
		strcpy(acodec_param, str);
	}
}

int main(int argc, char * argv[])
{
	if (argc < 2) {
		printf("   merge_av 1.0.0\n");
		printf("   run ffmpeg to merge audio and video files according to the record info file,\nusage:");
		printf("\n   %s record_info_filename [-p] [-k]", argv[0]);
		printf("\n   -p :only print the command,don't run ffmpeg");
		printf("\n   -k :keep the temp files\n");
		return -1;
	}

	if (readfile(argv[1]) < 0) {
		printf("open file: %s error", argv[1]);
		return -2;
	}

	for (int i = 2; i < argc; i++){
		if (!strcmp(argv[i], "-p")){
			only_print = true;
		}
		else if (!strcmp(argv[i], "-k")){
			keep_tmp_files = true;
		}
	}

	get_config_path();

	load_codec_param();

	process_files("dest.ts");

	return 0;
}