1163712Simp/*
2163712Simp * Copyright (C) 2005
3163712Simp * 	Petr Holub, Hidetoshi Shimokawa. All rights reserved.
4163712Simp *
5163712Simp * Redistribution and use in source and binary forms, with or without
6163712Simp * modification, are permitted provided that the following conditions
7163712Simp * are met:
8163712Simp * 1. Redistributions of source code must retain the above copyright
9163712Simp *    notice, this list of conditions and the following disclaimer.
10163712Simp * 2. Redistributions in binary form must reproduce the above copyright
11163712Simp *    notice, this list of conditions and the following disclaimer in the
12163712Simp *    documentation and/or other materials provided with the distribution.
13163712Simp * 3. All advertising materials mentioning features or use of this software
14163712Simp *    must display the following acknowledgement:
15163712Simp *
16163712Simp *	This product includes software developed by Hidetoshi Shimokawa.
17163712Simp *
18163712Simp * 4. Neither the name of the author nor the names of its contributors
19163712Simp *    may be used to endorse or promote products derived from this software
20163712Simp *    without specific prior written permission.
21163712Simp *
22163712Simp * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23163712Simp * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24163712Simp * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25163712Simp * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26163712Simp * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27163712Simp * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28163712Simp * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29163712Simp * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30163712Simp * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31163712Simp * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32163712Simp * SUCH DAMAGE.
33163712Simp *
34163712Simp * $FreeBSD$
35163712Simp */
36163712Simp#include <sys/param.h>
37163712Simp#include <sys/ioctl.h>
38163712Simp#include <sys/time.h>
39163712Simp#include <sys/types.h>
40163712Simp#include <sys/uio.h>
41163712Simp
42163712Simp#if __FreeBSD_version >= 500000
43163712Simp#include <arpa/inet.h>
44163712Simp#endif
45163712Simp
46163712Simp#include <err.h>
47163712Simp#include <errno.h>
48163712Simp#include <unistd.h>
49163712Simp#include <fcntl.h>
50163712Simp#include <stdio.h>
51163712Simp#include <stdlib.h>
52163712Simp#include <string.h>
53163712Simp#include <sysexits.h>
54163712Simp
55185996Ssbruno#if defined(__FreeBSD__)
56163712Simp#include <dev/firewire/firewire.h>
57163712Simp#include <dev/firewire/iec68113.h>
58185996Ssbruno#elif defined(__NetBSD__)
59185996Ssbruno#include <dev/ieee1394/firewire.h>
60185996Ssbruno#include <dev/ieee1394/iec68113.h>
61185996Ssbruno#else
62185996Ssbruno#warning "You need to add support for your OS"
63185996Ssbruno#endif
64163712Simp
65185996Ssbruno
66163712Simp#include "fwmethods.h"
67163712Simp
68163712Simp#define	DEBUG 0
69163712Simp
70163712Simp/*****************************************************************************
71163712Simp
72163712SimpMPEG-2 Transport Stream (MPEG TS) packet format according to IEC 61883:
73163712Simp
74163712Simp31                              15                             0
75163712Simp+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  --------
76163712Simp|           len                 |tag|  channel  | tcode |  sy   |
77163712Simp+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+    1394
78163712Simp|                           header_CRC                          |
79163712Simp+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  --------
80163712Simp|0|0|    sid    |      dbs      |fn | qpc |S|RSV|       dbc     |
81163712Simp+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+    CIP
82163712Simp|1|0|    fmt    |      fdf      |          fdf/syt              |
83163712Simp+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  --------
84163712Simp|   reserved  |        cycle_count      |      cycle_offset     |
85163712Simp+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
86163712Simp|                                                               |    N x
87163712Simp.                                                               .    MPEG
88163712Simp.                   MPEG TS payload 188 bytes                   .
89163712Simp.                                                               .
90163712Simp|                                                               |
91163712Simp+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  --------
92163712Simp|                            data_CRC                           |
93163712Simp+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
94163712Simp
95163712SimpN.b. that CRCs are removed by firewire layer!
96163712Simp
97163712SimpThe following fiels are fixed for IEEE-1394:
98163712Simptag = 01b
99163712Simptcode = 1010b
100163712SimpThe length is payload length, i.e. includes CIP header and data size.
101163712Simp
102163712SimpThe following fields are constant for MPEG TS:
103163712Simpsph = 1 (denoted as S in CIP header above)
104163712Simpdbs = 6
105163712Simpfmt = (1<<5)
106163712Simpfdf = reserved
107163712SimpIn the supported streams we also require
108163712Simpqpc = 0
109163712Simpfn = 3
110163712Simpand thus the payload is divided in 8 blocks as follows:
111163712Simp
112163712Simp  +-----+-----+-----+-----+-----+-----+-----+-----+
113163712Simp  | db0 | db1 | db2 | db3 | db4 | db5 | db6 | db7 |
114163712Simp  +-----+-----+-----+-----+-----+-----+-----+-----+
115163712Simp
116163712SimpWe have several cases of payload distribution based on stream
117163712Simpbandwidth (R):
118163712Simp1) R < 1.5 Mbps: any of db0..db7 may be payload,
119163712Simp2) 1.5 < R < 3 Mbps: db0/db1 or db2/db3 or db4/db5 or db6/db7 is payload,
120163712Simp3) 3 < R < 6 Mbps: db0/db1/db2/db3 or db4/db5/db6/db7 is payload,
121163712Simp4) R > 6 Mbps: all db0..db7 contain the payload.
122163712SimpCurently, only case (4) is supported in fwmpegts.c
123163712Simp
124163712SimpEach packet may contain N  MPEG TS data blocks with timestamp header,
125163712Simpwhich are (4+188)B long. Experimentally, the N ranges from 0 through 3.
126163712Simp
127163712Simp*****************************************************************************/
128163712Simp
129163712Simp
130163712Simptypedef uint8_t mpeg_ts_pld[188];
131163712Simp
132163712Simpstruct mpeg_pldt {
133163712Simp#if BYTE_ORDER == BIG_ENDIAN
134163712Simp	uint32_t	:7,
135163712Simp				c_count:13,
136163712Simp				c_offset:12;
137163712Simp#else /* BYTE_ORDER != BIG_ENDIAN */
138163712Simp	uint32_t	c_offset:12,
139163712Simp				c_count:13,
140163712Simp				:7;
141163712Simp#endif /* BYTE_ORDER == BIG_ENDIAN */
142163712Simp	mpeg_ts_pld payload;
143163712Simp};
144163712Simp
145163712Simp
146163712Simp#define	NCHUNK 8
147163712Simp#define	PSIZE 596
148163712Simp#define	NPACKET_R 4096
149163712Simp#define	RBUFSIZE (PSIZE * NPACKET_R)
150163712Simp
151163712Simpvoid
152163712Simpmpegtsrecv(int d, const char *filename, char ich, int count)
153163712Simp{
154163712Simp	struct ciphdr *ciph;
155163712Simp	struct fw_isochreq isoreq;
156163712Simp	struct fw_isobufreq bufreq;
157163712Simp	struct fw_pkt *pkt;
158163712Simp	struct mpeg_pldt *pld;
159163712Simp	uint32_t *ptr;
160163712Simp	int fd, k, len, m, pkt_size, startwr, tlen;
161163712Simp	char *buf;
162163712Simp
163163712Simp	startwr = 0;
164163712Simp
165163712Simp	if (strcmp(filename, "-") == 0)
166163712Simp		fd = STDOUT_FILENO;
167163712Simp	else {
168163712Simp		fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0660);
169163712Simp		if (fd == -1)
170216948Semaste			err(EX_NOINPUT, "%s", filename);
171163712Simp	}
172163712Simp	buf = malloc(RBUFSIZE);
173163712Simp
174163712Simp	bufreq.rx.nchunk = NCHUNK;
175163712Simp	bufreq.rx.npacket = NPACKET_R;
176163712Simp	bufreq.rx.psize = PSIZE;
177163712Simp	bufreq.tx.nchunk = 0;
178163712Simp	bufreq.tx.npacket = 0;
179163712Simp	bufreq.tx.psize = 0;
180163712Simp	if (ioctl(d, FW_SSTBUF, &bufreq) < 0)
181163712Simp		err(1, "ioctl");
182163712Simp
183163712Simp	isoreq.ch = ich & 0x3f;
184163712Simp	isoreq.tag = (ich >> 6) & 3;
185163712Simp
186163712Simp	if (ioctl(d, FW_SRSTREAM, &isoreq) < 0)
187163712Simp		err(1, "ioctl");
188163712Simp
189163712Simp	k = m = 0;
190163712Simp	while (count <= 0 || k <= count) {
191163712Simp		len = tlen = read(d, buf, RBUFSIZE);
192163712Simp#if DEBUG
193163712Simp		fprintf(stderr, "Read %d bytes.\n", len);
194163712Simp#endif /* DEBUG */
195163712Simp		if (len < 0) {
196163712Simp			if (errno == EAGAIN) {
197163712Simp				fprintf(stderr, "(EAGAIN) - push 'Play'?\n");
198188029Ssbruno				continue;
199188029Ssbruno			}
200188029Ssbruno			err(1, "read failed");
201163712Simp		}
202163712Simp		ptr = (uint32_t *) buf;
203163712Simp
204163712Simp		do {
205163712Simp			pkt = (struct fw_pkt *) ptr;
206163712Simp#if DEBUG
207163712Simp			fprintf(stderr, "\nReading new packet.\n");
208163712Simp			fprintf(stderr, "%08x %08x %08x %08x\n",
209163712Simp				htonl(ptr[0]), htonl(ptr[1]),
210163712Simp				htonl(ptr[2]), htonl(ptr[3]));
211163712Simp#endif /* DEBUG */
212163712Simp			/* there is no CRC in the 1394 header */
213163712Simp			ciph = (struct ciphdr *)(ptr + 1);	/* skip iso header */
214163712Simp			if (ciph->fmt != CIP_FMT_MPEG)
215163712Simp				errx(1, "unknown format 0x%x", ciph->fmt);
216163712Simp			if (ciph->fn != 3) {
217163712Simp				errx(1,
218163712Simp						"unsupported MPEG TS stream, fn=%d (only fn=3 is supported)",
219163712Simp						ciph->fn);
220163712Simp			}
221163712Simp			ptr = (uint32_t *) (ciph + 1);		/* skip cip header */
222163712Simp
223163712Simp			if (pkt->mode.stream.len <= sizeof(struct ciphdr)) {
224163712Simp				/* no payload */
225163712Simp				/* tlen needs to be decremented before end of the loop */
226163712Simp				goto next;
227163712Simp			}
228163712Simp#if DEBUG
229163712Simp			else {
230163712Simp				fprintf(stderr,
231163712Simp						"Packet net payload length (IEEE1394 header): %d\n",
232163712Simp						pkt->mode.stream.len - sizeof(struct ciphdr));
233163712Simp				fprintf(stderr, "Data block size (CIP header): %d [q], %d [B]\n",
234163712Simp						ciph->len, ciph->len * 4);
235163712Simp				fprintf(stderr,
236163712Simp						"Data fraction number (CIP header): %d => DBC increments with %d\n",
237163712Simp						ciph->fn, (1<<ciph->fn) );
238163712Simp				fprintf(stderr, "QCP (CIP header): %d\n", ciph->qpc );
239163712Simp				fprintf(stderr, "DBC counter (CIP header): %d\n", ciph->dbc );
240163712Simp				fprintf(stderr, "MPEG payload type size: %d\n",
241163712Simp						sizeof(struct mpeg_pldt));
242163712Simp			}
243163712Simp#endif /* DEBUG */
244163712Simp
245163712Simp			/* This is a condition that needs to be satisfied to start
246163712Simp			   writing the data */
247163712Simp			if (ciph->dbc % (1<<ciph->fn) == 0)
248163712Simp				startwr = 1;
249163712Simp			/* Read out all the MPEG TS data blocks from current packet */
250163712Simp			for (pld = (struct mpeg_pldt *)ptr;
251163712Simp			    (intptr_t)pld < (intptr_t)((char *)ptr +
252163712Simp			    pkt->mode.stream.len - sizeof(struct ciphdr));
253163712Simp			    pld++) {
254163712Simp				if (startwr == 1)
255163712Simp					write(fd, pld->payload,
256163712Simp					    sizeof(pld->payload));
257163712Simp			}
258163712Simp
259163712Simpnext:
260163712Simp			/* CRCs are removed from both header and trailer
261163712Simp			so that only 4 bytes of 1394 header remains */
262163712Simp			pkt_size = pkt->mode.stream.len + 4;
263163712Simp			ptr = (uint32_t *)((intptr_t)pkt + pkt_size);
264163712Simp			tlen -= pkt_size;
265163712Simp		} while (tlen > 0);
266163712Simp#if DEBUG
267163712Simp		fprintf(stderr, "\nReading a data from firewire.\n");
268163712Simp#endif /* DEBUG */
269163712Simp
270163712Simp	}
271163712Simp	if (fd != STDOUT_FILENO)
272163712Simp		close(fd);
273163712Simp	fprintf(stderr, "\n");
274163712Simp}
275