/*
NAME
  lex.go

DESCRIPTION
  lex.go provides a lexer to extract separate JPEG images from a MJPEG stream.

AUTHOR
  Dan Kortschak <dan@ausocean.org>

LICENSE
  lex.go is Copyright (C) 2017 the Australian Ocean Lab (AusOcean)

  It is free software: you can redistribute it and/or modify them
  under the terms of the GNU General Public License as published by the
  Free Software Foundation, either version 3 of the License, or (at your
  option) any later version.

  It is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  for more details.

  You should have received a copy of the GNU General Public License
  along with revid in gpl.txt. If not, see http://www.gnu.org/licenses.
*/

// lex.go provides a lexer to extract separate JPEG images from a MJPEG stream.

package mjpeg

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"time"
)

var noDelay = make(chan time.Time)

func init() {
	close(noDelay)
}

// Lex parses MJPEG frames read from src into separate writes to dst with
// successive writes being performed not earlier than the specified delay.
func Lex(dst io.Writer, src io.Reader, delay time.Duration) error {
	var tick <-chan time.Time
	if delay == 0 {
		tick = noDelay
	} else {
		ticker := time.NewTicker(delay)
		defer ticker.Stop()
		tick = ticker.C
	}

	r := bufio.NewReader(src)
	for {
		buf := make([]byte, 2, 4<<10)
		n, err := r.Read(buf)
		if n < 2 {
			return nil
		}
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}
		if !bytes.Equal(buf, []byte{0xff, 0xd8}) {
			return fmt.Errorf("parser: not MJPEG frame start: %#v", buf)
		}
		var last byte
		for {
			b, err := r.ReadByte()
			if err != nil {
				if err == io.EOF {
					return nil
				}
				return err
			}
			buf = append(buf, b)
			if last == 0xff && b == 0xd9 {
				break
			}
			last = b
		}
		<-tick
		_, err = dst.Write(buf)
		if err != nil {
			return err
		}
	}
}