1/*
2 * sndio play and grab interface
3 * Copyright (c) 2010 Jacob Meuser
4 *
5 * This file is part of Libav.
6 *
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22#include <stdint.h>
23#include <sndio.h>
24
25#include "libavformat/avformat.h"
26
27#include "sndio_common.h"
28
29static av_cold int audio_write_header(AVFormatContext *s1)
30{
31    SndioData *s = s1->priv_data;
32    AVStream *st;
33    int ret;
34
35    st             = s1->streams[0];
36    s->sample_rate = st->codec->sample_rate;
37    s->channels    = st->codec->channels;
38
39    ret = ff_sndio_open(s1, 1, s1->filename);
40
41    return ret;
42}
43
44static int audio_write_packet(AVFormatContext *s1, AVPacket *pkt)
45{
46    SndioData *s = s1->priv_data;
47    uint8_t *buf= pkt->data;
48    int size = pkt->size;
49    int len, ret;
50
51    while (size > 0) {
52        len = FFMIN(s->buffer_size - s->buffer_offset, size);
53        memcpy(s->buffer + s->buffer_offset, buf, len);
54        buf  += len;
55        size -= len;
56        s->buffer_offset += len;
57        if (s->buffer_offset >= s->buffer_size) {
58            ret = sio_write(s->hdl, s->buffer, s->buffer_size);
59            if (ret == 0 || sio_eof(s->hdl))
60                return AVERROR(EIO);
61            s->softpos      += ret;
62            s->buffer_offset = 0;
63        }
64    }
65
66    return 0;
67}
68
69static int audio_write_trailer(AVFormatContext *s1)
70{
71    SndioData *s = s1->priv_data;
72
73    sio_write(s->hdl, s->buffer, s->buffer_offset);
74
75    ff_sndio_close(s);
76
77    return 0;
78}
79
80AVOutputFormat ff_sndio_muxer = {
81    .name           = "sndio",
82    .long_name      = NULL_IF_CONFIG_SMALL("sndio audio playback"),
83    .priv_data_size = sizeof(SndioData),
84    /* XXX: we make the assumption that the soundcard accepts this format */
85    /* XXX: find better solution with "preinit" method, needed also in
86       other formats */
87    .audio_codec    = AV_NE(CODEC_ID_PCM_S16BE, CODEC_ID_PCM_S16LE),
88    .video_codec    = CODEC_ID_NONE,
89    .write_header   = audio_write_header,
90    .write_packet   = audio_write_packet,
91    .write_trailer  = audio_write_trailer,
92    .flags          = AVFMT_NOFILE,
93};
94