-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
RaspiVid.c
2962 lines (2493 loc) · 98.5 KB
/
RaspiVid.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
/*
Copyright (c) 2018, Raspberry Pi (Trading) Ltd.
Copyright (c) 2013, Broadcom Europe Ltd.
Copyright (c) 2013, James Hughes
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file RaspiVid.c
* Command line program to capture a camera video stream and encode it to file.
* Also optionally display a preview/viewfinder of current camera input.
*
* Description
*
* 3 components are created; camera, preview and video encoder.
* Camera component has three ports, preview, video and stills.
* This program connects preview and video to the preview and video
* encoder. Using mmal we don't need to worry about buffers between these
* components, but we do need to handle buffers from the encoder, which
* are simply written straight to the file in the requisite buffer callback.
*
* If raw option is selected, a video splitter component is connected between
* camera and preview. This allows us to set up callback for raw camera data
* (in YUV420 or RGB format) which might be useful for further image processing.
*
* We use the RaspiCamControl code to handle the specific camera settings.
* We use the RaspiPreview code to handle the (generic) preview window
*/
// We use some GNU extensions (basename)
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <memory.h>
#include <sysexits.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include "bcm_host.h"
#include "interface/vcos/vcos.h"
#include "interface/mmal/mmal.h"
#include "interface/mmal/mmal_logging.h"
#include "interface/mmal/mmal_buffer.h"
#include "interface/mmal/util/mmal_util.h"
#include "interface/mmal/util/mmal_util_params.h"
#include "interface/mmal/util/mmal_default_components.h"
#include "interface/mmal/util/mmal_connection.h"
#include "interface/mmal/mmal_parameters_camera.h"
#include "RaspiCommonSettings.h"
#include "RaspiCamControl.h"
#include "RaspiPreview.h"
#include "RaspiCLI.h"
#include "RaspiHelpers.h"
#include "RaspiGPS.h"
#include <semaphore.h>
#include <stdbool.h>
// Standard port setting for the camera component
#define MMAL_CAMERA_PREVIEW_PORT 0
#define MMAL_CAMERA_VIDEO_PORT 1
#define MMAL_CAMERA_CAPTURE_PORT 2
// Port configuration for the splitter component
#define SPLITTER_OUTPUT_PORT 0
#define SPLITTER_PREVIEW_PORT 1
// Video format information
// 0 implies variable
#define VIDEO_FRAME_RATE_NUM 30
#define VIDEO_FRAME_RATE_DEN 1
/// Video render needs at least 2 buffers.
#define VIDEO_OUTPUT_BUFFERS_NUM 3
// Max bitrate we allow for recording
const int MAX_BITRATE_MJPEG = 25000000; // 25Mbits/s
const int MAX_BITRATE_LEVEL4 = 25000000; // 25Mbits/s
const int MAX_BITRATE_LEVEL42 = 62500000; // 62.5Mbits/s
/// Interval at which we check for an failure abort during capture
const int ABORT_INTERVAL = 100; // ms
/// Capture/Pause switch method
/// Simply capture for time specified
enum
{
WAIT_METHOD_NONE, /// Simply capture for time specified
WAIT_METHOD_TIMED, /// Cycle between capture and pause for times specified
WAIT_METHOD_KEYPRESS, /// Switch between capture and pause on keypress
WAIT_METHOD_SIGNAL, /// Switch between capture and pause on signal
WAIT_METHOD_FOREVER /// Run/record forever
};
// Forward
typedef struct RASPIVID_STATE_S RASPIVID_STATE;
/** Struct used to pass information in encoder port userdata to callback
*/
typedef struct
{
FILE *file_handle; /// File handle to write buffer data to.
RASPIVID_STATE *pstate; /// pointer to our state in case required in callback
int abort; /// Set to 1 in callback if an error occurs to attempt to abort the capture
char *cb_buff; /// Circular buffer
int cb_len; /// Length of buffer
int cb_wptr; /// Current write pointer
int cb_wrap; /// Has buffer wrapped at least once?
int cb_data; /// Valid bytes in buffer
#define IFRAME_BUFSIZE (60*1000)
int iframe_buff[IFRAME_BUFSIZE]; /// buffer of iframe pointers
int iframe_buff_wpos;
int iframe_buff_rpos;
char header_bytes[29];
int header_wptr;
FILE *imv_file_handle; /// File handle to write inline motion vectors to.
FILE *raw_file_handle; /// File handle to write raw data to.
int flush_buffers;
FILE *pts_file_handle; /// File timestamps
} PORT_USERDATA;
/** Possible raw output formats
*/
typedef enum
{
RAW_OUTPUT_FMT_YUV = 0,
RAW_OUTPUT_FMT_RGB,
RAW_OUTPUT_FMT_GRAY,
} RAW_OUTPUT_FMT;
/** Structure containing all state information for the current run
*/
struct RASPIVID_STATE_S
{
RASPICOMMONSETTINGS_PARAMETERS common_settings; /// Common settings
int timeout; /// Time taken before frame is grabbed and app then shuts down. Units are milliseconds
MMAL_FOURCC_T encoding; /// Requested codec video encoding (MJPEG or H264)
int bitrate; /// Requested bitrate
int framerate; /// Requested frame rate (fps)
int intraperiod; /// Intra-refresh period (key frame rate)
int quantisationParameter; /// Quantisation parameter - quality. Set bitrate 0 and set this for variable bitrate
int bInlineHeaders; /// Insert inline headers to stream (SPS, PPS)
int demoMode; /// Run app in demo mode
int demoInterval; /// Interval between camera settings changes
int immutableInput; /// Flag to specify whether encoder works in place or creates a new buffer. Result is preview can display either
/// the camera output or the encoder output (with compression artifacts)
int profile; /// H264 profile to use for encoding
int level; /// H264 level to use for encoding
int waitMethod; /// Method for switching between pause and capture
int onTime; /// In timed cycle mode, the amount of time the capture is on per cycle
int offTime; /// In timed cycle mode, the amount of time the capture is off per cycle
int segmentSize; /// Segment mode In timed cycle mode, the amount of time the capture is off per cycle
int segmentWrap; /// Point at which to wrap segment counter
int segmentNumber; /// Current segment counter
int splitNow; /// Split at next possible i-frame if set to 1.
int splitWait; /// Switch if user wants splited files
RASPIPREVIEW_PARAMETERS preview_parameters; /// Preview setup parameters
RASPICAM_CAMERA_PARAMETERS camera_parameters; /// Camera setup parameters
MMAL_COMPONENT_T *camera_component; /// Pointer to the camera component
MMAL_COMPONENT_T *splitter_component; /// Pointer to the splitter component
MMAL_COMPONENT_T *encoder_component; /// Pointer to the encoder component
MMAL_CONNECTION_T *preview_connection; /// Pointer to the connection from camera or splitter to preview
MMAL_CONNECTION_T *splitter_connection;/// Pointer to the connection from camera to splitter
MMAL_CONNECTION_T *encoder_connection; /// Pointer to the connection from camera to encoder
MMAL_POOL_T *splitter_pool; /// Pointer to the pool of buffers used by splitter output port 0
MMAL_POOL_T *encoder_pool; /// Pointer to the pool of buffers used by encoder output port
PORT_USERDATA callback_data; /// Used to move data to the encoder callback
int bCapturing; /// State of capture/pause
int bCircularBuffer; /// Whether we are writing to a circular buffer
int inlineMotionVectors; /// Encoder outputs inline Motion Vectors
char *imv_filename; /// filename of inline Motion Vectors output
int raw_output; /// Output raw video from camera as well
RAW_OUTPUT_FMT raw_output_fmt; /// The raw video format
char *raw_filename; /// Filename for raw video output
int intra_refresh_type; /// What intra refresh type to use. -1 to not set.
int frame;
char *pts_filename;
int save_pts;
int64_t starttime;
int64_t lasttime;
bool netListen;
MMAL_BOOL_T addSPSTiming;
int slices;
};
/// Structure to cross reference H264 profile strings against the MMAL parameter equivalent
static XREF_T profile_map[] =
{
{"baseline", MMAL_VIDEO_PROFILE_H264_BASELINE},
{"main", MMAL_VIDEO_PROFILE_H264_MAIN},
{"high", MMAL_VIDEO_PROFILE_H264_HIGH},
// {"constrained", MMAL_VIDEO_PROFILE_H264_CONSTRAINED_BASELINE} // Does anyone need this?
};
static int profile_map_size = sizeof(profile_map) / sizeof(profile_map[0]);
/// Structure to cross reference H264 level strings against the MMAL parameter equivalent
static XREF_T level_map[] =
{
{"4", MMAL_VIDEO_LEVEL_H264_4},
{"4.1", MMAL_VIDEO_LEVEL_H264_41},
{"4.2", MMAL_VIDEO_LEVEL_H264_42},
};
static int level_map_size = sizeof(level_map) / sizeof(level_map[0]);
static XREF_T initial_map[] =
{
{"record", 0},
{"pause", 1},
};
static int initial_map_size = sizeof(initial_map) / sizeof(initial_map[0]);
static XREF_T intra_refresh_map[] =
{
{"cyclic", MMAL_VIDEO_INTRA_REFRESH_CYCLIC},
{"adaptive", MMAL_VIDEO_INTRA_REFRESH_ADAPTIVE},
{"both", MMAL_VIDEO_INTRA_REFRESH_BOTH},
{"cyclicrows", MMAL_VIDEO_INTRA_REFRESH_CYCLIC_MROWS},
// {"random", MMAL_VIDEO_INTRA_REFRESH_PSEUDO_RAND} Cannot use random, crashes the encoder. No idea why.
};
static int intra_refresh_map_size = sizeof(intra_refresh_map) / sizeof(intra_refresh_map[0]);
static XREF_T raw_output_fmt_map[] =
{
{"yuv", RAW_OUTPUT_FMT_YUV},
{"rgb", RAW_OUTPUT_FMT_RGB},
{"gray", RAW_OUTPUT_FMT_GRAY},
};
static int raw_output_fmt_map_size = sizeof(raw_output_fmt_map) / sizeof(raw_output_fmt_map[0]);
/// Command ID's and Structure defining our command line options
enum
{
CommandBitrate,
CommandTimeout,
CommandDemoMode,
CommandFramerate,
CommandPreviewEnc,
CommandIntraPeriod,
CommandProfile,
CommandTimed,
CommandSignal,
CommandKeypress,
CommandInitialState,
CommandQP,
CommandInlineHeaders,
CommandSegmentFile,
CommandSegmentWrap,
CommandSegmentStart,
CommandSplitWait,
CommandCircular,
CommandIMV,
CommandIntraRefreshType,
CommandFlush,
CommandSavePTS,
CommandCodec,
CommandLevel,
CommandRaw,
CommandRawFormat,
CommandNetListen,
CommandSPSTimings,
CommandSlices
};
static COMMAND_LIST cmdline_commands[] =
{
{ CommandBitrate, "-bitrate", "b", "Set bitrate. Use bits per second (e.g. 10MBits/s would be -b 10000000)", 1 },
{ CommandTimeout, "-timeout", "t", "Time (in ms) to capture for. If not specified, set to 5s. Zero to disable", 1 },
{ CommandDemoMode, "-demo", "d", "Run a demo mode (cycle through range of camera options, no capture)", 1},
{ CommandFramerate, "-framerate", "fps","Specify the frames per second to record", 1},
{ CommandPreviewEnc, "-penc", "e", "Display preview image *after* encoding (shows compression artifacts)", 0},
{ CommandIntraPeriod, "-intra", "g", "Specify the intra refresh period (key frame rate/GoP size). Zero to produce an initial I-frame and then just P-frames.", 1},
{ CommandProfile, "-profile", "pf", "Specify H264 profile to use for encoding", 1},
{ CommandTimed, "-timed", "td", "Cycle between capture and pause. -cycle on,off where on is record time and off is pause time in ms", 0},
{ CommandSignal, "-signal", "s", "Cycle between capture and pause on Signal", 0},
{ CommandKeypress, "-keypress", "k", "Cycle between capture and pause on ENTER", 0},
{ CommandInitialState, "-initial", "i", "Initial state. Use 'record' or 'pause'. Default 'record'", 1},
{ CommandQP, "-qp", "qp", "Quantisation parameter. Use approximately 10-40. Default 0 (off)", 1},
{ CommandInlineHeaders, "-inline", "ih", "Insert inline headers (SPS, PPS) to stream", 0},
{ CommandSegmentFile, "-segment", "sg", "Segment output file in to multiple files at specified interval <ms>", 1},
{ CommandSegmentWrap, "-wrap", "wr", "In segment mode, wrap any numbered filename back to 1 when reach number", 1},
{ CommandSegmentStart, "-start", "sn", "In segment mode, start with specified segment number", 1},
{ CommandSplitWait, "-split", "sp", "In wait mode, create new output file for each start event", 0},
{ CommandCircular, "-circular", "c", "Run encoded data through circular buffer until triggered then save", 0},
{ CommandIMV, "-vectors", "x", "Output filename <filename> for inline motion vectors", 1 },
{ CommandIntraRefreshType,"-irefresh", "if", "Set intra refresh type", 1},
{ CommandFlush, "-flush", "fl", "Flush buffers in order to decrease latency", 0 },
{ CommandSavePTS, "-save-pts", "pts","Save Timestamps to file for mkvmerge", 1 },
{ CommandCodec, "-codec", "cd", "Specify the codec to use - H264 (default) or MJPEG", 1 },
{ CommandLevel, "-level", "lev","Specify H264 level to use for encoding", 1},
{ CommandRaw, "-raw", "r", "Output filename <filename> for raw video", 1 },
{ CommandRawFormat, "-raw-format", "rf", "Specify output format for raw video. Default is yuv", 1},
{ CommandNetListen, "-listen", "l", "Listen on a TCP socket", 0},
{ CommandSPSTimings, "-spstimings", "stm", "Add in h.264 sps timings", 0},
{ CommandSlices , "-slices", "sl", "Horizontal slices per frame. Default 1 (off)", 1},
};
static int cmdline_commands_size = sizeof(cmdline_commands) / sizeof(cmdline_commands[0]);
static struct
{
char *description;
int nextWaitMethod;
} wait_method_description[] =
{
{"Simple capture", WAIT_METHOD_NONE},
{"Capture forever", WAIT_METHOD_FOREVER},
{"Cycle on time", WAIT_METHOD_TIMED},
{"Cycle on keypress", WAIT_METHOD_KEYPRESS},
{"Cycle on signal", WAIT_METHOD_SIGNAL},
};
static int wait_method_description_size = sizeof(wait_method_description) / sizeof(wait_method_description[0]);
/**
* Assign a default set of parameters to the state passed in
*
* @param state Pointer to state structure to assign defaults to
*/
static void default_status(RASPIVID_STATE *state)
{
if (!state)
{
vcos_assert(0);
return;
}
// Default everything to zero
memset(state, 0, sizeof(RASPIVID_STATE));
raspicommonsettings_set_defaults(&state->common_settings);
// Now set anything non-zero
state->timeout = -1; // replaced with 5000ms later if unset
state->common_settings.width = 1920; // Default to 1080p
state->common_settings.height = 1080;
state->encoding = MMAL_ENCODING_H264;
state->bitrate = 17000000; // This is a decent default bitrate for 1080p
state->framerate = VIDEO_FRAME_RATE_NUM;
state->intraperiod = -1; // Not set
state->quantisationParameter = 0;
state->demoMode = 0;
state->demoInterval = 250; // ms
state->immutableInput = 1;
state->profile = MMAL_VIDEO_PROFILE_H264_HIGH;
state->level = MMAL_VIDEO_LEVEL_H264_4;
state->waitMethod = WAIT_METHOD_NONE;
state->onTime = 5000;
state->offTime = 5000;
state->bCapturing = 0;
state->bInlineHeaders = 0;
state->segmentSize = 0; // 0 = not segmenting the file.
state->segmentNumber = 1;
state->segmentWrap = 0; // Point at which to wrap segment number back to 1. 0 = no wrap
state->splitNow = 0;
state->splitWait = 0;
state->inlineMotionVectors = 0;
state->intra_refresh_type = -1;
state->frame = 0;
state->save_pts = 0;
state->netListen = false;
state->addSPSTiming = MMAL_FALSE;
state->slices = 1;
// Setup preview window defaults
raspipreview_set_defaults(&state->preview_parameters);
// Set up the camera_parameters to default
raspicamcontrol_set_defaults(&state->camera_parameters);
}
static void check_camera_model(int cam_num)
{
MMAL_COMPONENT_T *camera_info;
MMAL_STATUS_T status;
// Try to get the camera name
status = mmal_component_create(MMAL_COMPONENT_DEFAULT_CAMERA_INFO, &camera_info);
if (status == MMAL_SUCCESS)
{
MMAL_PARAMETER_CAMERA_INFO_T param;
param.hdr.id = MMAL_PARAMETER_CAMERA_INFO;
param.hdr.size = sizeof(param)-4; // Deliberately undersize to check firmware version
status = mmal_port_parameter_get(camera_info->control, ¶m.hdr);
if (status != MMAL_SUCCESS)
{
// Running on newer firmware
param.hdr.size = sizeof(param);
status = mmal_port_parameter_get(camera_info->control, ¶m.hdr);
if (status == MMAL_SUCCESS && param.num_cameras > cam_num)
{
if (!strncmp(param.cameras[cam_num].camera_name, "toshh2c", 7))
{
fprintf(stderr, "The driver for the TC358743 HDMI to CSI2 chip you are using is NOT supported.\n");
fprintf(stderr, "They were written for a demo purposes only, and are in the firmware on an as-is\n");
fprintf(stderr, "basis and therefore requests for support or changes will not be acted on.\n\n");
}
}
}
mmal_component_destroy(camera_info);
}
}
/**
* Dump image state parameters to stderr.
*
* @param state Pointer to state structure to assign defaults to
*/
static void dump_status(RASPIVID_STATE *state)
{
int i;
if (!state)
{
vcos_assert(0);
return;
}
raspicommonsettings_dump_parameters(&state->common_settings);
fprintf(stderr, "bitrate %d, framerate %d, time delay %d\n", state->bitrate, state->framerate, state->timeout);
fprintf(stderr, "H264 Profile %s\n", raspicli_unmap_xref(state->profile, profile_map, profile_map_size));
fprintf(stderr, "H264 Level %s\n", raspicli_unmap_xref(state->level, level_map, level_map_size));
fprintf(stderr, "H264 Quantisation level %d, Inline headers %s\n", state->quantisationParameter, state->bInlineHeaders ? "Yes" : "No");
fprintf(stderr, "H264 Fill SPS Timings %s\n", state->addSPSTiming ? "Yes" : "No");
fprintf(stderr, "H264 Intra refresh type %s, period %d\n", raspicli_unmap_xref(state->intra_refresh_type, intra_refresh_map, intra_refresh_map_size), state->intraperiod);
fprintf(stderr, "H264 Slices %d\n", state->slices);
// Not going to display segment data unless asked for it.
if (state->segmentSize)
fprintf(stderr, "Segment size %d, segment wrap value %d, initial segment number %d\n", state->segmentSize, state->segmentWrap, state->segmentNumber);
if (state->raw_output)
fprintf(stderr, "Raw output enabled, format %s\n", raspicli_unmap_xref(state->raw_output_fmt, raw_output_fmt_map, raw_output_fmt_map_size));
fprintf(stderr, "Wait method : ");
for (i=0; i<wait_method_description_size; i++)
{
if (state->waitMethod == wait_method_description[i].nextWaitMethod)
fprintf(stderr, "%s", wait_method_description[i].description);
}
fprintf(stderr, "\nInitial state '%s'\n", raspicli_unmap_xref(state->bCapturing, initial_map, initial_map_size));
fprintf(stderr, "\n\n");
raspipreview_dump_parameters(&state->preview_parameters);
raspicamcontrol_dump_parameters(&state->camera_parameters);
}
/**
* Display usage information for the application to stdout
*
* @param app_name String to display as the application name
*/
static void application_help_message(char *app_name)
{
int i;
fprintf(stdout, "Display camera output to display, and optionally saves an H264 capture at requested bitrate\n\n");
fprintf(stdout, "\nusage: %s [options]\n\n", app_name);
fprintf(stdout, "Image parameter commands\n\n");
raspicli_display_help(cmdline_commands, cmdline_commands_size);
// Profile options
fprintf(stdout, "\n\nH264 Profile options :\n%s", profile_map[0].mode );
for (i=1; i<profile_map_size; i++)
{
fprintf(stdout, ",%s", profile_map[i].mode);
}
// Level options
fprintf(stdout, "\n\nH264 Level options :\n%s", level_map[0].mode );
for (i=1; i<level_map_size; i++)
{
fprintf(stdout, ",%s", level_map[i].mode);
}
// Intra refresh options
fprintf(stdout, "\n\nH264 Intra refresh options :\n%s", intra_refresh_map[0].mode );
for (i=1; i<intra_refresh_map_size; i++)
{
fprintf(stdout, ",%s", intra_refresh_map[i].mode);
}
// Raw output format options
fprintf(stdout, "\n\nRaw output format options :\n%s", raw_output_fmt_map[0].mode );
for (i=1; i<raw_output_fmt_map_size; i++)
{
fprintf(stdout, ",%s", raw_output_fmt_map[i].mode);
}
fprintf(stdout, "\n\n");
fprintf(stdout, "Raspivid allows output to a remote IPv4 host e.g. -o tcp://192.168.1.2:1234"
"or -o udp://192.168.1.2:1234\n"
"To listen on a TCP port (IPv4) and wait for an incoming connection use the -l option\n"
"e.g. raspivid -l -o tcp://0.0.0.0:3333 -> bind to all network interfaces,\n"
"raspivid -l -o tcp://192.168.1.1:3333 -> bind to a certain local IPv4 port\n");
return;
}
/**
* Parse the incoming command line and put resulting parameters in to the state
*
* @param argc Number of arguments in command line
* @param argv Array of pointers to strings from command line
* @param state Pointer to state structure to assign any discovered parameters to
* @return Non-0 if failed for some reason, 0 otherwise
*/
static int parse_cmdline(int argc, const char **argv, RASPIVID_STATE *state)
{
// Parse the command line arguments.
// We are looking for --<something> or -<abbreviation of something>
int valid = 1;
int i;
for (i = 1; i < argc && valid; i++)
{
int command_id, num_parameters;
if (!argv[i])
continue;
if (argv[i][0] != '-')
{
valid = 0;
continue;
}
// Assume parameter is valid until proven otherwise
valid = 1;
command_id = raspicli_get_command_id(cmdline_commands, cmdline_commands_size, &argv[i][1], &num_parameters);
// If we found a command but are missing a parameter, continue (and we will drop out of the loop)
if (command_id != -1 && num_parameters > 0 && (i + 1 >= argc) )
continue;
// We are now dealing with a command line option
switch (command_id)
{
case CommandBitrate: // 1-100
if (sscanf(argv[i + 1], "%u", &state->bitrate) == 1)
{
i++;
}
else
valid = 0;
break;
case CommandTimeout: // Time to run viewfinder/capture
{
if (sscanf(argv[i + 1], "%d", &state->timeout) == 1)
{
// Ensure that if previously selected a waitMethod we don't overwrite it
if (state->timeout == 0 && state->waitMethod == WAIT_METHOD_NONE)
state->waitMethod = WAIT_METHOD_FOREVER;
i++;
}
else
valid = 0;
break;
}
case CommandDemoMode: // Run in demo mode - no capture
{
// Demo mode might have a timing parameter
// so check if a) we have another parameter, b) its not the start of the next option
if (i + 1 < argc && argv[i+1][0] != '-')
{
if (sscanf(argv[i + 1], "%u", &state->demoInterval) == 1)
{
// TODO : What limits do we need for timeout?
if (state->demoInterval == 0)
state->demoInterval = 250; // ms
state->demoMode = 1;
i++;
}
else
valid = 0;
}
else
{
state->demoMode = 1;
}
break;
}
case CommandFramerate: // fps to record
{
if (sscanf(argv[i + 1], "%u", &state->framerate) == 1)
{
// TODO : What limits do we need for fps 1 - 30 - 120??
i++;
}
else
valid = 0;
break;
}
case CommandPreviewEnc:
state->immutableInput = 0;
break;
case CommandIntraPeriod: // key frame rate
{
if (sscanf(argv[i + 1], "%u", &state->intraperiod) == 1)
i++;
else
valid = 0;
break;
}
case CommandQP: // quantisation parameter
{
if (sscanf(argv[i + 1], "%u", &state->quantisationParameter) == 1)
i++;
else
valid = 0;
break;
}
case CommandProfile: // H264 profile
{
state->profile = raspicli_map_xref(argv[i + 1], profile_map, profile_map_size);
if( state->profile == -1)
state->profile = MMAL_VIDEO_PROFILE_H264_HIGH;
i++;
break;
}
case CommandInlineHeaders: // H264 inline headers
{
state->bInlineHeaders = 1;
break;
}
case CommandTimed:
{
if (sscanf(argv[i + 1], "%u,%u", &state->onTime, &state->offTime) == 2)
{
i++;
if (state->onTime < 1000)
state->onTime = 1000;
if (state->offTime < 1000)
state->offTime = 1000;
state->waitMethod = WAIT_METHOD_TIMED;
if (state->timeout == -1)
state->timeout = 0;
}
else
valid = 0;
break;
}
case CommandKeypress:
state->waitMethod = WAIT_METHOD_KEYPRESS;
if (state->timeout == -1)
state->timeout = 0;
break;
case CommandSignal:
state->waitMethod = WAIT_METHOD_SIGNAL;
// Reenable the signal
signal(SIGUSR1, default_signal_handler);
if (state->timeout == -1)
state->timeout = 0;
break;
case CommandInitialState:
{
state->bCapturing = raspicli_map_xref(argv[i + 1], initial_map, initial_map_size);
if( state->bCapturing == -1)
state->bCapturing = 0;
i++;
break;
}
case CommandSegmentFile: // Segment file in to chunks of specified time
{
if (sscanf(argv[i + 1], "%u", &state->segmentSize) == 1)
{
// Must enable inline headers for this to work
state->bInlineHeaders = 1;
i++;
}
else
valid = 0;
break;
}
case CommandSegmentWrap: // segment wrap value
{
if (sscanf(argv[i + 1], "%u", &state->segmentWrap) == 1)
i++;
else
valid = 0;
break;
}
case CommandSegmentStart: // initial segment number
{
if((sscanf(argv[i + 1], "%u", &state->segmentNumber) == 1) && (!state->segmentWrap || (state->segmentNumber <= state->segmentWrap)))
i++;
else
valid = 0;
break;
}
case CommandSplitWait: // split files on restart
{
// Must enable inline headers for this to work
state->bInlineHeaders = 1;
state->splitWait = 1;
break;
}
case CommandCircular:
{
state->bCircularBuffer = 1;
break;
}
case CommandIMV: // output filename
{
state->inlineMotionVectors = 1;
int len = strlen(argv[i + 1]);
if (len)
{
state->imv_filename = malloc(len + 1);
vcos_assert(state->imv_filename);
if (state->imv_filename)
strncpy(state->imv_filename, argv[i + 1], len+1);
i++;
}
else
valid = 0;
break;
}
case CommandIntraRefreshType:
{
state->intra_refresh_type = raspicli_map_xref(argv[i + 1], intra_refresh_map, intra_refresh_map_size);
i++;
break;
}
case CommandFlush:
{
state->callback_data.flush_buffers = 1;
break;
}
case CommandSavePTS: // output filename
{
state->save_pts = 1;
int len = strlen(argv[i + 1]);
if (len)
{
state->pts_filename = malloc(len + 1);
vcos_assert(state->pts_filename);
if (state->pts_filename)
strncpy(state->pts_filename, argv[i + 1], len+1);
i++;
}
else
valid = 0;
break;
}
case CommandCodec: // codec type
{
int len = strlen(argv[i + 1]);
if (len)
{
if (len==4 && !strncmp("H264", argv[i+1], 4))
state->encoding = MMAL_ENCODING_H264;
else if (len==5 && !strncmp("MJPEG", argv[i+1], 5))
state->encoding = MMAL_ENCODING_MJPEG;
else
valid = 0;
i++;
}
else
valid = 0;
break;
}
case CommandLevel: // H264 level
{
state->level = raspicli_map_xref(argv[i + 1], level_map, level_map_size);
if( state->level == -1)
state->level = MMAL_VIDEO_LEVEL_H264_4;
i++;
break;
}
case CommandRaw: // output filename
{
state->raw_output = 1;
//state->raw_output_fmt defaults to 0 / yuv
int len = strlen(argv[i + 1]);
if (len)
{
state->raw_filename = malloc(len + 1);
vcos_assert(state->raw_filename);
if (state->raw_filename)
strncpy(state->raw_filename, argv[i + 1], len+1);
i++;
}
else
valid = 0;
break;
}
case CommandRawFormat:
{
state->raw_output_fmt = raspicli_map_xref(argv[i + 1], raw_output_fmt_map, raw_output_fmt_map_size);
if (state->raw_output_fmt == -1)
valid = 0;
i++;
break;
}
case CommandNetListen:
{
state->netListen = true;
break;
}
case CommandSlices:
{
if ((sscanf(argv[i + 1], "%d", &state->slices) == 1) && (state->slices > 0))
i++;
else
valid = 0;
break;
}
case CommandSPSTimings:
{
state->addSPSTiming = MMAL_TRUE;
break;
}
default:
{
// Try parsing for any image specific parameters
// result indicates how many parameters were used up, 0,1,2
// but we adjust by -1 as we have used one already
const char *second_arg = (i + 1 < argc) ? argv[i + 1] : NULL;
int parms_used = (raspicamcontrol_parse_cmdline(&state->camera_parameters, &argv[i][1], second_arg));
// Still unused, try common settings
if (!parms_used)
parms_used = raspicommonsettings_parse_cmdline(&state->common_settings, &argv[i][1], second_arg, &application_help_message);
// Still unused, try preview options
if (!parms_used)
parms_used = raspipreview_parse_cmdline(&state->preview_parameters, &argv[i][1], second_arg);
// If no parms were used, this must be a bad parameter
if (!parms_used)
valid = 0;
else
i += parms_used - 1;
break;
}
}
}
if (!valid)
{
fprintf(stderr, "Invalid command line option (%s)\n", argv[i-1]);
return 1;
}
return 0;
}
/**
* Open a file based on the settings in state
*
* @param state Pointer to state
*/
static FILE *open_filename(RASPIVID_STATE *pState, char *filename)
{
FILE *new_handle = NULL;
char *tempname = NULL;
if (pState->segmentSize || pState->splitWait)
{
// Create a new filename string
//If %d/%u or any valid combination e.g. %04d is specified, assume segment number.
bool bSegmentNumber = false;
const char* pPercent = strchr(filename, '%');
if (pPercent)
{
pPercent++;
while (isdigit(*pPercent))
pPercent++;
if (*pPercent == 'u' || *pPercent == 'd')
bSegmentNumber = true;
}
if (bSegmentNumber)
{
asprintf(&tempname, filename, pState->segmentNumber);
}
else
{
char temp_ts_str[100];
time_t t = time(NULL);
struct tm *tm = localtime(&t);
strftime(temp_ts_str, 100, filename, tm);
asprintf(&tempname, "%s", temp_ts_str);
}