-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuvc.c
1930 lines (1724 loc) · 76.2 KB
/
uvc.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
/*
## Cypress FX3 Camera Kit Source file (uvc.c)
## ===========================
##
## Copyright Cypress Semiconductor Corporation, 2010-2012,
## All Rights Reserved
## UNPUBLISHED, LICENSED SOFTWARE.
##
## CONFIDENTIAL AND PROPRIETARY INFORMATION
## WHICH IS THE PROPERTY OF CYPRESS.
##
## Use of this file is governed
## by the license agreement included in the file
##
## <install>/license/license.txt
##
## where <install> is the Cypress software
## installation root directory path.
##
## ===========================
*/
/* This project implements a USB Video Class device that streams uncompressed video
data from an image sensor to a USB host PC.
Please refer to the Cypress Application Note: "AN75779: Interfacing an Image
Sensor to EZ-USB FX3 in a USB video class (UVC) Framework" (http://www.cypress.com/?rID=62824)
for a detailed design description of this application.
As the UVC class driver on Windows hosts does not support burst enabled Isochronous
endpoints on USB 3.0, this implementation makes use of Bulk endpoints for the video
streaming.
Two video formats are supported when the system functions on a USB 3.0 link:
1. 720p (1280 * 720) video at 30 fps
2. VGA (640 * 480) video at 15 fps
Only the VGA video stream is supported on a USB 2.0 link, due to bandwidth limitations.
The video streaming is accomplished with the help of a many-to-one manual DMA channel.
Two producer sockets are used to receive data on the GPIF side to prevent data loss. The
data is aggregated into one pipe and sent to the USB host over a bulk endpoint; after the
addition of appropriate UVC headers.
This firmware application makes use of two threads:
1. The video streaming thread is responsible for handling the USB video streaming.
If the UVC host has enabled video streaming, this thread continuously waits for
a filled buffer, adds the appropriate UVC headers and commits the data. This
thread also ensures the DMA multi-channel is reset and restarted at the end of
each video frame. This thread is only idle when the UVC host has not enable video
streaming.
2. The UVC control thread handles UVC class specific requests that arrive on the
control endpoint. The USB setup callback sets up events to notify this thread that
a request has been received, and the thread handles them as soon as possible.
*/
#include <cyu3system.h>
#include <cyu3os.h>
#include <cyu3dma.h>
#include <cyu3error.h>
#include <cyu3usb.h>
#include <cyu3uart.h>
#include <cyu3gpif.h>
#include <cyu3i2c.h>
#include <cyu3gpio.h>
#include <cyu3pib.h>
#include <cyu3utils.h>
#include <cyu3socket.h>
#include "uvc.h"
#include "util.h"
#include "appi2c.h"
#include "app_error_handler.h"
#include "sensor.h"
#include "serdes.h"
#include "auxiliary.h"
#include "camera_ptzcontrol.h"
#include "cyfxgpif2config.h"
/*************************************************************************************************
Global Variables
*************************************************************************************************/
static CyU3PThread uvcAppThread; /* UVC video streaming thread. */
static CyU3PThread uvcAppEP0Thread; /* UVC control request handling thread. */
static CyU3PEvent glFxUVCEvent; /* Event group used to signal threads. */
CyU3PDmaMultiChannel glChHandleUVCStream; /* DMA multi-channel handle. */
/* Current UVC control request fields. See USB specification for definition. */
uint8_t bmReqType, bRequest; /* bmReqType and bRequest fields. */
uint16_t wValue, wIndex, wLength; /* wValue, wIndex and wLength fields. */
CyU3PUSBSpeed_t usbSpeed = CY_U3P_NOT_CONNECTED; /* Current USB connection speed. */
CyBool_t streamingStarted = CyFalse; /* Whether USB host has started streaming data */
CyBool_t glIsApplnActive = CyFalse; /* When CLEAR_FEATURE (stop streaming) request is sent this variable is reset and set when start
streaming request is sent by Host. This is used during commit buffer failure event. */
static CyBool_t glIsConfigured = CyFalse; /* Whether Application is in configured state or not */
/* Mac OS does not send EP Clear feature when the app is closed. It just stops issuing IN tokens. So buffer commit failures
* can be counted and if it reaches beyond a limit, streaming can be stopped. Buffer commit failure code can be cleared
* on DMA Consumer event so that the limit is not reached under streaming conditions. */
static uint8_t glCommitBufferFailureCount = 0;
/*Variable to track whether the reason for DMA Reset is Frame Timer overflow or Commit Buffer Failure*/
static uint8_t glDmaResetFlag = CY_FX_UVC_DMA_RESET_EVENT_NOT_ACTIVE;
static uint8_t glUvcVcErrorCode = CY_FX_UVC_VC_ERROR_CODE_NO_ERROR;
#ifdef FRAME_TIMER_ENABLE
/* Maximum frame transfer time in milli-seconds. The value is updated for every resolution and frame rate.
* Note: The value should always be greater than the frame blanking period */
uint16_t glFrameTimerPeriod = CY_FX_UVC_FRAME_TIMER_VAL_200MS;
/* Timer used to track frame transfer time. */
static CyU3PTimer UvcTimer;
/* Frame timer overflow call back function */
static void CyFxUvcAppProgressTimer(uint32_t arg)
{
if(glDmaResetFlag == CY_FX_UVC_DMA_RESET_EVENT_NOT_ACTIVE)
{
glDmaResetFlag = CY_FX_UVC_DMA_RESET_FRAME_TIMER_OVERFLOW;
CyU3PEventSet(&glFxUVCEvent, CY_FX_UVC_DMA_RESET_EVENT, CYU3P_EVENT_OR);
}
}
#endif
#ifdef BACKFLOW_DETECT
uint8_t back_flow_detected = 0; /* Whether buffer overflow error is detected. */
#endif
#ifdef USB_DEBUG_INTERFACE
CyU3PDmaChannel glDebugCmdChannel; /* Channel to receive debug commands on. */
CyU3PDmaChannel glDebugRspChannel; /* Channel to send debug responses on. */
uint8_t *glDebugRspBuffer; /* Buffer used to send debug responses. */
#endif
/* UVC Probe Control Settings for a USB 3.0 connection. */
uint8_t glProbeCtrl[CY_FX_UVC_MAX_PROBE_SETTING] = {
0x00, 0x00, /* bmHint : no hit */
0x01, /* Use 1st Video format index */
0x01, /* Use 1st Video frame index */
0x07, 0x16, 0x05, 0x00, /* Desired frame interval in the unit of 100ns: 30 fps; changed by JRS*/
0x00, 0x00, /* Key frame rate in key frame/video frame units: only applicable
to video streaming with adjustable compression parameters */
0x00, 0x00, /* PFrame rate in PFrame / key frame units: only applicable to
video streaming with adjustable compression parameters */
0x00, 0x00, /* Compression quality control: only applicable to video streaming
with adjustable compression parameters */
0x00, 0x00, /* Window size for average bit rate: only applicable to video
streaming with adjustable compression parameters */
0x00, 0x00, /* Internal video streaming i/f latency in ms */
PYTHON480_FRAMESIZE_BYTES_30FPS, /* Max video frame size in bytes; Changed by GL*/
0x00, 0x90, 0x00, 0x00, /* No. of bytes device can rx in single payload = 16 KB */
#ifndef FX3_UVC_1_0_SUPPORT
/* UVC 1.1 Probe Control has additional fields from UVC 1.0 */
0x00, 0x60, 0xE3, 0x16, /* Device Clock */
0x00, /* Framing Information - Ignored for uncompressed format*/
0x00, /* Preferred payload format version */
0x00, /* Minimum payload format version */
0x00 /* Maximum payload format version */
#endif
};
/* UVC Probe Control Setting for a USB 2.0 connection. */
uint8_t glProbeCtrl20[CY_FX_UVC_MAX_PROBE_SETTING] = {
0x00, 0x00, /* bmHint : no hit */
0x01, /* Use 1st Video format index */
0x01, /* Use 1st Video frame index */
0x07, 0x16, 0x05, 0x00, /* Desired frame interval in the unit of 100ns: 30 fps; changed by JRS */
0x00, 0x00, /* Key frame rate in key frame/video frame units: only applicable
to video streaming with adjustable compression parameters */
0x00, 0x00, /* PFrame rate in PFrame / key frame units: only applicable to
video streaming with adjustable compression parameters */
0x00, 0x00, /* Compression quality control: only applicable to video streaming
with adjustable compression parameters */
0x00, 0x00, /* Window size for average bit rate: only applicable to video
streaming with adjustable compression parameters */
0x00, 0x00, /* Internal video streaming i/f latency in ms */
PYTHON480_FRAMESIZE_BYTES_30FPS, /* Max video frame size in bytes */
0x00, 0x90, 0x00, 0x00, /* No. of bytes device can rx in single payload = 16 KB */
#ifndef FX3_UVC_1_0_SUPPORT
/* UVC 1.1 Probe Control has additional fields from UVC 1.0 */
0x00, 0x60, 0xE3, 0x16, /* Device Clock */
0x00, /* Framing Information - Ignored for uncompressed format*/
0x00, /* Preferred payload format version */
0x00, /* Minimum payload format version */
0x00 /* Maximum payload format version */
#endif
};
/* Video Probe Commit Control. This array is filled out when the host sends down the SET_CUR request. */
static uint8_t glCommitCtrl[CY_FX_UVC_MAX_PROBE_SETTING_ALIGNED];
/* Scratch buffer used for handling UVC class requests with a data phase. */
static uint8_t glEp0Buffer[32];
/* UVC Header to be prefixed at the top of each 16 KB video data buffer. */
uint8_t volatile glUVCHeader[CY_FX_UVC_MAX_HEADER] =
{
0x0C, /* Header Length */
0x8C, /* Bit field header field */
0x00, 0x00, 0x00, 0x00, /* Presentation time stamp field */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* Source clock reference field */
};
#ifdef UVC_EXTENSION_UNIT
/* Format is: Version 1.0 (Major.Minor) Build date: 9/10/17 (MM/DD/YY) */
static uint8_t glFxUvcFirmwareVersion[5] = {
1, /* Major version */
0, /* Minor version */
9, /* Build month */
22, /* Build day */
17 /* Build Year */
};
#endif
#ifdef DEBUG_PRINT_FRAME_COUNT
volatile static uint32_t glFrameCount = 0; /* Number of video frames transferred so far. */
volatile static uint32_t glDmaDone = 1; /* Number of buffers transferred in the current frame. */
#endif
/* Function to handle 'back-channel' communication through saturation control */
static void
handleSaturationCommunication (
uint8_t value)
{
switch(value) {
case SATURATION_RECORD_START:
SensorStart ();
break;
case SATURATION_RECORD_END:
SensorStop ();
break;
case SATURATION_INIT:
SensorInit ();
break;
default:
break;
}
}
/* Add the UVC packet header to the top of the specified DMA buffer. */
void
CyFxUVCAddHeader (
uint8_t *buffer_p, /* Buffer pointer */
uint8_t frameInd /* EOF or normal frame indication */
)
{
/* Copy header to buffer */
CyU3PMemCopy (buffer_p, (uint8_t *)glUVCHeader, CY_FX_UVC_MAX_HEADER);
/* The EOF flag needs to be set if this is the last packet for this video frame. */
if (frameInd & CY_FX_UVC_HEADER_EOF)
{
buffer_p[1] |= CY_FX_UVC_HEADER_EOF;
glUVCHeader[1] ^= CY_FX_UVC_HEADER_FRAME_ID;
}
}
/* This function performs the operations for a Video Streaming Abort.
This is called every time there is a USB reset, suspend or disconnect event.
*/
static void
CyFxUVCApplnAbortHandler (
void)
{
/* Set Video Stream Abort Event */
CyU3PEventSet (&glFxUVCEvent, CY_FX_UVC_STREAM_ABORT_EVENT, CYU3P_EVENT_OR);
}
/* This is the Callback function to handle the USB Events */
static void
CyFxUVCApplnUSBEventCB (
CyU3PUsbEventType_t evtype, /* Event type */
uint16_t evdata /* Event data */
)
{
switch (evtype)
{
case CY_U3P_USB_EVENT_SUSPEND:
CyU3PDebugPrint (4, "UsbEventCB: SUSPEND encountered...\r\n");
/* Set USB suspend Event */
CyU3PEventSet (&glFxUVCEvent, CY_FX_USB_SUSPEND_EVENT_HANDLER, CYU3P_EVENT_OR);
break;
case CY_U3P_USB_EVENT_EP_UNDERRUN:
CyU3PDebugPrint (4, "UsbEventCB: CY_U3P_USB_EVENT_EP_UNDERRUN encountered...\r\n");
break;
/* Intentional Fall-through all cases */
case CY_U3P_USB_EVENT_SETCONF:
if (CyU3PUsbGetSpeed() == CY_U3P_SUPER_SPEED)
{
CyU3PDebugPrint(4, "UsbEventCB: Detected SS USB Connection\r\n");
}
else if (CyU3PUsbGetSpeed() == CY_U3P_HIGH_SPEED)
{
CyU3PDebugPrint(4, "UsbEventCB: Detected HS USB Connection\r\n");
}
case CY_U3P_USB_EVENT_RESET:
case CY_U3P_USB_EVENT_DISCONNECT:
case CY_U3P_USB_EVENT_CONNECT:
if (evtype == CY_U3P_USB_EVENT_SETCONF)
glIsConfigured = CyTrue;
else
glIsConfigured = CyFalse;
/* Stop the video streamer application and enable LPM. */
CyU3PUsbLPMEnable();
if (glIsApplnActive)
{
CyU3PDebugPrint(4, "UsbEventCB: Call App Stop\r\n");
CyFxUVCApplnAbortHandler();
}
break;
default:
break;
}
}
/* Callback to handle the USB Setup Requests and UVC Class events */
static CyBool_t
CyFxUVCApplnUSBSetupCB (
uint32_t setupdat0, /* SETUP Data 0 */
uint32_t setupdat1 /* SETUP Data 1 */
)
{
CyBool_t uvcHandleReq = CyFalse;
uint32_t status;
/* Obtain Request Type and Request */
bmReqType = (uint8_t)(setupdat0 & CY_FX_USB_SETUP_REQ_TYPE_MASK);
bRequest = (uint8_t)((setupdat0 & CY_FX_USB_SETUP_REQ_MASK) >> 8);
wValue = (uint16_t)((setupdat0 & CY_FX_USB_SETUP_VALUE_MASK) >> 16);
wIndex = (uint16_t)(setupdat1 & CY_FX_USB_SETUP_INDEX_MASK);
wLength = (uint16_t)((setupdat1 & CY_FX_USB_SETUP_LENGTH_MASK) >> 16);
/* Check for UVC Class Requests */
switch (bmReqType)
{
case CY_FX_USB_UVC_GET_REQ_TYPE:
case CY_FX_USB_UVC_SET_REQ_TYPE:
/* UVC Specific requests are handled in the EP0 thread. */
switch (wIndex & 0xFF)
{
case CY_FX_UVC_CONTROL_INTERFACE:
{
uvcHandleReq = CyTrue;
status = CyU3PEventSet (&glFxUVCEvent, CY_FX_UVC_VIDEO_CONTROL_REQUEST_EVENT,
CYU3P_EVENT_OR);
if (status != CY_U3P_SUCCESS)
{
CyU3PDebugPrint (4, "Set CY_FX_UVC_VIDEO_CONTROL_REQUEST_EVENT Failed %x\r\n", status);
CyU3PUsbStall (0, CyTrue, CyFalse);
}
}
break;
case CY_FX_UVC_STREAM_INTERFACE:
{
uvcHandleReq = CyTrue;
status = CyU3PEventSet (&glFxUVCEvent, CY_FX_UVC_VIDEO_STREAM_REQUEST_EVENT,
CYU3P_EVENT_OR);
if (status != CY_U3P_SUCCESS)
{
/* Error handling */
CyU3PDebugPrint (4, "Set CY_FX_UVC_VIDEO_STREAM_REQUEST_EVENT Failed %x\r\n", status);
CyU3PUsbStall (0, CyTrue, CyFalse);
}
}
break;
default:
break;
}
break;
case CY_FX_USB_SET_INTF_REQ_TYPE:
if (bRequest == CY_FX_USB_SET_INTERFACE_REQ)
{
/* Some hosts send Set Interface Alternate Setting 0 command while stopping the video
* stream. The application uses this event to stop streaming. */
if ((wIndex == CY_FX_UVC_STREAM_INTERFACE) && (wValue == 0))
{
/* Stop GPIF state machine to stop data transfers through FX3 */
CyU3PDebugPrint (4, "Alternate setting 0..\r\n");
/* Clear the stall condition and sequence numbers. */
CyU3PUsbStall (CY_FX_EP_BULK_VIDEO, CyFalse, CyTrue);
CyFxUVCApplnAbortHandler ();
uvcHandleReq = CyTrue;
/* Complete Control request handshake */
CyU3PUsbAckSetup ();
}
}
else if ((bRequest == CY_U3P_USB_SC_SET_FEATURE) || (bRequest == CY_U3P_USB_SC_CLEAR_FEATURE))
{
CyU3PDebugPrint(4, "USBSetupCB:In SET_FTR %d::%d\r\n", glIsApplnActive, glIsConfigured);
if (glIsConfigured)
{
uvcHandleReq = CyTrue;
CyU3PUsbAckSetup ();
}
}
break;
case CY_U3P_USB_TARGET_ENDPT:
if (bRequest == CY_U3P_USB_SC_CLEAR_FEATURE)
{
if (wIndex == CY_FX_EP_BULK_VIDEO)
{
/* Windows OS sends Clear Feature Request after it stops streaming,
* however MAC OS sends clear feature request right after it sends a
* Commit -> SET_CUR request. Hence, stop the video streaming and clear
* the stall condition and sequence numbers */
CyU3PDebugPrint (4, "Clear feature request detected...\r\n");
/* Clear the stall condition and sequence numbers. */
CyU3PUsbStall (CY_FX_EP_BULK_VIDEO, CyFalse, CyTrue);
CyFxUVCApplnAbortHandler();
uvcHandleReq = CyTrue;
/* Complete Control request handshake */
CyU3PUsbAckSetup ();
}
}
break;
default:
break;
}
/* Return status of request handling to the USB driver */
return uvcHandleReq;
}
/* DMA callback providing notification when data buffers are received from the sensor and when they have
* been drained by the USB host.
*
* The UVC headers are attached to the data, and forwarded to the USB host in this callback function.
*/
void
CyFxUvcApplnDmaCallback (
CyU3PDmaMultiChannel *chHandle,
CyU3PDmaCbType_t type,
CyU3PDmaCBInput_t *input
)
{
CyU3PDmaBuffer_t dmaBuffer;
CyU3PReturnStatus_t status = CY_U3P_SUCCESS;
if (type == CY_U3P_DMA_CB_PROD_EVENT)
{
/* This is a produce event notification to the CPU. This notification is received upon reception of
* every buffer. The buffer will not be sent out unless it is explicitly committed. The call shall fail
* if there is a bus reset / usb disconnect or if there is any application error.
*/
#ifdef FRAME_TIMER_ENABLE
/* Received data from the sensor so stop the frame timer */
CyU3PTimerStop(&UvcTimer);
/* Restart the frame timer so that we receive the next buffer before timer overflows */
CyU3PTimerModify(&UvcTimer, glFrameTimerPeriod, 0);
CyU3PTimerStart(&UvcTimer);
#endif
/* There is a possibility that CyU3PDmaMultiChannelGetBuffer will return CY_U3P_ERROR_INVALID_SEQUENCE here.
* In such a case, do nothing. We make up for this missed produce event by making repeated commit actions
* in subsequent produce event callbacks.
*/
status = CyU3PDmaMultiChannelGetBuffer (chHandle, &dmaBuffer, CYU3P_NO_WAIT);
while (status == CY_U3P_SUCCESS)
{
/* Add Headers*/
if (dmaBuffer.count == CY_FX_UVC_BUF_FULL_SIZE)
{
/* A full buffer indicates there is more data to go in this video frame. */
CyFxUVCAddHeader (dmaBuffer.buffer - CY_FX_UVC_MAX_HEADER, CY_FX_UVC_HEADER_FRAME);
}
else
{
/* A partially filled buffer indicates the end of the ongoing video frame. */
CyFxUVCAddHeader (dmaBuffer.buffer - CY_FX_UVC_MAX_HEADER, CY_FX_UVC_HEADER_EOF);
#ifdef DEBUG_PRINT_FRAME_COUNT
glFrameCount++;
glDmaDone = 0;
#endif
}
/* Commit Buffer to USB*/
status = CyU3PDmaMultiChannelCommitBuffer (chHandle, (dmaBuffer.count + CY_FX_UVC_MAX_HEADER), 0);
if (status == CY_U3P_SUCCESS)
{
#ifdef DEBUG_PRINT_FRAME_COUNT
glDmaDone++;
#endif
}
else
{
if(glDmaResetFlag == CY_FX_UVC_DMA_RESET_EVENT_NOT_ACTIVE)
{
glDmaResetFlag = CY_FX_UVC_DMA_RESET_COMMIT_BUFFER_FAILURE;
CyU3PEventSet(&glFxUVCEvent, CY_FX_UVC_DMA_RESET_EVENT, CYU3P_EVENT_OR);
}
break;
}
/* Check if any more buffers are ready to go, and commit them here. */
status = CyU3PDmaMultiChannelGetBuffer (chHandle, &dmaBuffer, CYU3P_NO_WAIT);
}
}
else if (type == CY_U3P_DMA_CB_CONS_EVENT)
{
streamingStarted = CyTrue;
glCommitBufferFailureCount = 0; /* Reset the counter after data is consumed by USB */
}
}
/* GpifCB callback function is invoked when FV triggers GPIF interrupt */
void
CyFxGpifCB (
uint8_t currentState /* GPIF state which triggered the interrupt. */
)
{
/* The ongoing video frame has ended. If we have a partial buffer sitting on the socket, we need to forcibly
* wrap it up. We also need to toggle the FW_TRG a couple of times to get the state machine ready for the
* next frame.
*
* Note: DMA channel APIs cannot be used here as this is ISR context. We are making use of the raw socket
* APIs.
*/
switch (currentState)
{
case PARTIAL_BUF_IN_SCK0:
CyU3PDmaSocketSetWrapUp (CY_U3P_PIB_SOCKET_0);
break;
case FULL_BUF_IN_SCK0:
break;
case PARTIAL_BUF_IN_SCK1:
CyU3PDmaSocketSetWrapUp (CY_U3P_PIB_SOCKET_1);
break;
case FULL_BUF_IN_SCK1:
break;
default:
/* This should not happen. Do nothing. */
return;
}
CyU3PGpifControlSWInput (CyTrue);
CyU3PGpifControlSWInput (CyFalse);
}
/* This function initializes the Debug Module for the UVC Application */
static void
CyFxUVCApplnDebugInit (
void)
{
CyU3PUartConfig_t uartConfig;
CyU3PReturnStatus_t apiRetStatus;
/* Initialize the UART for printing debug messages */
apiRetStatus = CyU3PUartInit ();
if (apiRetStatus != CY_U3P_SUCCESS)
{
CyU3PDebugPrint (4, "UART initialization failed!\n");
CyFxAppErrorHandler (apiRetStatus);
}
/* Set UART Configuration */
uartConfig.baudRate = CY_U3P_UART_BAUDRATE_19200;
uartConfig.stopBit = CY_U3P_UART_ONE_STOP_BIT;
uartConfig.parity = CY_U3P_UART_NO_PARITY;
uartConfig.txEnable = CyTrue;
uartConfig.rxEnable = CyFalse;
uartConfig.flowCtrl = CyFalse;
uartConfig.isDma = CyTrue;
/* Set the UART configuration */
apiRetStatus = CyU3PUartSetConfig (&uartConfig, NULL);
if (apiRetStatus != CY_U3P_SUCCESS)
{
CyFxAppErrorHandler (apiRetStatus);
}
/* Set the UART transfer */
apiRetStatus = CyU3PUartTxSetBlockXfer (0xFFFFFFFF);
if (apiRetStatus != CY_U3P_SUCCESS)
{
CyFxAppErrorHandler (apiRetStatus);
}
/* Initialize the Debug logger module. */
apiRetStatus = CyU3PDebugInit (CY_U3P_LPP_SOCKET_UART_CONS, 4);
if (apiRetStatus != CY_U3P_SUCCESS)
{
CyFxAppErrorHandler (apiRetStatus);
}
/* Disable log message headers. */
CyU3PDebugPreamble (CyFalse);
}
#ifdef BACKFLOW_DETECT
static void CyFxUvcAppPibCallback (
CyU3PPibIntrType cbType,
uint16_t cbArg)
{
if ((cbType == CYU3P_PIB_INTR_ERROR) && ((cbArg == 0x1005) || (cbArg == 0x1006)))
{
if (!back_flow_detected)
{
CyU3PDebugPrint (4, "Backflow detected...\r\n");
back_flow_detected = 1;
}
}
}
#endif
#ifdef USB_DEBUG_INTERFACE
static void
CyFxUvcAppDebugCallback (
CyU3PDmaChannel *handle,
CyU3PDmaCbType_t type,
CyU3PDmaCBInput_t *input)
{
if (type == CY_U3P_DMA_CB_PROD_EVENT)
{
/* Data has been received. Notify the EP0 thread which handles the debug commands as well. */
CyU3PEventSet (&glFxUVCEvent, CY_FX_USB_DEBUG_CMD_EVENT, CYU3P_EVENT_OR);
}
}
#endif
/*
* Load the GPIF configuration on the GPIF-II engine. This operation is performed at start-up.
*/
static void
CyFxUvcAppGpifInit (
void)
{
CyU3PReturnStatus_t apiRetStatus;
apiRetStatus = CyU3PGpifLoad ((CyU3PGpifConfig_t *) &CyFxGpifConfig);
if (apiRetStatus != CY_U3P_SUCCESS)
{
/* Error Handling */
CyU3PDebugPrint (4, "Loading GPIF Configuration failed, Error Code = %d\r\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}
}
/* Callback for LPM requests. Always return true to allow host to transition device
* into required LPM state U1/U2/U3. When data transmission is active LPM management
* is explicitly disabled to prevent data transmission errors.
*/
static CyBool_t
CyFxUVCAppLPMRqtCB (
CyU3PUsbLinkPowerMode link_mode /*USB 3.0 linkmode requested by Host */
)
{
return CyTrue;
}
/* This function initializes the USB Module, creates event group,
sets the enumeration descriptors, configures the Endpoints and
configures the DMA module for the UVC Application */
static void
CyFxUVCApplnInit (void)
{
CyU3PDmaMultiChannelConfig_t dmaMultiConfig;
CyU3PEpConfig_t endPointConfig;
CyU3PReturnStatus_t apiRetStatus;
CyU3PPibClock_t pibclock;
#ifdef USB_DEBUG_INTERFACE
CyU3PDmaChannelConfig_t channelConfig;
#endif
/* Create UVC event group */
apiRetStatus = CyU3PEventCreate (&glFxUVCEvent);
if (apiRetStatus != 0)
{
CyU3PDebugPrint (4, "UVC Create Event failed, Error Code = %d\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}
#ifdef UVC_PTZ_SUPPORT
CyFxUvcAppPTZInit ();
#endif
/* Initialize the P-port. */
pibclock.clkDiv = 2;
pibclock.clkSrc = CY_U3P_SYS_CLK;
pibclock.isDllEnable = CyFalse;
pibclock.isHalfDiv = CyFalse;
apiRetStatus = CyU3PPibInit (CyTrue, &pibclock);
if (apiRetStatus != CY_U3P_SUCCESS)
{
CyU3PDebugPrint (4, "PIB Function Failed to Start, Error Code = %d\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}
CyFxUvcAppGpifInit ();
/* Register the GPIF State Machine callback used to get frame end notifications.
* We use the fast callback version which is triggered from ISR context.
*/
CyU3PGpifRegisterSMIntrCallback (CyFxGpifCB);
#ifdef BACKFLOW_DETECT
back_flow_detected = 0;
CyU3PPibRegisterCallback (CyFxUvcAppPibCallback, CYU3P_PIB_INTR_ERROR);
#endif
/* Image sensor initialization. Reset and then initialize with appropriate configuration. */
SensorConfigureSerdes ();
apiRetStatus = SensorDisable ();
if (apiRetStatus == CY_U3P_SUCCESS) {
apiRetStatus = SensorInit ();
}
if (apiRetStatus != CY_U3P_SUCCESS) {
CyU3PDebugPrint (4, "I2C initialization of sensor failed, Error Code = %d\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}
/* USB initialization. */
apiRetStatus = CyU3PUsbStart ();
if (apiRetStatus != CY_U3P_SUCCESS)
{
CyU3PDebugPrint (4, "USB Function Failed to Start, Error Code = %d\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}
/* Setup the Callback to Handle the USB Setup Requests */
CyU3PUsbRegisterSetupCallback (CyFxUVCApplnUSBSetupCB, CyFalse);
/* Setup the Callback to Handle the USB Events */
CyU3PUsbRegisterEventCallback (CyFxUVCApplnUSBEventCB);
/* Register a callback to handle LPM requests from the USB 3.0 host. */
CyU3PUsbRegisterLPMRequestCallback (CyFxUVCAppLPMRqtCB);
/* Register the USB device descriptors with the driver. */
CyU3PUsbSetDesc (CY_U3P_USB_SET_HS_DEVICE_DESCR, 0, (uint8_t *)CyFxUSBDeviceDscr);
CyU3PUsbSetDesc (CY_U3P_USB_SET_SS_DEVICE_DESCR, 0, (uint8_t *)CyFxUSBDeviceDscrSS);
/* BOS and Device qualifier descriptors. */
CyU3PUsbSetDesc (CY_U3P_USB_SET_DEVQUAL_DESCR, 0, (uint8_t *)CyFxUSBDeviceQualDscr);
CyU3PUsbSetDesc (CY_U3P_USB_SET_SS_BOS_DESCR, 0, (uint8_t *)CyFxUSBBOSDscr);
/* Configuration descriptors. */
CyU3PUsbSetDesc (CY_U3P_USB_SET_HS_CONFIG_DESCR, 0, (uint8_t *)CyFxUSBHSConfigDscr);
CyU3PUsbSetDesc (CY_U3P_USB_SET_FS_CONFIG_DESCR, 0, (uint8_t *)CyFxUSBFSConfigDscr);
CyU3PUsbSetDesc (CY_U3P_USB_SET_SS_CONFIG_DESCR, 0, (uint8_t *)CyFxUSBSSConfigDscr);
/* String Descriptors */
CyU3PUsbSetDesc (CY_U3P_USB_SET_STRING_DESCR, 0, (uint8_t *)CyFxUSBStringLangIDDscr);
CyU3PUsbSetDesc (CY_U3P_USB_SET_STRING_DESCR, 1, (uint8_t *)CyFxUSBManufactureDscr);
CyU3PUsbSetDesc (CY_U3P_USB_SET_STRING_DESCR, 2, (uint8_t *)CyFxUSBProductDscr);
/* Configure the video streaming endpoint. */
endPointConfig.enable = 1;
endPointConfig.epType = CY_U3P_USB_EP_BULK;
endPointConfig.pcktSize = CY_FX_EP_BULK_VIDEO_PKT_SIZE;
endPointConfig.isoPkts = 1;
endPointConfig.burstLen = 16;
endPointConfig.streams = 0;
apiRetStatus = CyU3PSetEpConfig (CY_FX_EP_BULK_VIDEO, &endPointConfig);
if (apiRetStatus != CY_U3P_SUCCESS)
{
/* Error Handling */
CyU3PDebugPrint (4, "USB Set Endpoint config failed, Error Code = %d\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}
/* Configure the status interrupt endpoint.
Note: This endpoint is not being used by the application as of now. This can be used in case
UVC device needs to notify the host about any error conditions. A MANUAL_OUT DMA channel
can be associated with this endpoint and used to send these data packets.
*/
endPointConfig.enable = 1;
endPointConfig.epType = CY_U3P_USB_EP_INTR;
endPointConfig.pcktSize = 64;
endPointConfig.isoPkts = 0;
endPointConfig.streams = 0;
endPointConfig.burstLen = 1;
apiRetStatus = CyU3PSetEpConfig (CY_FX_EP_CONTROL_STATUS, &endPointConfig);
if (apiRetStatus != CY_U3P_SUCCESS)
{
/* Error Handling */
CyU3PDebugPrint (4, "USB Set Endpoint config failed, Error Code = %d\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}
/* Create a DMA Manual channel for sending the video data to the USB host. */
dmaMultiConfig.size = CY_FX_UVC_STREAM_BUF_SIZE;
dmaMultiConfig.count = CY_FX_UVC_STREAM_BUF_COUNT;
dmaMultiConfig.validSckCount = 2;
dmaMultiConfig.prodSckId [0] = (CyU3PDmaSocketId_t)CY_U3P_PIB_SOCKET_0;
dmaMultiConfig.prodSckId [1] = (CyU3PDmaSocketId_t)CY_U3P_PIB_SOCKET_1;
dmaMultiConfig.consSckId [0] = (CyU3PDmaSocketId_t)(CY_U3P_UIB_SOCKET_CONS_0 | CY_FX_EP_VIDEO_CONS_SOCKET);
dmaMultiConfig.prodAvailCount = 0;
dmaMultiConfig.prodHeader = 12; /* 12 byte UVC header to be added. */
dmaMultiConfig.prodFooter = 4; /* 4 byte footer to compensate for the 12 byte header. */
dmaMultiConfig.consHeader = 0;
dmaMultiConfig.dmaMode = CY_U3P_DMA_MODE_BYTE;
dmaMultiConfig.notification = CY_U3P_DMA_CB_PROD_EVENT | CY_U3P_DMA_CB_CONS_EVENT;
dmaMultiConfig.cb = CyFxUvcApplnDmaCallback;
apiRetStatus = CyU3PDmaMultiChannelCreate (&glChHandleUVCStream, CY_U3P_DMA_TYPE_MANUAL_MANY_TO_ONE,
&dmaMultiConfig);
if (apiRetStatus != CY_U3P_SUCCESS)
{
/* Error handling */
CyU3PDebugPrint (4, "DMA Channel Creation Failed, Error Code = %d\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}
#ifdef USB_DEBUG_INTERFACE
/* Configure the endpoints and create DMA channels used by the USB debug interface.
The command (OUT) endpoint is configured in packet mode and enabled to receive data.
Once the CY_U3P_DMA_CB_PROD_EVENT callback is received, the received data packet is
processed and the data is returned through the CyU3PDmaChannelSetupSendBuffer API call.
*/
endPointConfig.enable = 1;
endPointConfig.epType = CY_U3P_USB_EP_BULK;
endPointConfig.pcktSize = 1024; /* Use SuperSpeed settings here. */
endPointConfig.isoPkts = 0;
endPointConfig.streams = 0;
endPointConfig.burstLen = 1;
apiRetStatus = CyU3PSetEpConfig (CY_FX_EP_DEBUG_CMD, &endPointConfig);
if (apiRetStatus != CY_U3P_SUCCESS)
{
CyU3PDebugPrint (4, "Debug Command endpoint config failed, Error code = %d\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}
CyU3PUsbSetEpPktMode (CY_FX_EP_DEBUG_CMD, CyTrue);
apiRetStatus = CyU3PSetEpConfig (CY_FX_EP_DEBUG_RSP, &endPointConfig);
if (apiRetStatus != CY_U3P_SUCCESS)
{
CyU3PDebugPrint (4, "Debug Response endpoint config failed, Error code = %d\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}
channelConfig.size = 1024;
channelConfig.count = 1;
channelConfig.prodSckId = CY_U3P_UIB_SOCKET_PROD_0 | CY_FX_EP_DEBUG_CMD_SOCKET;
channelConfig.consSckId = CY_U3P_CPU_SOCKET_CONS;
channelConfig.prodAvailCount = 0;
channelConfig.prodHeader = 0;
channelConfig.prodFooter = 0;
channelConfig.consHeader = 0;
channelConfig.dmaMode = CY_U3P_DMA_MODE_BYTE;
channelConfig.notification = CY_U3P_DMA_CB_PROD_EVENT;
channelConfig.cb = CyFxUvcAppDebugCallback;
apiRetStatus = CyU3PDmaChannelCreate (&glDebugCmdChannel, CY_U3P_DMA_TYPE_MANUAL_IN, &channelConfig);
if (apiRetStatus != CY_U3P_SUCCESS)
{
CyU3PDebugPrint (4, "Debug Command channel create failed, Error code = %d\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}
apiRetStatus = CyU3PDmaChannelSetXfer (&glDebugCmdChannel, 0);
if (apiRetStatus != CY_U3P_SUCCESS)
{
CyU3PDebugPrint (4, "Debug channel SetXfer failed, Error code = %d\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}
channelConfig.size = 1024;
channelConfig.count = 0; /* No buffers allocated. We will only use the SetupSend API. */
channelConfig.prodSckId = CY_U3P_CPU_SOCKET_PROD;
channelConfig.consSckId = CY_U3P_UIB_SOCKET_CONS_0 | CY_FX_EP_DEBUG_RSP_SOCKET;
channelConfig.prodAvailCount = 0;
channelConfig.prodHeader = 0;
channelConfig.prodFooter = 0;
channelConfig.consHeader = 0;
channelConfig.dmaMode = CY_U3P_DMA_MODE_BYTE;
channelConfig.notification = 0;
channelConfig.cb = 0;
apiRetStatus = CyU3PDmaChannelCreate (&glDebugRspChannel, CY_U3P_DMA_TYPE_MANUAL_OUT, &channelConfig);
if (apiRetStatus != CY_U3P_SUCCESS)
{
CyU3PDebugPrint (4, "Debug Response channel create failed, Error code = %d\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}
glDebugRspBuffer = (uint8_t *)CyU3PDmaBufferAlloc (1024);
if (glDebugRspBuffer == 0)
{
CyU3PDebugPrint (4, "Failed to allocate memory for debug buffer\r\n");
CyFxAppErrorHandler (CY_U3P_ERROR_MEMORY_ERROR);
}
#endif
#ifdef FRAME_TIMER_ENABLE
CyU3PTimerCreate(&UvcTimer, CyFxUvcAppProgressTimer, 0x00, glFrameTimerPeriod, 0, CYU3P_NO_ACTIVATE);
#endif
/* Enable USB connection from the FX3 device, preferably at USB 3.0 speed. */
apiRetStatus = CyU3PConnectState (CyTrue, CyTrue);
if (apiRetStatus != CY_U3P_SUCCESS)
{
CyU3PDebugPrint (4, "USB Connect failed, Error Code = %d\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}
}
void
CyFxUvcApplnStop()
{
#ifdef DEBUG_PRINT_FRAME_COUNT
/* Clear state variables. */
glDmaDone = 1;
glFrameCount = 0;
#endif /* DEBUG_PRINT_FRAME_COUNT */
#ifdef FRAME_TIMER_ENABLE
/* Stop the frame timer during an application stop */
CyU3PTimerStop(&UvcTimer);
#endif
/* Disable the GPIF state machine. */
CyU3PGpifDisable (CyFalse);
streamingStarted = CyFalse;
glDmaResetFlag = CY_FX_UVC_DMA_RESET_EVENT_NOT_ACTIVE;
/* Place the EP in NAK mode before cleaning up the pipe. */
CyU3PUsbSetEpNak (CY_FX_EP_BULK_VIDEO, CyTrue);
CyU3PBusyWait (125);
/* Reset and flush the endpoint pipe. */
CyU3PDmaMultiChannelReset (&glChHandleUVCStream);
CyU3PUsbFlushEp (CY_FX_EP_BULK_VIDEO);
CyU3PUsbSetEpNak (CY_FX_EP_BULK_VIDEO, CyFalse);
CyU3PBusyWait (125);
/* Allow USB low power link transitions at this stage. */
CyU3PUsbLPMEnable ();
CyU3PDebugPrint (4, "Application Stopped\r\n");
}
void
CyFxUvcApplnStart()
{
CyU3PReturnStatus_t apiRetStatus;
#ifdef DEBUG_PRINT_FRAME_COUNT
/* Clear state variables. */
glDmaDone = 1;
glFrameCount = 0;
#endif /* DEBUG_PRINT_FRAME_COUNT */
/* Start with frame ID 0. */
glUVCHeader[1] &= ~CY_FX_UVC_HEADER_FRAME_ID;
/* Make sure we return to an active USB link state and stay there. */
CyU3PUsbLPMDisable ();
if (CyU3PUsbGetSpeed () == CY_U3P_SUPER_SPEED)
{
CyU3PUsbSetLinkPowerState (CyU3PUsbLPM_U0);
CyU3PBusyWait (200); /*in microseconds, originally 200 */
}
else
{
CyU3PUsb2Resume ();
}
/* Place the EP in NAK mode before cleaning up the pipe. */
CyU3PUsbSetEpNak (CY_FX_EP_BULK_VIDEO, CyTrue);
CyU3PBusyWait (125); /*in microseconds, originally 125 */
/* Reset and flush the endpoint pipe. */
CyU3PUsbFlushEp (CY_FX_EP_BULK_VIDEO);
CyU3PDmaMultiChannelReset (&glChHandleUVCStream);
/* Set DMA Channel transfer size, first producer socket */
apiRetStatus = CyU3PDmaMultiChannelSetXfer (&glChHandleUVCStream, 0, 0);
if (apiRetStatus != CY_U3P_SUCCESS)
{
/* Error handling */
CyU3PDebugPrint (4, "DMA Channel Set Transfer Failed, Error Code = %d\r\n", apiRetStatus);
CyFxAppErrorHandler (apiRetStatus);
}