xref: /freebsd/usr.sbin/fwcontrol/fwmpegts.c (revision 4f52dfbb)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (C) 2005
5  * 	Petr Holub, Hidetoshi Shimokawa. All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *
18  *	This product includes software developed by Hidetoshi Shimokawa.
19  *
20  * 4. Neither the name of the author nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * $FreeBSD$
37  */
38 #include <sys/param.h>
39 #include <sys/ioctl.h>
40 #include <sys/time.h>
41 #include <sys/types.h>
42 #include <sys/uio.h>
43 
44 #if __FreeBSD_version >= 500000
45 #include <arpa/inet.h>
46 #endif
47 
48 #include <err.h>
49 #include <errno.h>
50 #include <unistd.h>
51 #include <fcntl.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <sysexits.h>
56 
57 #if defined(__FreeBSD__)
58 #include <dev/firewire/firewire.h>
59 #include <dev/firewire/iec68113.h>
60 #elif defined(__NetBSD__)
61 #include <dev/ieee1394/firewire.h>
62 #include <dev/ieee1394/iec68113.h>
63 #else
64 #warning "You need to add support for your OS"
65 #endif
66 
67 
68 #include "fwmethods.h"
69 
70 #define	DEBUG 0
71 
72 /*****************************************************************************
73 
74 MPEG-2 Transport Stream (MPEG TS) packet format according to IEC 61883:
75 
76 31                              15                             0
77 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  --------
78 |           len                 |tag|  channel  | tcode |  sy   |
79 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+    1394
80 |                           header_CRC                          |
81 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  --------
82 |0|0|    sid    |      dbs      |fn | qpc |S|RSV|       dbc     |
83 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+    CIP
84 |1|0|    fmt    |      fdf      |          fdf/syt              |
85 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  --------
86 |   reserved  |        cycle_count      |      cycle_offset     |
87 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
88 |                                                               |    N x
89 .                                                               .    MPEG
90 .                   MPEG TS payload 188 bytes                   .
91 .                                                               .
92 |                                                               |
93 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  --------
94 |                            data_CRC                           |
95 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
96 
97 N.b. that CRCs are removed by firewire layer!
98 
99 The following fields are fixed for IEEE-1394:
100 tag = 01b
101 tcode = 1010b
102 The length is payload length, i.e. includes CIP header and data size.
103 
104 The following fields are constant for MPEG TS:
105 sph = 1 (denoted as S in CIP header above)
106 dbs = 6
107 fmt = (1<<5)
108 fdf = reserved
109 In the supported streams we also require
110 qpc = 0
111 fn = 3
112 and thus the payload is divided in 8 blocks as follows:
113 
114   +-----+-----+-----+-----+-----+-----+-----+-----+
115   | db0 | db1 | db2 | db3 | db4 | db5 | db6 | db7 |
116   +-----+-----+-----+-----+-----+-----+-----+-----+
117 
118 We have several cases of payload distribution based on stream
119 bandwidth (R):
120 1) R < 1.5 Mbps: any of db0..db7 may be payload,
121 2) 1.5 < R < 3 Mbps: db0/db1 or db2/db3 or db4/db5 or db6/db7 is payload,
122 3) 3 < R < 6 Mbps: db0/db1/db2/db3 or db4/db5/db6/db7 is payload,
123 4) R > 6 Mbps: all db0..db7 contain the payload.
124 Currently, only case (4) is supported in fwmpegts.c
125 
126 Each packet may contain N  MPEG TS data blocks with timestamp header,
127 which are (4+188)B long. Experimentally, the N ranges from 0 through 3.
128 
129 *****************************************************************************/
130 
131 
132 typedef uint8_t mpeg_ts_pld[188];
133 
134 struct mpeg_pldt {
135 #if BYTE_ORDER == BIG_ENDIAN
136 	uint32_t	:7,
137 				c_count:13,
138 				c_offset:12;
139 #else /* BYTE_ORDER != BIG_ENDIAN */
140 	uint32_t	c_offset:12,
141 				c_count:13,
142 				:7;
143 #endif /* BYTE_ORDER == BIG_ENDIAN */
144 	mpeg_ts_pld payload;
145 };
146 
147 
148 #define	NCHUNK 8
149 #define	PSIZE 596
150 #define	NPACKET_R 4096
151 #define	RBUFSIZE (PSIZE * NPACKET_R)
152 
153 void
154 mpegtsrecv(int d, const char *filename, char ich, int count)
155 {
156 	struct ciphdr *ciph;
157 	struct fw_isochreq isoreq;
158 	struct fw_isobufreq bufreq;
159 	struct fw_pkt *pkt;
160 	struct mpeg_pldt *pld;
161 	uint32_t *ptr;
162 	int fd, k, len, m, pkt_size, startwr, tlen;
163 	char *buf;
164 
165 	startwr = 0;
166 
167 	if (strcmp(filename, "-") == 0)
168 		fd = STDOUT_FILENO;
169 	else {
170 		fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0660);
171 		if (fd == -1)
172 			err(EX_NOINPUT, "%s", filename);
173 	}
174 	buf = malloc(RBUFSIZE);
175 
176 	bufreq.rx.nchunk = NCHUNK;
177 	bufreq.rx.npacket = NPACKET_R;
178 	bufreq.rx.psize = PSIZE;
179 	bufreq.tx.nchunk = 0;
180 	bufreq.tx.npacket = 0;
181 	bufreq.tx.psize = 0;
182 	if (ioctl(d, FW_SSTBUF, &bufreq) < 0)
183 		err(1, "ioctl");
184 
185 	isoreq.ch = ich & 0x3f;
186 	isoreq.tag = (ich >> 6) & 3;
187 
188 	if (ioctl(d, FW_SRSTREAM, &isoreq) < 0)
189 		err(1, "ioctl");
190 
191 	k = m = 0;
192 	while (count <= 0 || k <= count) {
193 		len = tlen = read(d, buf, RBUFSIZE);
194 #if DEBUG
195 		fprintf(stderr, "Read %d bytes.\n", len);
196 #endif /* DEBUG */
197 		if (len < 0) {
198 			if (errno == EAGAIN) {
199 				fprintf(stderr, "(EAGAIN) - push 'Play'?\n");
200 				continue;
201 			}
202 			err(1, "read failed");
203 		}
204 		ptr = (uint32_t *) buf;
205 
206 		do {
207 			pkt = (struct fw_pkt *) ptr;
208 #if DEBUG
209 			fprintf(stderr, "\nReading new packet.\n");
210 			fprintf(stderr, "%08x %08x %08x %08x\n",
211 				htonl(ptr[0]), htonl(ptr[1]),
212 				htonl(ptr[2]), htonl(ptr[3]));
213 #endif /* DEBUG */
214 			/* there is no CRC in the 1394 header */
215 			ciph = (struct ciphdr *)(ptr + 1);	/* skip iso header */
216 			if (ciph->fmt != CIP_FMT_MPEG)
217 				errx(1, "unknown format 0x%x", ciph->fmt);
218 			if (ciph->fn != 3) {
219 				errx(1,
220 						"unsupported MPEG TS stream, fn=%d (only fn=3 is supported)",
221 						ciph->fn);
222 			}
223 			ptr = (uint32_t *) (ciph + 1);		/* skip cip header */
224 
225 			if (pkt->mode.stream.len <= sizeof(struct ciphdr)) {
226 				/* no payload */
227 				/* tlen needs to be decremented before end of the loop */
228 				goto next;
229 			}
230 #if DEBUG
231 			else {
232 				fprintf(stderr,
233 						"Packet net payload length (IEEE1394 header): %d\n",
234 						pkt->mode.stream.len - sizeof(struct ciphdr));
235 				fprintf(stderr, "Data block size (CIP header): %d [q], %d [B]\n",
236 						ciph->len, ciph->len * 4);
237 				fprintf(stderr,
238 						"Data fraction number (CIP header): %d => DBC increments with %d\n",
239 						ciph->fn, (1<<ciph->fn) );
240 				fprintf(stderr, "QCP (CIP header): %d\n", ciph->qpc );
241 				fprintf(stderr, "DBC counter (CIP header): %d\n", ciph->dbc );
242 				fprintf(stderr, "MPEG payload type size: %d\n",
243 						sizeof(struct mpeg_pldt));
244 			}
245 #endif /* DEBUG */
246 
247 			/* This is a condition that needs to be satisfied to start
248 			   writing the data */
249 			if (ciph->dbc % (1<<ciph->fn) == 0)
250 				startwr = 1;
251 			/* Read out all the MPEG TS data blocks from current packet */
252 			for (pld = (struct mpeg_pldt *)ptr;
253 			    (intptr_t)pld < (intptr_t)((char *)ptr +
254 			    pkt->mode.stream.len - sizeof(struct ciphdr));
255 			    pld++) {
256 				if (startwr == 1)
257 					write(fd, pld->payload,
258 					    sizeof(pld->payload));
259 			}
260 
261 next:
262 			/* CRCs are removed from both header and trailer
263 			so that only 4 bytes of 1394 header remains */
264 			pkt_size = pkt->mode.stream.len + 4;
265 			ptr = (uint32_t *)((intptr_t)pkt + pkt_size);
266 			tlen -= pkt_size;
267 		} while (tlen > 0);
268 #if DEBUG
269 		fprintf(stderr, "\nReading a data from firewire.\n");
270 #endif /* DEBUG */
271 
272 	}
273 	if (fd != STDOUT_FILENO)
274 		close(fd);
275 	fprintf(stderr, "\n");
276 }
277