forked from dickontoo/omxtx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
omxtx.c
1472 lines (1279 loc) · 39.1 KB
/
omxtx.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
/* omxtx.c
*
* (c) 2012 Dickon Hood <[email protected]>
*
* A trivial OpenMAX transcoder for the Pi.
*
* Very much a work-in-progress, and as such is noisy, doesn't produce
* particularly pretty output, and is probably buggier than a swamp in
* summer. Beware of memory leaks.
*
* Usage: ./omxtx [-b bitrate] [-r size] input.foo output.m4v
*
* 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.
*/
/* To do:
*
* * Flush the buffers at the end
* * Sort out the PTSes
* * Read up on buffer timings in general
* * Feed the packets to AVFormat rather than dumping them raw to disc
* * Interleave correctly with the other AV packets in the stream, rather
* than just dropping them entirely
*/
#define _BSD_SOURCE
#define FF_API_CODEC_ID 1
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "bcm_host.h"
#include "libavformat/avformat.h"
#include "libavutil/avutil.h"
#include "libavcodec/avcodec.h"
#include "libavutil/mathematics.h"
#include <error.h>
#include "OMX_Video.h"
#include "OMX_Types.h"
#include "OMX_Component.h"
#include "OMX_Core.h"
#include "OMX_Broadcom.h"
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
#include <unistd.h>
static OMX_VERSIONTYPE SpecificationVersion = {
.s.nVersionMajor = 1,
.s.nVersionMinor = 1,
.s.nRevision = 2,
.s.nStep = 0
};
/* Hateful things: */
#define MAKEME(y, x) do { \
y = calloc(1, sizeof(x)); \
y->nSize = sizeof(x); \
y->nVersion = SpecificationVersion; \
} while (0)
#define OERR(cmd) do { \
OMX_ERRORTYPE oerr = cmd; \
if (oerr != OMX_ErrorNone) { \
fprintf(stderr, #cmd \
" failed on line %d: %x\n", \
__LINE__, oerr); \
exit(1); \
} else { \
fprintf(stderr, #cmd \
" completed OK.\n"); \
} \
} while (0)
#define OERRq(cmd) do { oerr = cmd; \
if (oerr != OMX_ErrorNone) { \
fprintf(stderr, #cmd \
" failed: %x\n", oerr); \
exit(1); \
} \
} while (0)
/* ... but damn useful.*/
/* Hardware component names: */
#define ENCNAME "OMX.broadcom.video_encode"
#define DECNAME "OMX.broadcom.video_decode"
#define RSZNAME "OMX.broadcom.resize"
#define VIDNAME "OMX.broadcom.video_render"
#define SPLNAME "OMX.broadcom.video_splitter"
/* portbase for the modules, could also be queried, but as the components are broadcom/raspberry
specific anyway... */
#define PORT_RSZ 60
#define PORT_VID 90
#define PORT_DEC 130
#define PORT_ENC 200
#define PORT_SPL 250
enum states {
DECINIT,
DECTUNNELSETUP,
DECRUNNING,
DECFLUSH,
DECDONE,
DECFAILED,
ENCPREINIT,
ENCINIT,
ENCGOTBUF,
ENCDONE,
};
static struct context {
AVFormatContext *ic;
AVFormatContext *oc;
int nextin;
int nextout;
int incount;
int outcount;
volatile int fps;
volatile int framecount;
int done;
volatile int flags;
OMX_BUFFERHEADERTYPE *encbufs, *bufhead;
volatile enum states decstate;
volatile enum states encstate;
int vidindex;
OMX_HANDLETYPE dec, enc, rsz, spl, vid;
pthread_mutex_t lock;
AVBitStreamFilterContext *bsfc;
int bitrate;
char *resize;
char *oname;
double frameduration;
} ctx;
#define FLAGS_VERBOSE (1<<0)
#define FLAGS_DECEMPTIEDBUF (1<<1)
#define FLAGS_MONITOR (1<<2)
static OMX_BUFFERHEADERTYPE *allocbufs(OMX_HANDLETYPE h, int port, int enable);
/* Print some useful information about the state of the port: */
static void dumpport(OMX_HANDLETYPE handle, int port)
{
OMX_VIDEO_PORTDEFINITIONTYPE *viddef;
OMX_PARAM_PORTDEFINITIONTYPE *portdef;
MAKEME(portdef, OMX_PARAM_PORTDEFINITIONTYPE);
portdef->nPortIndex = port;
OERR(OMX_GetParameter(handle, OMX_IndexParamPortDefinition, portdef));
printf("Port %d is %s, %s\n", portdef->nPortIndex,
(portdef->eDir == 0 ? "input" : "output"),
(portdef->bEnabled == 0 ? "disabled" : "enabled"));
printf("Wants %d bufs, needs %d, size %d, enabled: %d, pop: %d, "
"aligned %d\n", portdef->nBufferCountActual,
portdef->nBufferCountMin, portdef->nBufferSize,
portdef->bEnabled, portdef->bPopulated,
portdef->nBufferAlignment);
viddef = &portdef->format.video;
switch (portdef->eDomain) {
case OMX_PortDomainVideo:
printf("Video type is currently:\n"
"\tMIME:\t\t%s\tNative:\t\t%p\n"
"\tWidth:\t\t%d\tHeight:\t\t%d\n"
"\tStride:\t\t%d\tSliceHeight:\t%d\n"
"\tBitrate:\t%d\tFramerate:\t%d (%x); (%f)\n"
"\tError hiding:\t%d\n"
"\tCodec:\t\t%d\tColour:\t\t%d\n",
viddef->cMIMEType, viddef->pNativeRender,
viddef->nFrameWidth, viddef->nFrameHeight,
viddef->nStride, viddef->nSliceHeight,
viddef->nBitrate,
viddef->xFramerate, viddef->xFramerate,
((float)viddef->xFramerate/(float)65536),
viddef->bFlagErrorConcealment,
viddef->eCompressionFormat, viddef->eColorFormat);
break;
case OMX_PortDomainImage:
printf("Image type is currently:\n"
"\tMIME:\t\t%s\tNative:\t\t%p\n"
"\tWidth:\t\t%d\tHeight:\t\t%d\n"
"\tStride:\t\t%d\tSliceHeight:\t%d\n"
"\tError hiding:\t%d\n"
"\tCodec:\t\t%d\tColour:\t\t%d\n",
portdef->format.image.cMIMEType,
portdef->format.image.pNativeRender,
portdef->format.image.nFrameWidth,
portdef->format.image.nFrameHeight,
portdef->format.image.nStride,
portdef->format.image.nSliceHeight,
portdef->format.image.bFlagErrorConcealment,
portdef->format.image.eCompressionFormat,
portdef->format.image.eColorFormat);
break;
/* Feel free to add others. */
default:
break;
}
free(portdef);
}
static int mapcodec(enum CodecID id)
{
printf("Mapping codec ID %d (%x)\n", id, id);
switch (id) {
case CODEC_ID_MPEG2VIDEO:
case CODEC_ID_MPEG2VIDEO_XVMC:
return OMX_VIDEO_CodingMPEG2;
case CODEC_ID_H264:
return OMX_VIDEO_CodingAVC;
case 13:
return OMX_VIDEO_CodingMPEG4;
default:
return -1;
}
return -1;
}
static const char *mapstate(OMX_STATETYPE state) {
switch (state) {
case OMX_StateLoaded:
return "loaded";
case OMX_StateIdle:
return "idle";
case OMX_StateExecuting:
return "executing";
case OMX_StatePause:
return "paused";
case OMX_StateWaitForResources:
return "waiting for resources";
default:
return "unknown???";
}
}
static void dumpportstate(void)
{
enum OMX_STATETYPE state;
printf("\n\nIn exit handler, after %d frames:\n", ctx.framecount);
dumpport(ctx.dec, PORT_DEC);
dumpport(ctx.dec, PORT_DEC+1);
dumpport(ctx.enc, PORT_ENC);
dumpport(ctx.enc, PORT_ENC+1);
OMX_GetState(ctx.dec, &state);
printf("Decoder state: %d (%s)\n", state, mapstate(state));
OMX_GetState(ctx.enc, &state);
printf("Encoder state: %d (%s)\n", state, mapstate(state));
}
static const char *mapcomponent(struct context *ctx, OMX_HANDLETYPE h)
{
if (h == ctx->dec)
return "Decoder";
if (h == ctx->enc)
return "Encoder";
if (h == ctx->rsz)
return "Resizer";
if (h == ctx->spl)
return "Splitter";
if (h == ctx->vid)
return "Video Render";
return "Unknown!";
}
static AVFormatContext *makeoutputcontext(AVFormatContext *ic,
const char *oname, int idx, const OMX_PARAM_PORTDEFINITIONTYPE *prt,
AVPacket **ifb)
{
AVFormatContext *oc;
AVOutputFormat *fmt;
int i;
AVStream *iflow, *oflow;
AVCodec *c;
AVCodecContext *cc;
const OMX_VIDEO_PORTDEFINITIONTYPE *viddef;
int r;
char err[256];
viddef = &prt->format.video;
fmt = av_guess_format(NULL, oname, NULL);
if (!fmt) {
fprintf(stderr, "Can't guess format for %s; defaulting to "
"MPEG\n",
oname);
fmt = av_guess_format(NULL, "MPEG", NULL);
}
if (!fmt) {
fprintf(stderr, "Failed even that. Bye bye.\n");
exit(1);
}
oc = avformat_alloc_context();
if (!oc) {
fprintf(stderr, "Failed to alloc outputcontext\n");
exit(1);
}
oc->oformat = fmt;
snprintf(oc->filename, sizeof(oc->filename), "%s", oname);
oc->debug = 1;
oc->start_time_realtime = ic->start_time_realtime;
oc->start_time = ic->start_time;
#define ETB(x) x.num, x.den
for (i = 0; i < ic->nb_streams; i++) {
iflow = ic->streams[i];
if (i == idx) { /* My new H.264 stream. */
c = avcodec_find_encoder(CODEC_ID_H264);
printf("Found a codec at %p\n", c);
oflow = avformat_new_stream(oc, c);
printf("Defaults: output stream: %d/%d, input stream: %d/%d, input codec: %d/%d, output codec: %d/%d, output framerate: %d/%d, input framerate: %d/%d, ticks: %d; %d %lld/%lld\n", ETB(oflow->time_base), ETB(iflow->time_base), ETB(iflow->codec->time_base), ETB(oflow->codec->time_base), ETB(oflow->r_frame_rate), ETB(iflow->r_frame_rate), oflow->codec->ticks_per_frame, iflow->codec->ticks_per_frame, oc->start_time_realtime, ic->start_time_realtime);
cc = oflow->codec;
cc->width = viddef->nFrameWidth;
cc->height = viddef->nFrameHeight;
cc->time_base = iflow->codec->time_base;
cc->codec_id = CODEC_ID_H264;
cc->codec_type = AVMEDIA_TYPE_VIDEO;
cc->max_b_frames = 12; /* Probably wrong */
cc->has_b_frames = 1;
cc->gop_size = 200;
cc->pix_fmt = PIX_FMT_YUV420P;
cc->bit_rate = ctx.bitrate;
cc->profile = FF_PROFILE_H264_HIGH;
cc->level = 41;
oflow->avg_frame_rate = iflow->avg_frame_rate;
oflow->r_frame_rate = iflow->r_frame_rate;
oflow->time_base = iflow->time_base;
cc->flags = CODEC_FLAG2_LOCAL_HEADER;
oflow->start_time = iflow->start_time;
printf("Defaults: output stream: %d/%d, input stream: %d/%d, input codec: %d/%d, output codec: %d/%d, output framerate: %d/%d, input framerate: %d/%d\n", ETB(oflow->time_base), ETB(iflow->time_base), ETB(iflow->codec->time_base), ETB(oflow->codec->time_base), ETB(oflow->r_frame_rate), ETB(iflow->r_frame_rate));
printf("Time base: %d/%d, fps %d/%d\n", oflow->time_base.num, oflow->time_base.den, oflow->r_frame_rate.num, oflow->r_frame_rate.den);
// oflow->sample_aspect_ratio = iflow->sample_aspect_ratio;
} else { /* Something pre-existing. */
c = avcodec_find_encoder(iflow->codec->codec_id);
oflow = avformat_new_stream(oc, c);
avcodec_copy_context(oflow->codec, iflow->codec);
}
}
for (i = 0; i < oc->nb_streams; i++) {
if (oc->oformat->flags & AVFMT_GLOBALHEADER)
oc->streams[i]->codec->flags
|= CODEC_FLAG_GLOBAL_HEADER;
if (oc->streams[i]->codec->sample_rate == 0)
oc->streams[i]->codec->sample_rate = 48000; /* ish */
}
printf("\n\n\nOutput:\n");
av_dump_format(oc, 0, oname, 1);
/* At some point they changed the API: */
#ifndef URL_WRONLY
#define URL_WRONLY AVIO_FLAG_WRITE
#endif
avio_open(&oc->pb, oname, URL_WRONLY);
r = avformat_write_header(oc, NULL);
if (r < 0) {
av_strerror(r, err, sizeof(err));
printf("Failed to write header: %s\n", err);
exit(1);
}
printf("Writing initial frame buffer contents out...");
for (i = 0; ifb[i]; i++) {
AVPacket *rp;
int index;
rp = ifb[i];
index = rp->stream_index;
if (rp->pts != AV_NOPTS_VALUE)
rp->pts = av_rescale_q(rp->pts,
ic->streams[index]->time_base,
oc->streams[index]->time_base);
if (rp->dts != AV_NOPTS_VALUE)
rp->dts = av_rescale_q(rp->dts,
ic->streams[index]->time_base,
oc->streams[index]->time_base);
av_interleaved_write_frame(oc, rp);
}
printf(" ...done. Wrote %d frames.\n\n", i);
return oc;
}
OMX_ERRORTYPE genericeventhandler(OMX_HANDLETYPE component,
struct context *ctx,
OMX_EVENTTYPE event,
OMX_U32 data1,
OMX_U32 data2,
OMX_PTR eventdata)
{
switch (event) {
case OMX_EventError:
if (ctx->flags & FLAGS_VERBOSE)
printf("%s %p has errored: %x\n", mapcomponent(ctx, component),
component, data1);
return data1;
break;
case OMX_EventCmdComplete:
if (ctx->flags & FLAGS_VERBOSE)
printf("%s %p has completed the last command.\n",
mapcomponent(ctx, component), component);
break;
case OMX_EventPortSettingsChanged: {
// if (ctx->flags & FLAGS_VERBOSE)
printf("%s %p port %d settings changed.\n",
mapcomponent(ctx, component), component, data1);
dumpport(component, data1);
}
break;
default:
if (ctx->flags & FLAGS_VERBOSE)
printf("Got an event of type %x on %s %p "
"(d1: %x, d2 %x)\n", event,
mapcomponent(ctx, component), component,
data1, data2);
}
return OMX_ErrorNone;
}
OMX_ERRORTYPE deceventhandler(OMX_HANDLETYPE component,
struct context *ctx,
OMX_EVENTTYPE event,
OMX_U32 data1,
OMX_U32 data2,
OMX_PTR eventdata)
{
if (event == OMX_EventPortSettingsChanged) {
ctx->decstate = DECTUNNELSETUP;
}
return genericeventhandler(component, ctx, event, data1, data2,
eventdata);
}
OMX_ERRORTYPE enceventhandler(OMX_HANDLETYPE component,
struct context *ctx,
OMX_EVENTTYPE event,
OMX_U32 data1,
OMX_U32 data2,
OMX_PTR eventdata)
{
return genericeventhandler(component, ctx, event, data1, data2,
eventdata);
}
OMX_ERRORTYPE rszeventhandler(OMX_HANDLETYPE component,
struct context *ctx,
OMX_EVENTTYPE event,
OMX_U32 data1,
OMX_U32 data2,
OMX_PTR eventdata)
{
return genericeventhandler(component, ctx, event, data1, data2,
eventdata);
}
OMX_ERRORTYPE emptied(OMX_HANDLETYPE component,
struct context *ctx,
OMX_BUFFERHEADERTYPE *buf)
{
if (ctx->flags & FLAGS_VERBOSE)
printf("Got a buffer emptied event on %s %p, buf %p\n",
mapcomponent(ctx, component), component, buf);
buf->nFilledLen = 0;
ctx->flags |= FLAGS_DECEMPTIEDBUF;
return OMX_ErrorNone;
}
OMX_ERRORTYPE filled(OMX_HANDLETYPE component,
struct context *ctx,
OMX_BUFFERHEADERTYPE *buf)
{
OMX_BUFFERHEADERTYPE *spare;
if (ctx->flags & FLAGS_VERBOSE)
printf("Got buffer %p filled (len %d)\n", buf,
buf->nFilledLen);
/*
* Don't call OMX_FillThisBuffer() here, as the hardware craps out after
* a short while. I don't know why. Reentrancy, or the like, I suspect.
* Queue the packet(s) and deal with them in main().
*
* It only ever seems to ask for the one buffer, but better safe than sorry...
*/
pthread_mutex_lock(&ctx->lock);
if (ctx->bufhead == NULL) {
buf->pAppPrivate = NULL;
ctx->bufhead = buf;
pthread_mutex_unlock(&ctx->lock);
return OMX_ErrorNone;
}
spare = ctx->bufhead;
while (spare->pAppPrivate != NULL)
spare = spare->pAppPrivate;
spare->pAppPrivate = buf;
buf->pAppPrivate = NULL;
pthread_mutex_unlock(&ctx->lock);
return OMX_ErrorNone;
}
OMX_CALLBACKTYPE encevents = {
(void (*)) enceventhandler,
(void (*)) emptied,
(void (*)) filled
};
OMX_CALLBACKTYPE decevents = {
(void (*)) deceventhandler,
(void (*)) emptied,
(void (*)) filled
};
OMX_CALLBACKTYPE rszevents = {
(void (*)) rszeventhandler,
(void (*)) emptied,
(void (*)) filled
};
OMX_CALLBACKTYPE genevents = {
(void (*)) genericeventhandler,
(void (*)) emptied,
(void (*)) filled
};
static void *fps(void *p)
{
enum OMX_STATETYPE state;
int lastframe;
while (1) {
lastframe = ctx.framecount;
sleep(1);
printf("Frame %6d (%5ds). Frames last second: %d \r",
ctx.framecount, ctx.framecount/25,
ctx.framecount-lastframe);
fflush(stdout);
if (0 && ctx.fps == 0) {
printf("In fps thread, after %d frames:\n",
ctx.framecount);
dumpport(ctx.dec, PORT_DEC);
dumpport(ctx.dec, PORT_DEC+1);
dumpport(ctx.enc, PORT_ENC);
dumpport(ctx.enc, PORT_ENC+1);
OMX_GetState(ctx.dec, &state);
printf("Decoder state: %d\n", state);
OMX_GetState(ctx.enc, &state);
printf("Encoder state: %d\n", state);
}
}
return NULL;
}
static OMX_BUFFERHEADERTYPE *allocbufs(OMX_HANDLETYPE h, int port, int enable)
{
int i;
OMX_BUFFERHEADERTYPE *list = NULL, **end = &list;
OMX_PARAM_PORTDEFINITIONTYPE *portdef;
MAKEME(portdef, OMX_PARAM_PORTDEFINITIONTYPE);
portdef->nPortIndex = port;
OERR(OMX_GetParameter(h, OMX_IndexParamPortDefinition, portdef));
if (enable)
OERR(OMX_SendCommand(h, OMX_CommandPortEnable, port, NULL));
for (i = 0; i < portdef->nBufferCountActual; i++) {
OMX_U8 *buf;
buf = vcos_malloc_aligned(portdef->nBufferSize,
portdef->nBufferAlignment, "buffer");
printf("Allocated a buffer of %d bytes\n",
portdef->nBufferSize);
OERR(OMX_UseBuffer(h, end, port, NULL, portdef->nBufferSize,
buf));
end = (OMX_BUFFERHEADERTYPE **) &((*end)->pAppPrivate);
}
free(portdef);
return list;
}
static AVBitStreamFilterContext *dofiltertest(AVPacket *rp)
{
AVBitStreamFilterContext *bsfc;
bsfc = NULL;
if (!(rp->data[0] == 0x00 && rp->data[1] == 0x00 &&
rp->data[2] == 0x00 && rp->data[3] == 0x01)) {
bsfc = av_bitstream_filter_init("h264_mp4toannexb");
if (!bsfc) {
printf("Failed to open filter. This is bad.\n");
} else {
printf("Have a filter at %p\n", bsfc);
}
} else
printf("No need for a filter.\n");
return bsfc;
}
static AVPacket *filter(struct context *ctx, AVPacket *rp)
{
AVPacket *p;
AVPacket *fp;
int rc;
fp = calloc(1, sizeof(AVPacket));
if (ctx->bsfc) {
rc = av_bitstream_filter_filter(ctx->bsfc,
ctx->ic->streams[ctx->vidindex]->codec,
NULL, &(fp->data), &(fp->size),
rp->data, rp->size,
rp->flags & AV_PKT_FLAG_KEY);
if (rc > 0) {
av_free_packet(rp);
fp->destruct = av_destruct_packet;
p = fp;
} else {
printf("Failed to filter frame: "
"%d (%x)\n", rc, rc);
p = rp;
}
} else
p = rp;
return p;
}
static void configure(struct context *ctx, AVPacket **ifb)
{
pthread_t fpst;
pthread_attr_t fpsa;
OMX_CONFIG_FRAMERATETYPE *framerate;
OMX_VIDEO_PARAM_PROFILELEVELTYPE *level;
OMX_VIDEO_PARAM_BITRATETYPE *bitrate;
OMX_BUFFERHEADERTYPE *encbufs;
OMX_PARAM_PORTDEFINITIONTYPE *portdef;
OMX_VIDEO_PORTDEFINITIONTYPE *viddef;
OMX_PARAM_PORTDEFINITIONTYPE *imgportdef;
OMX_IMAGE_PORTDEFINITIONTYPE *imgdef;
OMX_VIDEO_PARAM_PORTFORMATTYPE *pfmt;
OMX_HANDLETYPE dec, enc, rsz, spl, vid;
int x, y;
MAKEME(portdef, OMX_PARAM_PORTDEFINITIONTYPE);
MAKEME(imgportdef, OMX_PARAM_PORTDEFINITIONTYPE);
/* These just save a bit of typing. No other reason. */
dec = ctx->dec;
enc = ctx->enc;
rsz = ctx->rsz;
spl = ctx->spl;
vid = ctx->vid;
viddef = &portdef->format.video;
imgdef = &imgportdef->format.image;
printf("Decoder has changed settings. Setting up encoder.\n");
/* Get the decoder port state...: */
portdef->nPortIndex = PORT_DEC+1;
OERR(OMX_GetParameter(dec, OMX_IndexParamPortDefinition, portdef));
if (ctx->resize) {
OERR(OMX_SendCommand(rsz, OMX_CommandStateSet, OMX_StateIdle, NULL));
imgportdef->nPortIndex = PORT_RSZ;
OERR(OMX_GetParameter(rsz, OMX_IndexParamPortDefinition,
imgportdef));
/*
* The least they could have done was to make *all* the common elements appear
* in the same place in the structures, but no...
*/
imgdef->nFrameWidth = viddef->nFrameWidth;
imgdef->nFrameHeight = viddef->nFrameHeight;
imgdef->nStride = viddef->nStride;
imgdef->nSliceHeight = viddef->nSliceHeight;
imgdef->bFlagErrorConcealment = viddef->bFlagErrorConcealment;
imgdef->eCompressionFormat = viddef->eCompressionFormat;
imgdef->eColorFormat = viddef->eColorFormat;
imgdef->pNativeWindow = viddef->pNativeWindow;
OERR(OMX_SetParameter(rsz, OMX_IndexParamPortDefinition,
imgportdef));
if (sscanf(ctx->resize, "%dx%d", &x, &y) == 2) {
x += 0x0f;
x &= ~0x0f;
y += 0x0f;
y &= ~0x0f;
imgdef->nFrameWidth = x;
imgdef->nFrameHeight = y;
} else {
imgdef->nFrameWidth *= x;
imgdef->nFrameWidth /= 100;
imgdef->nFrameWidth += 0x0f;
imgdef->nFrameWidth &= ~0x0f;
imgdef->nFrameHeight *= x;
imgdef->nFrameHeight /= 100;
imgdef->nFrameHeight += 0x0f;
imgdef->nFrameHeight &= ~0x0f;
}
imgdef->nStride = 0;
imgdef->nSliceHeight = 0;
printf("Frame size: %dx%d, scale factor %d\n",
imgdef->nFrameWidth, imgdef->nFrameHeight, x);
imgportdef->nPortIndex = PORT_RSZ+1;
OERR(OMX_SetParameter(rsz, OMX_IndexParamPortDefinition, imgportdef));
portdef->nPortIndex = PORT_ENC;
viddef->nFrameWidth = imgdef->nFrameWidth;
viddef->nFrameHeight = imgdef->nFrameHeight;
viddef->nStride = imgdef->nStride;
viddef->nSliceHeight = imgdef->nSliceHeight;
viddef->bFlagErrorConcealment = imgdef->bFlagErrorConcealment;
viddef->eCompressionFormat = imgdef->eCompressionFormat;
viddef->eColorFormat = imgdef->eColorFormat;
viddef->pNativeWindow = imgdef->pNativeWindow;
}
/* ... and feed it to the encoder: */
portdef->nPortIndex = PORT_ENC;
OERR(OMX_SetParameter(enc, OMX_IndexParamPortDefinition, portdef));
/* Setup the tunnel(s): */
if (ctx->flags & FLAGS_MONITOR) {
OERR(OMX_SendCommand(vid, OMX_CommandStateSet, OMX_StateIdle,
NULL));
OERR(OMX_SendCommand(spl, OMX_CommandStateSet, OMX_StateIdle,
NULL));
portdef->nPortIndex = PORT_VID;
// OERR(OMX_SetParameter(vid, OMX_IndexParamPortDefinition, portdef));
dumpport(spl, PORT_SPL);
portdef->nPortIndex = PORT_SPL;
OERR(OMX_SetParameter(spl, OMX_IndexParamPortDefinition,
portdef));
portdef->nPortIndex = PORT_SPL+1;
OERR(OMX_SetParameter(spl, OMX_IndexParamPortDefinition,
portdef));
portdef->nPortIndex = PORT_SPL+2;
OERR(OMX_SetParameter(spl, OMX_IndexParamPortDefinition,
portdef));
OERR(OMX_SetupTunnel(dec, PORT_DEC+1, spl, PORT_SPL));
OERR(OMX_SetupTunnel(spl, PORT_SPL+2, vid, PORT_VID));
if (ctx->resize) {
OERR(OMX_SetupTunnel(spl, PORT_SPL+1, rsz,
PORT_RSZ));
OERR(OMX_SetupTunnel(rsz, PORT_RSZ+1, enc,
PORT_ENC));
} else {
OERR(OMX_SetupTunnel(spl, PORT_SPL+1, enc,
PORT_ENC));
}
} else {
if (ctx->resize) {
OERR(OMX_SetupTunnel(dec, PORT_DEC+1, rsz,
PORT_RSZ));
OERR(OMX_SetupTunnel(rsz, PORT_RSZ+1, enc,
PORT_ENC));
} else {
OERR(OMX_SetupTunnel(dec, PORT_DEC+1, enc,
PORT_ENC));
}
}
OERR(OMX_SendCommand(enc, OMX_CommandStateSet, OMX_StateIdle, NULL));
if (ctx->bitrate == 0) {
viddef->nBitrate *= 3;
viddef->nBitrate /= 4;
} else {
if (ctx->bitrate == 0)
viddef->nBitrate = (2*1024*1024);
else
viddef->nBitrate = ctx->bitrate;
ctx->bitrate = viddef->nBitrate;
}
viddef->eCompressionFormat = OMX_VIDEO_CodingAVC;
viddef->nStride = viddef->nSliceHeight = viddef->eColorFormat = 0;
portdef->nPortIndex = PORT_ENC+1;
OERR(OMX_SetParameter(enc, OMX_IndexParamPortDefinition, portdef));
MAKEME(bitrate, OMX_VIDEO_PARAM_BITRATETYPE);
bitrate->nPortIndex = PORT_ENC+1;
bitrate->eControlRate = OMX_Video_ControlRateVariable;
bitrate->nTargetBitrate = viddef->nBitrate;
OERR(OMX_SetParameter(enc, OMX_IndexParamVideoBitrate, bitrate));
MAKEME(pfmt, OMX_VIDEO_PARAM_PORTFORMATTYPE);
pfmt->nPortIndex = PORT_ENC+1;
pfmt->nIndex = 0;
pfmt->eCompressionFormat = OMX_VIDEO_CodingAVC;
pfmt->eColorFormat = OMX_COLOR_FormatYUV420PackedPlanar;
pfmt->xFramerate = viddef->xFramerate;
pfmt->nPortIndex = PORT_ENC+1;
pfmt->nIndex = 1;
pfmt->eCompressionFormat = OMX_VIDEO_CodingAVC;
pfmt->eColorFormat = 0;
pfmt->xFramerate = 0; //viddef->xFramerate;
OERR(OMX_SetParameter(enc, OMX_IndexParamVideoPortFormat,
pfmt));
MAKEME(framerate, OMX_CONFIG_FRAMERATETYPE);
framerate->nPortIndex = PORT_ENC+1;
framerate->xEncodeFramerate = viddef->xFramerate;
OERR(OMX_SetParameter(enc, OMX_IndexConfigVideoFramerate, framerate));
#if 0 /* Doesn't seem to apply to video? */
printf("Interlacing: %d\n", ic->streams[vidindex]->codec->field_order);
if (0 || ic->streams[vidindex]->codec->field_order == AV_FIELD_TT) {
interlace->nPortIndex = PORT_ENC+1;
interlace->eMode = OMX_InterlaceFieldsInterleavedUpperFirst;
interlace->bRepeatFirstField = 0;
OERR(OMX_SetParameter(enc, OMX_IndexConfigCommonInterlace,
interlace));
}
#endif
MAKEME(level, OMX_VIDEO_PARAM_PROFILELEVELTYPE);
level->nPortIndex = PORT_ENC+1;
OERR(OMX_GetParameter(enc, OMX_IndexParamVideoProfileLevelCurrent,
level));
printf("Current level:\t\t%d\nCurrent profile:\t%d\n",
level->eLevel, level->eProfile);
OERR(OMX_SetParameter(enc, OMX_IndexParamVideoProfileLevelCurrent,
level));
ctx->encbufs = encbufs = allocbufs(enc, PORT_ENC+1, 1);
OERR(OMX_SendCommand(dec, OMX_CommandPortEnable, PORT_DEC+1, NULL));
OERR(OMX_SendCommand(enc, OMX_CommandPortEnable, PORT_ENC, NULL));
if (ctx->flags & FLAGS_MONITOR) {
OERR(OMX_SendCommand(vid, OMX_CommandPortEnable, PORT_VID,
NULL));
OERR(OMX_SendCommand(spl, OMX_CommandPortEnable, PORT_SPL,
NULL));
OERR(OMX_SendCommand(spl, OMX_CommandPortEnable, PORT_SPL+1,
NULL));
OERR(OMX_SendCommand(spl, OMX_CommandPortEnable, PORT_SPL+2,
NULL));
// sleep(1); printf("\n\n\n\n\n"); for (i = 0; i < 5; i++) dumpport(spl, PORT_SPL+i); sleep(1);
printf("Pre-sleep.\n"); fflush(stdout);
sleep(1); /* Should probably wait for an event instead */
printf("Post-sleep.\n"); fflush(stdout);
OERR(OMX_SendCommand(vid, OMX_CommandStateSet,
OMX_StateExecuting, NULL));
OERR(OMX_SendCommand(spl, OMX_CommandStateSet,
OMX_StateExecuting, NULL));
}
if (ctx->resize) {
OERR(OMX_SendCommand(rsz, OMX_CommandPortEnable, PORT_RSZ, NULL));
OERR(OMX_SendCommand(rsz, OMX_CommandPortEnable, PORT_RSZ+1, NULL));
OERR(OMX_SendCommand(rsz, OMX_CommandStateSet, OMX_StateExecuting, NULL));
}
OERR(OMX_SendCommand(enc, OMX_CommandStateSet, OMX_StateExecuting, NULL));
sleep(1);
OERR(OMX_FillThisBuffer(enc, encbufs));
/* Dump current port states: */
dumpport(dec, PORT_DEC);
dumpport(dec, PORT_DEC+1);
if (ctx->resize) {
dumpport(rsz, PORT_RSZ);
dumpport(rsz, PORT_RSZ+1);
}
dumpport(enc, PORT_ENC);
dumpport(enc, PORT_ENC+1);
/* Make an output context: */
ctx->oc = makeoutputcontext(ctx->ic, ctx->oname, ctx->vidindex,
portdef, ifb);
if (!ctx->oc) {
fprintf(stderr, "Whoops.\n");
exit(1);
}
atexit(dumpportstate);
pthread_attr_init(&fpsa);
pthread_attr_setdetachstate(&fpsa, PTHREAD_CREATE_DETACHED);
pthread_create(&fpst, &fpsa, fps, NULL);
}
static void usage(const char *name)
{
fprintf(stderr, "Usage: %s [-b bitrate] [-m] [-r size] <infile> "
"<outfile>\n\n"
"Where:\n"
"\t-b bitrate\tTarget bitrate in bits/second (default: 2Mb/s)\n"
"\t-m\t\tMonitor. Display the decoder's output\n"
"\t-r size\t\tResize output. 'size' is either a percentage, or XXxYY\n"
"\n", name);
exit(1);
}
static void freepacket(AVPacket *p)
{
if (p->data)
free(p->data);
p->data = NULL;
p->destruct = av_destruct_packet;
av_free_packet(p);
}
int main(int argc, char *argv[])
{
AVFormatContext *ic;
AVFormatContext *oc;
char *iname;
int err;
int vidindex;
int i, j;
OMX_ERRORTYPE oerr;
OMX_HANDLETYPE dec = NULL, enc = NULL, rsz = NULL, spl = NULL, vid = NULL;
OMX_VIDEO_PARAM_PORTFORMATTYPE *pfmt;
OMX_PORT_PARAM_TYPE *porttype;
OMX_PARAM_PORTDEFINITIONTYPE *portdef;
OMX_BUFFERHEADERTYPE *decbufs;
OMX_VIDEO_PORTDEFINITIONTYPE *viddef;
OMX_VIDEO_PARAM_PROFILELEVELTYPE *level;
time_t start, end;
int offset;
AVPacket *p, *rp;
int ish264;