1/*-
2 * SPDX-License-Identifier: BSD-4-Clause
3 *
4 * Copyright (C) 2003
5 * 	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#include <sys/param.h>
37#include <sys/ioctl.h>
38#include <sys/time.h>
39#include <sys/types.h>
40#include <sys/uio.h>
41#include <arpa/inet.h>
42#include <err.h>
43#include <errno.h>
44#include <unistd.h>
45#include <fcntl.h>
46#include <stdio.h>
47#include <stdlib.h>
48#include <string.h>
49#include <sysexits.h>
50
51#include <dev/firewire/firewire.h>
52#include <dev/firewire/iec68113.h>
53
54#include "fwmethods.h"
55
56#define DEBUG		0
57#define FIX_FRAME	1
58
59struct frac {
60	int n,d;
61};
62
63struct frac frame_cycle[2]  = {
64	{8000*100, 2997},	/* NTSC 8000 cycle / 29.97 Hz */
65	{320, 1},		/* PAL  8000 cycle / 25 Hz */
66};
67int npackets[] = {
68	250		/* NTSC */,
69	300		/* PAL */
70};
71struct frac pad_rate[2]  = {
72	{203, 2997},	/* = (8000 - 29.97 * 250)/(29.97 * 250) */
73	{1, 15},	/* = (8000 - 25 * 300)/(25 * 300) */
74};
75char *system_name[] = {"NTSC", "PAL"};
76int frame_rate[] = {30, 25};
77
78#define PSIZE 512
79#define DSIZE 480
80#define NCHUNK 64
81
82#define NPACKET_R 256
83#define NPACKET_T 255
84#define TNBUF 100	/* XXX too large value causes block noise */
85#define NEMPTY 10	/* depends on TNBUF */
86#define RBUFSIZE (PSIZE * NPACKET_R)
87#define MAXBLOCKS (300)
88#define CYCLE_FRAC 0xc00
89
90void
91dvrecv(int d, const char *filename, char ich, int count)
92{
93	struct fw_isochreq isoreq;
94	struct fw_isobufreq bufreq;
95	struct dvdbc *dv;
96	struct ciphdr *ciph;
97	struct fw_pkt *pkt;
98	char *pad, *buf;
99	u_int32_t *ptr;
100	int len, tlen, npad, fd, k, m, vec, system = -1, nb;
101	int nblocks[] = {250 /* NTSC */, 300 /* PAL */};
102	struct iovec wbuf[NPACKET_R];
103
104	if(strcmp(filename, "-") == 0) {
105		fd = STDOUT_FILENO;
106	} else {
107		fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0660);
108		if (fd == -1)
109			err(EX_NOINPUT, "%s", filename);
110	}
111	buf = malloc(RBUFSIZE);
112	pad = malloc(DSIZE*MAXBLOCKS);
113	memset(pad, 0xff, DSIZE*MAXBLOCKS);
114	bzero(wbuf, sizeof(wbuf));
115
116	bufreq.rx.nchunk = NCHUNK;
117	bufreq.rx.npacket = NPACKET_R;
118	bufreq.rx.psize = PSIZE;
119	bufreq.tx.nchunk = 0;
120	bufreq.tx.npacket = 0;
121	bufreq.tx.psize = 0;
122	if (ioctl(d, FW_SSTBUF, &bufreq) < 0)
123		err(1, "ioctl FW_SSTBUF");
124
125	isoreq.ch = ich & 0x3f;
126	isoreq.tag = (ich >> 6) & 3;
127
128	if (ioctl(d, FW_SRSTREAM, &isoreq) < 0)
129       		err(1, "ioctl");
130
131	k = m = 0;
132	while (count <= 0 || k <= count) {
133#if 0
134		tlen = 0;
135		while ((len = read(d, buf + tlen, PSIZE
136						/* RBUFSIZE - tlen */)) > 0) {
137			if (len < 0) {
138				if (errno == EAGAIN) {
139					fprintf(stderr, "(EAGAIN)\n");
140					fflush(stderr);
141					if (len <= 0)
142						continue;
143				} else
144					err(1, "read failed");
145			}
146			tlen += len;
147			if ((RBUFSIZE - tlen) < PSIZE)
148				break;
149		};
150#else
151		tlen = len = read(d, buf, RBUFSIZE);
152		if (len < 0) {
153			if (errno == EAGAIN) {
154				fprintf(stderr, "(EAGAIN) - push 'Play'?\n");
155				fflush(stderr);
156				if (len <= 0)
157					continue;
158			} else
159				err(1, "read failed");
160		}
161#endif
162		vec = 0;
163		ptr = (u_int32_t *) buf;
164again:
165		pkt = (struct fw_pkt *) ptr;
166#if DEBUG
167		fprintf(stderr, "%08x %08x %08x %08x\n",
168			htonl(ptr[0]), htonl(ptr[1]),
169			htonl(ptr[2]), htonl(ptr[3]));
170#endif
171		ciph = (struct ciphdr *)(ptr + 1);	/* skip iso header */
172		if (ciph->fmt != CIP_FMT_DVCR)
173			errx(1, "unknown format 0x%x", ciph->fmt);
174		ptr = (u_int32_t *) (ciph + 1);		/* skip cip header */
175#if DEBUG
176		if (ciph->fdf.dv.cyc != 0xffff && k == 0) {
177			fprintf(stderr, "0x%04x\n", ntohs(ciph->fdf.dv.cyc));
178		}
179#endif
180		if (pkt->mode.stream.len <= sizeof(struct ciphdr))
181			/* no payload */
182			goto next;
183		for (dv = (struct dvdbc *)ptr;
184				(char *)dv < (char *)(ptr + ciph->len);
185				dv+=6) {
186
187#if DEBUG
188			fprintf(stderr, "(%d,%d) ", dv->sct, dv->dseq);
189#endif
190			if  (dv->sct == DV_SCT_HEADER && dv->dseq == 0) {
191				if (system < 0) {
192					system = ciph->fdf.dv.fs;
193					fprintf(stderr, "%s\n", system_name[system]);
194				}
195
196				/* Fix DSF bit */
197				if (system == 1 &&
198					(dv->payload[0] & DV_DSF_12) == 0)
199					dv->payload[0] |= DV_DSF_12;
200				nb = nblocks[system];
201 				fprintf(stderr, "%d:%02d:%02d %d\r",
202					k / (3600 * frame_rate[system]),
203					(k / (60 * frame_rate[system])) % 60,
204					(k / frame_rate[system]) % 60,
205					k % frame_rate[system]);
206
207#if FIX_FRAME
208				if (m > 0 && m != nb) {
209					/* padding bad frame */
210					npad = ((nb - m) % nb);
211					if (npad < 0)
212						npad += nb;
213					fprintf(stderr, "\n%d blocks padded\n",
214					    npad);
215					npad *= DSIZE;
216					wbuf[vec].iov_base = pad;
217					wbuf[vec++].iov_len = npad;
218					if (vec >= NPACKET_R) {
219						writev(fd, wbuf, vec);
220						vec = 0;
221					}
222				}
223#endif
224				k++;
225				fflush(stderr);
226				m = 0;
227			}
228			if (k == 0 || (count > 0 && k > count))
229				continue;
230			m++;
231			wbuf[vec].iov_base = (char *) dv;
232			wbuf[vec++].iov_len = DSIZE;
233			if (vec >= NPACKET_R) {
234				writev(fd, wbuf, vec);
235				vec = 0;
236			}
237		}
238		ptr = (u_int32_t *)dv;
239next:
240		if ((char *)ptr < buf + tlen)
241			goto again;
242		if (vec > 0)
243			writev(fd, wbuf, vec);
244	}
245	if (fd != STDOUT_FILENO)
246		close(fd);
247	fprintf(stderr, "\n");
248}
249
250
251void
252dvsend(int d, const char *filename, char ich, int count)
253{
254	struct fw_isochreq isoreq;
255	struct fw_isobufreq bufreq;
256	struct dvdbc *dv;
257	struct fw_pkt *pkt;
258	int len, tlen, header, fd, frames, packets, vec, offset, nhdr, i;
259	int system=-1, pad_acc, cycle_acc, cycle, f_frac;
260	struct iovec wbuf[TNBUF*2 + NEMPTY];
261	char *pbuf;
262	u_int32_t iso_data, iso_empty, hdr[TNBUF + NEMPTY][3];
263	struct ciphdr *ciph;
264	struct timeval start, end;
265	double rtime;
266
267	fd = open(filename, O_RDONLY);
268	if (fd == -1)
269		err(EX_NOINPUT, "%s", filename);
270
271	pbuf = malloc(DSIZE * TNBUF);
272	bzero(wbuf, sizeof(wbuf));
273
274	bufreq.rx.nchunk = 0;
275	bufreq.rx.npacket = 0;
276	bufreq.rx.psize = 0;
277	bufreq.tx.nchunk = NCHUNK;
278	bufreq.tx.npacket = NPACKET_T;
279	bufreq.tx.psize = PSIZE;
280	if (ioctl(d, FW_SSTBUF, &bufreq) < 0)
281		err(1, "ioctl FW_SSTBUF");
282
283	isoreq.ch = ich & 0x3f;
284	isoreq.tag = (ich >> 6) & 3;
285
286	if (ioctl(d, FW_STSTREAM, &isoreq) < 0)
287       		err(1, "ioctl FW_STSTREAM");
288
289	iso_data = 0;
290	pkt = (struct fw_pkt *) &iso_data;
291	pkt->mode.stream.len = DSIZE + sizeof(struct ciphdr);
292	pkt->mode.stream.sy = 0;
293	pkt->mode.stream.tcode = FWTCODE_STREAM;
294	pkt->mode.stream.chtag = ich;
295	iso_empty = iso_data;
296	pkt = (struct fw_pkt *) &iso_empty;
297	pkt->mode.stream.len = sizeof(struct ciphdr);
298
299	bzero(hdr[0], sizeof(hdr[0]));
300	hdr[0][0] = iso_data;
301	ciph = (struct ciphdr *)&hdr[0][1];
302	ciph->src = 0;	 /* XXX */
303	ciph->len = 120;
304	ciph->dbc = 0;
305	ciph->eoh1 = 1;
306	ciph->fdf.dv.cyc = 0xffff;
307
308	for (i = 1; i < TNBUF; i++)
309		bcopy(hdr[0], hdr[i], sizeof(hdr[0]));
310
311	gettimeofday(&start, NULL);
312#if DEBUG
313	fprintf(stderr, "%08x %08x %08x\n",
314			htonl(hdr[0]), htonl(hdr[1]), htonl(hdr[2]));
315#endif
316	frames = 0;
317	packets = 0;
318	pad_acc = 0;
319	while (1) {
320		tlen = 0;
321		while (tlen < DSIZE * TNBUF) {
322			len = read(fd, pbuf + tlen, DSIZE * TNBUF - tlen);
323			if (len <= 0) {
324				if (tlen > 0)
325					break;
326				if (len < 0)
327					warn("read");
328				else
329					fprintf(stderr, "\nend of file\n");
330				goto send_end;
331			}
332			tlen += len;
333		}
334		vec = 0;
335		offset = 0;
336		nhdr = 0;
337next:
338		dv = (struct dvdbc *)(pbuf + offset * DSIZE);
339#if 0
340		header = (dv->sct == 0 && dv->dseq == 0);
341#else
342		header = (packets == 0 || packets % npackets[system] == 0);
343#endif
344
345		ciph = (struct ciphdr *)&hdr[nhdr][1];
346		if (header) {
347			if (system < 0) {
348				system = ((dv->payload[0] & DV_DSF_12) != 0);
349				printf("%s\n", system_name[system]);
350				cycle = 1;
351				cycle_acc = frame_cycle[system].d * cycle;
352			}
353			fprintf(stderr, "%d", frames % 10);
354			frames ++;
355			if (count > 0 && frames > count)
356				break;
357			if (frames % frame_rate[system] == 0)
358				fprintf(stderr, "\n");
359			fflush(stderr);
360			f_frac = (cycle_acc % frame_cycle[system].d
361					* CYCLE_FRAC) / frame_cycle[system].d;
362#if 0
363			int f_cycle;
364			f_cycle = (cycle_acc / frame_cycle[system].d) & 0xf;
365			ciph->fdf.dv.cyc = htons(f_cycle << 12 | f_frac);
366#else
367			ciph->fdf.dv.cyc = htons(cycle << 12 | f_frac);
368#endif
369			cycle_acc += frame_cycle[system].n;
370			cycle_acc %= frame_cycle[system].d * 0x10;
371
372		} else {
373			ciph->fdf.dv.cyc = 0xffff;
374		}
375		ciph->dbc = packets++ % 256;
376		pad_acc += pad_rate[system].n;
377		if (pad_acc >= pad_rate[system].d) {
378			pad_acc -= pad_rate[system].d;
379			bcopy(hdr[nhdr], hdr[nhdr+1], sizeof(hdr[0]));
380			hdr[nhdr][0] = iso_empty;
381			wbuf[vec].iov_base = (char *)hdr[nhdr];
382			wbuf[vec++].iov_len = sizeof(hdr[0]);
383			nhdr ++;
384			cycle ++;
385		}
386		hdr[nhdr][0] = iso_data;
387		wbuf[vec].iov_base = (char *)hdr[nhdr];
388		wbuf[vec++].iov_len = sizeof(hdr[0]);
389		wbuf[vec].iov_base = (char *)dv;
390		wbuf[vec++].iov_len = DSIZE;
391		nhdr ++;
392		cycle ++;
393		offset ++;
394		if (offset * DSIZE < tlen)
395			goto next;
396
397again:
398		len = writev(d, wbuf, vec);
399		if (len < 0) {
400			if (errno == EAGAIN) {
401				fprintf(stderr, "(EAGAIN) - push 'Play'?\n");
402				goto again;
403			}
404			err(1, "write failed");
405		}
406	}
407	fprintf(stderr, "\n");
408send_end:
409	gettimeofday(&end, NULL);
410	rtime = end.tv_sec - start.tv_sec
411			+ (end.tv_usec - start.tv_usec) * 1e-6;
412	fprintf(stderr, "%d frames, %.2f secs, %.2f frames/sec\n",
413			frames, rtime, frames/rtime);
414	close(fd);
415}
416