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