-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmtn.c
2838 lines (2578 loc) · 105 KB
/
mtn.c
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
/* mtn - movie thumbnailer http://moviethumbnail.sourceforge.net/
Copyright (C) 2007-2008 tuit <tuitfun@yahoo.co.th>, et al.
based on "Using libavformat and libavcodec" by Martin Böhme:
http://www.inb.uni-luebeck.de/~boehme/using_libavcodec.html
http://www.inb.uni-luebeck.de/~boehme/libavcodec_update.html
and "An ffmpeg and SDL Tutorial":
http://www.dranger.com/ffmpeg/
and "Using GD with FFMPeg":
http://cvs.php.net/viewvc.cgi/gd/playground/ffmpeg/
and ffplay.c in ffmpeg
Copyright (c) 2003 Fabrice Bellard
http://ffmpeg.mplayerhq.hu/
and gd.c in libGD
http://cvs.php.net/viewvc.cgi/php-src/ext/gd/libgd/gd.c?revision=1.111&view=markup
please excuse the mess, i am a very rusty programmer!
helps, comments or patches are very welcomed. :)
tested with ffmpeg-r14005 and gd-2.0.34
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
//// enable unicode functions in mingw
//#ifdef WIN32
// #define UNICODE
// #define _UNICODE
//#endif
#include <assert.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <locale.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "mtn.h"
/* more global variables */
char *gb_version = "20121218a(j) copyright (c) 2007-2008 tuit, et al.";
time_t gb_st_start = 0; // start time of program
params parameters =
{
NULL,
GB_A_RATIO,
GB_B_BLANK,
GB_B_BEGIN, // skip this seconds from the beginning
GB_C_COLUMN,
GB_C_CUT, // cut movie; <=0 off
GB_D_EDGE, // edge detection; 0 off; >0 on
GB_E_EXT,
GB_E_END, // skip this seconds at the end
GB_F_FONTNAME,
COLOR_INFO, // info color
9, // info font size
GB_F_FONTNAME, // time stamp fontname
COLOR_WHITE, // time stamp color
COLOR_BLACK, // time stamp shadow color
8, // time stamp font size
GB_G_GAP,
GB_H_HEIGHT, // mininum height of each shot; will reduce # of column to meet this height
GB_I_INFO, // 1 on; 0 off
GB_I_INDIVIDUAL, // 1 on; 0 off
GB_J_QUALITY,
GB_K_BCOLOR, // background color
GB_L_INFO_LOCATION,
GB_L_TIME_LOCATION,
GB_N_NORMAL, // normal priority; 1 normal; 0 lower
GB_N_SUFFIX, // info text file suffix
GB_O_SUFFIX,
GB_O_OUTDIR,
GB_P_PAUSE, // pause before exiting; 1 pause; 0 dont pause
GB_P_DONTPAUSE, // dont pause; overide gb_p_pause
GB_Q_QUIET, // 1 on; 0 off
GB_R_ROW, // 0 = as many rows as needed
GB_S_STEP, // less than 0 = every frame; 0 = step evenly to get column x row
GB_T_TIME, // 1 on; 0 off
GB_T_TEXT,
GB_V_VERBOSE, // 1 on; 0 off
GB_V_VERBOSE, // 1 on; 0 off
GB_W_WIDTH, // 0 = column * movie width
GB_W_OVERWRITE, // 1 = overwrite; 0 = dont overwrite
GB_Z_SEEK, // always use seek mode; 1 on; 0 off
GB_Z_NONSEEK // always use non-seek mode; 1 on; 0 off
};
/* misc functions */
/* strrstr not in mingw
*/
char *strlaststr (char *haystack, char *needle)
{
// If needle is an empty string, the function returns haystack. -- from glibc doc
if (0 == strlen(needle)) {
return haystack;
}
char *start = haystack;
char *found = NULL;
char *prev = NULL;
while ((found = strstr(start, needle)) != NULL) {
prev = found;
start++;
}
return prev;
}
char *format_color(rgb_color col)
{
static char buf[7]; // FIXME
sprintf(buf, "%02X%02X%02X", col.r, col.g, col.b);
return buf; // FIXME
}
void format_time(double duration, char *str, char sep)
{
if (duration < 0) {
sprintf(str, "N/A");
} else {
int hours, mins, secs;
secs = duration;
mins = secs / 60;
secs %= 60;
hours = mins / 60;
mins %= 60;
sprintf(str, "%02d%c%02d%c%02d", hours, sep, mins, sep, secs);
}
}
char *format_size(int64_t size, char *unit)
{
static char buf[20]; // FIXME
if (size < 1024) {
sprintf(buf, "%"PRId64" %s", size, unit);
} else if (size < 1024*1024) {
sprintf(buf, "%.2f Ki%s", size/1024.0, unit);
} else if (size < 1024*1024*1024) {
sprintf(buf, "%.2f Mi%s", size/1024.0/1024, unit);
} else {
sprintf(buf, "%.2f Gi%s", size/1024.0/1024/1024, unit);
}
return buf;
}
/*
return only the file name of the full path
FIXME: wont work in unix if filename has '\\', e.g. path = "hello \\ world";
*/
char *path_2_file(char *path)
{
int len = strlen(path);
char *slash = strrchr(path, '/');
char *backslash = strrchr(path, '\\');
if (NULL != slash || NULL != backslash) {
char *last = (slash > backslash) ? slash : backslash;
if (last - path + 1 < len) { // make sure last char is not '/' or '\\'
return last + 1;
}
}
return path;
}
/*
copy n strings to dst
... must be char *
dst must be large enough
*/
char *strcpy_va(char *dst, int n, ...)
{
va_list ap;
int pos = 0;
dst[pos] = '\0';
va_start(ap, n);
int i;
for (i=0; i < n; i++) {
char *s = va_arg(ap, char *);
assert(NULL != s);
int len = strlen(s);
strncpy(dst + pos, s, len + 1); // for '\0'
pos += len;
}
va_end(ap);
return dst;
}
/*
return 1 if file is a regular file
return 0 if fail or is not
*/
int is_reg(char *file)
{
#if defined(WIN32) && defined(_UNICODE)
wchar_t file_w[FILENAME_MAX];
UTF8_2_WC(file_w, file, FILENAME_MAX);
#else
char *file_w = file;
#endif
struct _stat buf;
if (0 != _tstat(file_w, &buf)) {
return 0;
}
return S_ISREG(buf.st_mode);
}
/*
return 1 if file is a regular file and modified time >= st_time
return 0 if fail or is not
*/
int is_reg_newer(char *file, time_t st_time)
{
#if defined(WIN32) && defined(_UNICODE)
wchar_t file_w[FILENAME_MAX];
UTF8_2_WC(file_w, file, FILENAME_MAX);
#else
char *file_w = file;
#endif
struct _stat buf;
if (0 != _tstat(file_w, &buf)) {
return 0;
}
return S_ISREG(buf.st_mode) && (difftime(buf.st_mtime, st_time) >= 0);
}
/*
return 1 if file is a directory
return 0 if fail or is not a directory
FIXME: /c under msys is not a directory. why?
*/
int is_dir(char *file)
{
#if defined(WIN32) && defined(_UNICODE)
wchar_t file_w[FILENAME_MAX];
UTF8_2_WC(file_w, file, FILENAME_MAX);
#else
char *file_w = file;
#endif
struct _stat buf;
if (0 != _tstat(file_w, &buf)) {
return 0;
}
return S_ISDIR(buf.st_mode);
}
/*
*/
char *rem_trailing_slash(char *str)
{
#ifdef WIN32
// mingw doesn't seem to be happy about trailing '/' or '\\'
// strip trailing '/' or '\\' that might get added by shell filename completion for directories
int last_index = strlen(str) - 1;
// we need last '/' or '\\' for root drive "c:\"
while (last_index > 2 &&
('/' == str[last_index] || '\\' == str[last_index])) {
str[last_index--] = '\0';
}
#endif
return str;
}
/* mtn */
/*
return pointer to a new cropped image. the original one is freed.
if error, return original and the original stays intact
*/
gdImagePtr crop_image(gdImagePtr ip, int new_width, int new_height)
{
// cant find GD's crop, so we'll need to create a smaller image
gdImagePtr new_ip = gdImageCreateTrueColor(new_width, new_height);
if (NULL == new_ip) {
//return NULL;
// return the original should be better
return ip;
}
gdImageCopy(new_ip, ip, 0, 0, 0, 0, new_width, new_height);
gdImageDestroy(ip);
return new_ip;
}
/*
returns height, or 0 if error
*/
int image_string_height(char *text, char *font, double size)
{
int brect[8];
if (NULL == text || 0 == strlen(text)) {
return 0;
}
char *err = gdImageStringFT(NULL, &brect[0], 0, font, size, 0, 0, 0, text);
if (NULL != err) {
return 0;
}
return brect[3] - brect[7];
}
/*
position can be:
1: lower left
2: lower right
3: upper right
4: upper left
returns NULL if success, otherwise returns error message
*/
char *image_string(gdImagePtr ip, char *font, rgb_color color, double size, int position, int gap, char *text, int shadow, rgb_color shadow_color)
{
int brect[8];
int gd_color = gdImageColorResolve(ip, color.r, color.g, color.b);
char *err = gdImageStringFT(NULL, &brect[0], gd_color, font, size, 0, 0, 0, text);
if (NULL != err) {
return err;
}
/*
int width = brect[2] - brect[6];
int height = brect[3] - brect[7];
*/
int x, y;
switch (position)
{
case 1: // lower left
x = -brect[0] + gap;
y = gdImageSY(ip) - brect[1] - gap;
break;
case 2: // lower right
x = gdImageSX(ip) - brect[2] - gap;
y = gdImageSY(ip) - brect[3] - gap;
break;
case 3: // upper right
x = gdImageSX(ip) - brect[4] - gap;
y = -brect[5] + gap;
break;
case 4: // upper left
x = -brect[6] + gap;
y = -brect[7] + gap;
break;
default:
return "image_string's position can only be 1, 2, 3, or 4";
}
if (shadow) {
int shadowx, shadowy;
switch (position)
{
case 1: // lower left
shadowx = x+1;
shadowy = y;
y = y-1;
break;
case 2: // lower right
shadowx = x;
shadowy = y;
x = x-1;
y = y-1;
break;
case 3: // upper right
shadowx = x;
shadowy = y+1;
x = x-1;
break;
case 4: // upper left
shadowx = x+1;
shadowy = y+1;
break;
default:
return "image_string's position can only be 1, 2, 3, or 4";
}
int gd_shadow = gdImageColorResolve(ip, shadow_color.r, shadow_color.g, shadow_color.b);
err = gdImageStringFT(ip, &brect[0], gd_shadow, font, size, 0, shadowx, shadowy, text);
if (NULL != err) {
return err;
}
}
return gdImageStringFT(ip, &brect[0], gd_color, font, size, 0, x, y, text);
}
/*
return 0 if can save jpg
*/
int save_jpg(gdImagePtr ip, char *outname)
{
#if defined(WIN32) && defined(_UNICODE)
wchar_t outname_w[FILENAME_MAX];
UTF8_2_WC(outname_w, outname, FILENAME_MAX);
#else
char *outname_w = outname;
#endif
int done = -1;
FILE *fp = _tfopen(outname_w, _TEXT("wb"));
if (NULL == fp) {
goto cleanup;
}
errno = 0;
gdImageJpeg(ip, fp, parameters.gb_j_quality); /* how to check if write was successful? */
if (0 != errno) { // FIXME: valid check?
goto cleanup;
}
done = 0; // 0 = ok
cleanup:
if (NULL != fp && 0 != fclose(fp)) {
done = -1;
}
return done;
}
/*
pFrame must be a PIX_FMT_RGB24 frame
*/
void FrameRGB_2_gdImage(AVFrame *pFrame, gdImagePtr ip, int width, int height)
{
uint8_t *src = pFrame->data[0];
int x, y;
for (y = 0; y < height; y++) {
for (x = 0; x < width * 3; x += 3) {
gdImageSetPixel(ip, x / 3, y, gdImageColorResolve(ip, src[x], src[x + 1], src[x + 2]));
//gdImageSetPixel(ip, x/3, y, gdTrueColor(src[x], src[x+1], src[x+2]));
}
src += width * 3;
}
}
/*
*/
void shot_new(shot *psh)
{
psh->ip = NULL;
psh->eff_target = AV_NOPTS_VALUE;
psh->found_pts = AV_NOPTS_VALUE;
psh->blank = 0;
int i;
for (i=0; i<EDGE_PARTS; i++) {
psh->edge[i] = 1;
}
}
/* initialize
*/
void thumb_new(thumbnail *ptn)
{
ptn->out_ip = NULL;
ptn->out_filename[0] = '\0';
ptn->info_filename[0] = '\0';
ptn->out_saved = 0;
ptn->width = ptn->height = 0;
ptn->txt_height = 0;
ptn->column = ptn->row = 0;
ptn->step = 0;
ptn->shot_width = ptn->shot_height = 0;
ptn->center_gap = 0;
ptn->idx = -1;
// dynamic
ptn->ppts = NULL;
}
/*
alloc dynamic data; must be called after all required static data is filled in
return -1 if failed
*/
int thumb_alloc_dynamic(thumbnail *ptn)
{
ptn->ppts = malloc(ptn->column * ptn->row * sizeof(*(ptn->ppts)));
if (NULL == ptn->ppts) {
return -1;
}
return 0;
}
void thumb_cleanup_dynamic(thumbnail *ptn)
{
if (NULL != ptn->ppts) {
free(ptn->ppts);
ptn->ppts = NULL;
}
}
/*
add shot
because ptn->idx is the last index, this function assumes that shots will be added
in increasing order.
*/
void thumb_add_shot(thumbnail *ptn, gdImagePtr ip, int idx, int64_t pts)
{
int dstX = idx%ptn->column * (ptn->shot_width+parameters.gb_g_gap) + parameters.gb_g_gap + ptn->center_gap;
int dstY = idx/ptn->column * (ptn->shot_height+parameters.gb_g_gap) + parameters.gb_g_gap
+ ((3 == parameters.gb_L_info_location || 4 == parameters.gb_L_info_location) ? ptn->txt_height : 0);
gdImageCopy(ptn->out_ip, ip, dstX, dstY, 0, 0, ptn->shot_width, ptn->shot_height);
ptn->idx = idx;
ptn->ppts[idx] = pts;
}
#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#ifndef MAX
#define MAX(a,b) ((a)<(b)?(b):(a))
#endif
/*
perform convolution on pFrame and store result in ip
pFrame must be a PIX_FMT_RGB24 frame
ip must be of the same size as pFrame
begin = upper left, end = lower right
filter should be a 2-dimensional but since we cant pass it without knowning the size, we'll use 1 dimension
modified from:
http://cvs.php.net/viewvc.cgi/php-src/ext/gd/libgd/gd.c?revision=1.111&view=markup
*/
void FrameRGB_convolution(AVFrame *pFrame, int width, int height,
float *filter, int filter_size, float filter_div, float offset,
gdImagePtr ip, int xbegin, int ybegin, int xend, int yend)
{
int x, y, i, j;
float new_r, new_g, new_b;
uint8_t *src = pFrame->data[0];
for (y=ybegin; y<=yend; y++) {
for(x=xbegin; x<=xend; x++) {
new_r = new_g = new_b = 0;
//float grey = 0;
for (j=0; j<filter_size; j++) {
int yv = MIN(MAX(y - filter_size/2 + j, 0), height - 1);
for (i=0; i<filter_size; i++) {
int xv = MIN(MAX(x - filter_size/2 + i, 0), width - 1);
int pos = yv*width*3 + xv*3;
new_r += src[pos] * filter[j * filter_size + i];
new_g += src[pos+1] * filter[j * filter_size + i];
new_b += src[pos+2] * filter[j * filter_size + i];
//grey += (src[pos] + src[pos+1] + src[pos+2])/3 * filter[j * filter_size + i];
}
}
new_r = (new_r/filter_div)+offset;
new_g = (new_g/filter_div)+offset;
new_b = (new_b/filter_div)+offset;
//grey = (grey/filter_div)+offset;
new_r = (new_r > 255.0f)? 255.0f : ((new_r < 0.0f)? 0.0f:new_r);
new_g = (new_g > 255.0f)? 255.0f : ((new_g < 0.0f)? 0.0f:new_g);
new_b = (new_b > 255.0f)? 255.0f : ((new_b < 0.0f)? 0.0f:new_b);
//grey = (grey > 255.0f)? 255.0f : ((grey < 0.0f)? 0.0f:grey);
gdImageSetPixel(ip, x, y, gdImageColorResolve(ip, (int)new_r, (int)new_g, (int)new_b));
//gdImageSetPixel(ip, x, y, gdTrueColor((int)new_r, (int)new_g, (int)new_b));
//gdImageSetPixel(ip, x, y, gdTrueColor((int)grey, (int)grey, (int)grey));
}
}
}
/* begin = upper left, end = lower right
*/
float cmp_edge(gdImagePtr ip, int xbegin, int ybegin, int xend, int yend)
{
#define CMP_EDGE 208
int count = 0;
int i, j;
for (j = ybegin; j <= yend; j++) {
for (i = xbegin; i <= xend; i++) {
int pixel = gdImageGetPixel(ip, i, j);
if (gdImageRed(ip, pixel) >= CMP_EDGE
&& gdImageGreen(ip, pixel) >= CMP_EDGE
&& gdImageBlue(ip, pixel) >= CMP_EDGE) {
count++;
}
}
}
return (float)count / (yend - ybegin + 1) / (xend - xbegin + 1);
}
int is_edge(float *edge, float edge_found)
{
if (parameters.gb_V) { // DEBUG
return 1;
}
int count = 0;
int i;
for (i = 0; i < EDGE_PARTS; i++) {
if (edge[i] >= edge_found) {
count++;
}
}
if (count >= 2) {
return count;
}
return 0;
}
/*
pFrame must be an PIX_FMT_RGB24 frame
http://student.kuleuven.be/~m0216922/CG/
http://www.pages.drexel.edu/~weg22/edge.html
http://student.kuleuven.be/~m0216922/CG/filtering.html
http://cvs.php.net/viewvc.cgi/php-src/ext/gd/libgd/gd.c?revision=1.111&view=markup
*/
gdImagePtr detect_edge(AVFrame *pFrame, int width, int height, float *edge, float edge_found)
{
static float filter[] = {
0,-1, 0,
-1, 4,-1,
0,-1, 0
};
#define FILTER_SIZE 3 // 3x3
#define FILTER_DIV 1
#define OFFSET 128
static int init_filter = 0; // FIXME
if (0 == init_filter) {
init_filter = 1;
filter[1] = -parameters.gb_D_edge/4.0f;
filter[3] = -parameters.gb_D_edge/4.0f;
filter[4] = parameters.gb_D_edge;
filter[5] = -parameters.gb_D_edge/4.0f;
filter[7] = -parameters.gb_D_edge/4.0f;
}
gdImagePtr ip = gdImageCreateTrueColor(width, height);
if (NULL == ip) {
av_log(NULL, AV_LOG_ERROR, " gdImageCreateTrueColor failed\n");
return NULL;
}
if (parameters.gb_v_verbose > 0) {
FrameRGB_2_gdImage(pFrame, ip, width, height);
}
int i;
for (i = 0; i < EDGE_PARTS; i++) {
edge[i] = 1;
}
// check 6 parts to speed this up & to improve correctness
int y_size = height/10;
int ya = y_size*2;
int yb = y_size*4;
int yc = y_size*6;
int x_crop = width/8;
// only find edge if neccessary
int parts[EDGE_PARTS][4] = {
//xbegin, ybegin, xend, yend
{x_crop, ya, width/2, ya+y_size},
{width/2+1, ya+y_size, width-x_crop, ya+2*y_size},
{x_crop, yb, width/2, yb+y_size},
{width/2+1, yb+y_size, width-x_crop, yb+2*y_size},
{x_crop, yc, width/2, yc+y_size},
{width/2+1, yc+y_size, width-x_crop, yc+2*y_size},
};
int count = 0;
for (i = 0; i < EDGE_PARTS && count < 2; i++) {
FrameRGB_convolution(pFrame, width, height, filter, FILTER_SIZE, FILTER_DIV, OFFSET,
ip, parts[i][0], parts[i][1], parts[i][2], parts[i][3]);
edge[i] = cmp_edge(ip, parts[i][0], parts[i][1], parts[i][2], parts[i][3]);
if (edge[i] >= edge_found) {
count++;
}
}
return ip;
}
/* for debuging */
void save_AVFrame(AVFrame *pFrame, int src_width, int src_height, int pix_fmt,
char *filename, int dst_width, int dst_height)
{
AVFrame *pFrameRGB = NULL;
uint8_t *rgb_buffer = NULL;
struct SwsContext *pSwsCtx = NULL;
gdImagePtr ip = NULL;
pFrameRGB = avcodec_alloc_frame();
if (pFrameRGB == NULL) {
av_log(NULL, AV_LOG_ERROR, " couldn't allocate a video frame\n");
goto cleanup;
}
int rgb_bufsize = avpicture_get_size(PIX_FMT_RGB24, dst_width, dst_height);
rgb_buffer = av_malloc(rgb_bufsize);
if (NULL == rgb_buffer) {
av_log(NULL, AV_LOG_ERROR, " av_malloc %d bytes failed\n", rgb_bufsize);
goto cleanup;
}
avpicture_fill((AVPicture *) pFrameRGB, rgb_buffer, PIX_FMT_RGB24, dst_width, dst_height);
pSwsCtx = sws_getContext(src_width, src_height, pix_fmt,
dst_width, dst_height, PIX_FMT_RGB24, SWS_BILINEAR, NULL, NULL, NULL);
if (NULL == pSwsCtx) { // sws_getContext is not documented
av_log(NULL, AV_LOG_ERROR, " sws_getContext failed\n");
goto cleanup;
}
sws_scale(pSwsCtx, (const uint8_t * const *)pFrame->data, pFrame->linesize, 0, src_height,
pFrameRGB->data, pFrameRGB->linesize);
ip = gdImageCreateTrueColor(dst_width, dst_height);
if (NULL == ip) {
av_log(NULL, AV_LOG_ERROR, " gdImageCreateTrueColor failed: width %d, height %d\n", dst_width, dst_height);
goto cleanup;
}
FrameRGB_2_gdImage(pFrameRGB, ip, dst_width, dst_height);
int ret = save_jpg(ip, filename);
if (0 != ret) {
av_log(NULL, AV_LOG_ERROR, " save_jpg failed: %s\n", filename);
goto cleanup;
}
cleanup:
if (NULL != ip)
gdImageDestroy(ip);
if (NULL != pSwsCtx)
sws_freeContext(pSwsCtx); // do we need to do this?
if (NULL != rgb_buffer)
av_free(rgb_buffer);
if (NULL != pFrameRGB)
av_free(pFrameRGB);
}
/* av_pkt_dump_log()?? */
void dump_packet(AVPacket *p, AVStream * ps)
{
/* from av_read_frame()
pkt->pts, pkt->dts and pkt->duration are always set to correct values in
AVStream.timebase units (and guessed if the format cannot provided them).
pkt->pts can be AV_NOPTS_VALUE if the video format has B frames, so it is
better to rely on pkt->dts if you do not decompress the payload.
*/
av_log(NULL, AV_LOG_VERBOSE, "***dump_packet: pos:%"PRId64"\n", p->pos);
av_log(NULL, AV_LOG_VERBOSE, "pts tb: %"PRId64", dts tb: %"PRId64", duration tb: %d\n",
p->pts, p->dts, p->duration);
av_log(NULL, AV_LOG_VERBOSE, "pts s: %.2f, dts s: %.2f, duration s: %.2f\n",
p->pts * av_q2d(ps->time_base), p->dts * av_q2d(ps->time_base),
p->duration * av_q2d(ps->time_base)); // pts can be AV_NOPTS_VALUE
}
void dump_codec_context(AVCodecContext * p)
{
av_log(NULL, AV_LOG_VERBOSE, "***dump_codec_context %s, time_base: %d / %d\n", p->codec_name,
p->time_base.num, p->time_base.den);
av_log(NULL, AV_LOG_VERBOSE, "frame_number: %d, width: %d, height: %d, sample_aspect_ratio %d/%d%s\n",
p->frame_number, p->width, p->height, p->sample_aspect_ratio.num, p->sample_aspect_ratio.den,
(0 == p->sample_aspect_ratio.num) ? "" : "**a**");
}
void dump_index_entries(AVStream * p)
{
// index_entries are only used if the format does not support seeking natively
int i;
double diff = 0;
for (i=0; i < p->nb_index_entries; i++) {
AVIndexEntry *e = p->index_entries + i;
double prev_ts = 0, cur_ts = 0;
cur_ts = e->timestamp * av_q2d(p->time_base);
//assert(cur_ts > 0);
diff += cur_ts - prev_ts;
if (i < 20) { // show only first 20
av_log(NULL, AV_LOG_VERBOSE, " i: %d, pos: %"PRId64", timestamp tb: %"PRId64", timestamp s: %.2f, flags: %d, size: %d, min_distance: %d\n",
i, e->pos, e->timestamp, e->timestamp * av_q2d(p->time_base), e->flags, e->size, e->min_distance);
}
prev_ts = cur_ts;
}
av_log(NULL, AV_LOG_VERBOSE, " *** nb_index_entries: %d, avg. timestamp s diff: %.2f\n", p->nb_index_entries, diff / p->nb_index_entries);
}
void dump_stream(AVStream * p)
{
av_log(NULL, AV_LOG_VERBOSE, "***dump_stream, time_base: %d / %d\n",
p->time_base.num, p->time_base.den);
av_log(NULL, AV_LOG_VERBOSE, "cur_dts tb?: %"PRId64", start_time tb: %"PRId64", duration tb: %"PRId64", nb_frames: %"PRId64"\n",
p->cur_dts, p->start_time, p->duration, p->nb_frames);
// get funny results here. use format_context's.
av_log(NULL, AV_LOG_VERBOSE, "cur_dts s?: %.2f, start_time s: %.2f, duration s: %.2f\n",
p->cur_dts * av_q2d(p->time_base), p->start_time * av_q2d(p->time_base),
p->duration * av_q2d(p->time_base)); // duration can be AV_NOPTS_VALUE
// field pts in AVStream is for encoding
}
/*
set scale source width & height (scaled_w and scaled_h)
*/
void calc_scale_src(int width, int height, AVRational ratio, int *scaled_w, int *scaled_h)
{
// mplayer dont downscale horizontally. however, we'll always scale
// horizontally, up or down, which is the same as mpc's display and
// vlc's snapshot. this should make square pixel for both pal & ntsc.
*scaled_w = width;
*scaled_h = height;
if (0 != ratio.num) { // ratio is defined
assert(ratio.den != 0);
*scaled_w = av_q2d(ratio) * width + 0.5; // round nearest
}
}
/*
modified from libavformat's dump_format
*/
void get_stream_info_type(AVFormatContext *ic, enum AVMediaType type, char *buf, AVRational sample_aspect_ratio)
{
char sub_buf[1024] = ""; // FIXME
unsigned int i;
for(i=0; i<ic->nb_streams; i++) {
char codec_buf[256];
int flags = ic->iformat->flags;
AVStream *st = ic->streams[i];
AVDictionaryEntry *language = av_dict_get(ic->metadata, "language", NULL, 0);
if (type != st->codec->codec_type) {
continue;
}
if (AVMEDIA_TYPE_SUBTITLE == st->codec->codec_type) {
if (language != NULL) {
sprintf(sub_buf + strlen(sub_buf), "%s ", language->value);
} else {
// FIXME: ignore for now; language seem to be missing in .vob files
//sprintf(sub_buf + strlen(sub_buf), "? ");
}
continue;
}
if (parameters.gb_v_verbose > 0) {
sprintf(buf + strlen(buf), "Stream %d", i);
if (flags & AVFMT_SHOW_IDS) {
sprintf(buf + strlen(buf), "[0x%x]", st->id);
}
/*
int g = ff_gcd(st->time_base.num, st->time_base.den);
sprintf(buf + strlen(buf), ", %d/%d", st->time_base.num/g, st->time_base.den/g);
*/
sprintf(buf + strlen(buf), ": ");
}
avcodec_string(codec_buf, sizeof(codec_buf), st->codec, 0);
// remove [PAR DAR] from string, it's not very useful.
char *begin = NULL, *end = NULL;
if ((begin=strstr(codec_buf, " [PAR")) != NULL
&& (end=strchr(begin, ']')) != NULL) {
while (*++end != '\0') {
*begin++ = *end;
}
*begin = '\0';
}
sprintf(buf + strlen(buf), codec_buf);
if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
if (st->r_frame_rate.den && st->r_frame_rate.num)
sprintf(buf + strlen(buf), ", %5.2f fps(r)", av_q2d(st->r_frame_rate));
//else if(st->time_base.den && st->time_base.num)
// sprintf(buf + strlen(buf), ", %5.2f fps(m)", 1/av_q2d(st->time_base));
else
sprintf(buf + strlen(buf), ", %5.2f fps(c)", 1/av_q2d(st->codec->time_base));
// show aspect ratio
int scaled_src_width, scaled_src_height;
calc_scale_src(st->codec->width, st->codec->height, sample_aspect_ratio,
&scaled_src_width, &scaled_src_height);
if (scaled_src_width != st->codec->width || scaled_src_height != st->codec->height) {
sprintf(buf + strlen(buf), " => %dx%d", scaled_src_width, scaled_src_height);
}
}
if (language != NULL) {
sprintf(buf + strlen(buf), " (%s)", language->value);
}
sprintf(buf + strlen(buf), NEWLINE);
}
if (0 < strlen(sub_buf)) {
sprintf(buf + strlen(buf), "Subtitles: %s\n", sub_buf);
}
}
/*
modified from libavformat's dump_format
*/
char *get_stream_info(AVFormatContext *ic, char *url, int strip_path, AVRational sample_aspect_ratio)
{
static char buf[4096]; // FIXME: this is also used for all text at the top
int duration = -1;
char *file_name = url;
if (1 == strip_path) {
file_name = path_2_file(url);
}
sprintf(buf, "File: %s", file_name);
//sprintf(buf + strlen(buf), " (%s)", ic->iformat->name);
sprintf(buf + strlen(buf), "%sSize: %"PRId64" bytes (%s)", NEWLINE, avio_size(ic->pb), format_size(avio_size(ic->pb), "B"));
if (ic->duration != AV_NOPTS_VALUE) { // FIXME: gcc warning: comparison between signed and unsigned
int hours, mins, secs;
duration = secs = ic->duration / AV_TIME_BASE;
mins = secs / 60;
secs %= 60;
hours = mins / 60;
mins %= 60;
sprintf(buf + strlen(buf), ", duration: %02d:%02d:%02d", hours, mins, secs);
} else {
sprintf(buf + strlen(buf), ", duration: N/A");
}
/*
if (ic->start_time != AV_NOPTS_VALUE) {
int secs, us;
secs = ic->start_time / AV_TIME_BASE;
us = ic->start_time % AV_TIME_BASE;
sprintf(buf + strlen(buf), ", start: %d.%06d", secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
}
*/
// some formats, eg. flv, dont seem to support bit_rate, so we'll prefer to
// calculate from duration.
// is this ok? probably not ok with .vob files when duration is wrong. DEBUG
if (duration > 0) {
sprintf(buf + strlen(buf), ", avg.bitrate: %.0f kb/s%s", (double) avio_size(ic->pb) * 8 / duration / 1000, NEWLINE);
} else if (ic->bit_rate) {
sprintf(buf + strlen(buf), ", bitrate: %d kb/s%s", ic->bit_rate / 1000, NEWLINE);
} else {
sprintf(buf + strlen(buf), ", bitrate: N/A%s", NEWLINE);
}
get_stream_info_type(ic, AVMEDIA_TYPE_AUDIO, buf, sample_aspect_ratio);
get_stream_info_type(ic, AVMEDIA_TYPE_VIDEO, buf, sample_aspect_ratio);
get_stream_info_type(ic, AVMEDIA_TYPE_SUBTITLE, buf, sample_aspect_ratio);
// CODEC_TYPE_DATA FIXME: what is this type?
// CODEC_TYPE_NB FIXME: what is this type?
//strfmon(buf + strlen(buf), 100, "strfmon: %!i\n", avio_size(ic->pb));
return buf;
}
void dump_format_context(AVFormatContext *p, int __attribute__((unused)) index, char *url, int __attribute__((unused)) is_output)
{
//av_log(NULL, AV_LOG_ERROR, "\n");
av_log(NULL, AV_LOG_VERBOSE, "***dump_format_context, name: %s, long_name: %s\n",
p->iformat->name, p->iformat->long_name);
//dump_format(p, index, url, is_output);
// dont show scaling info at this time because we dont have the proper sample_aspect_ratio
av_log(NULL, LOG_INFO, get_stream_info(p, url, 0, GB_A_RATIO));
av_log(NULL, AV_LOG_VERBOSE, "start_time av: %"PRId64", duration av: %"PRId64", file_size: %"PRId64"\n",
p->start_time, p->duration, avio_size(p->pb));
av_log(NULL, AV_LOG_VERBOSE, "start_time s: %.2f, duration s: %.2f\n",
(double) p->start_time / AV_TIME_BASE, (double) p->duration / AV_TIME_BASE);
AVDictionaryEntry* track = av_dict_get(p->metadata, "track", NULL, 0);
AVDictionaryEntry* title = av_dict_get(p->metadata, "title", NULL, 0);
AVDictionaryEntry* author = av_dict_get(p->metadata, "author", NULL, 0);
AVDictionaryEntry* copyright = av_dict_get(p->metadata, "copyright", NULL, 0);
AVDictionaryEntry* comment = av_dict_get(p->metadata, "comment", NULL, 0);
AVDictionaryEntry* album = av_dict_get(p->metadata, "album", NULL, 0);
AVDictionaryEntry* year = av_dict_get(p->metadata, "year", NULL, 0);
AVDictionaryEntry* genre = av_dict_get(p->metadata, "genre", NULL, 0);
if (track != NULL)
av_log(NULL, LOG_INFO, " Track: %s\n", track->value);
if (title != NULL)
av_log(NULL, LOG_INFO, " Title: %s\n", title->value);
if (author != NULL)
av_log(NULL, LOG_INFO, " Author: %s\n", author->value);
if (copyright != NULL)
av_log(NULL, LOG_INFO, " Copyright: %s\n", copyright->value);
if (comment != NULL)
av_log(NULL, LOG_INFO, " Comment: %s\n", comment->value);
if (album != NULL)
av_log(NULL, LOG_INFO, " Album: %s\n", album->value);
if (year != NULL)
av_log(NULL, LOG_INFO, " Year: %s\n", year->value);
if (genre != NULL)
av_log(NULL, LOG_INFO, " Genre: %s\n", genre->value);
}
/*
*/