]> git.sesse.net Git - ffmpeg/blob - libavdevice/iec61883.c
Merge commit '97bf7c03b1338a867da52c159a2afecbdedcfa88'
[ffmpeg] / libavdevice / iec61883.c
1 /*
2  * Copyright (c) 2012 Georg Lippitsch <georg.lippitsch@gmx.at>
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * libiec61883 interface
24  */
25
26 #include <sys/poll.h>
27 #include <libraw1394/raw1394.h>
28 #include <libavc1394/avc1394.h>
29 #include <libavc1394/rom1394.h>
30 #include <libiec61883/iec61883.h>
31 #include "libavformat/dv.h"
32 #include "libavformat/mpegts.h"
33 #include "libavutil/opt.h"
34 #include "avdevice.h"
35
36 #define THREADS HAVE_PTHREADS
37
38 #if THREADS
39 #include <pthread.h>
40 #endif
41
42 #define MOTDCT_SPEC_ID      0x00005068
43 #define IEC61883_AUTO       0
44 #define IEC61883_DV         1
45 #define IEC61883_HDV        2
46
47 /**
48  * For DV, one packet corresponds exactly to one frame.
49  * For HDV, these are MPEG2 transport stream packets.
50  * The queue is implemented as linked list.
51  */
52 typedef struct DVPacket {
53     uint8_t *buf;                       ///< actual buffer data
54     int len;                            ///< size of buffer allocated
55     struct DVPacket *next;              ///< next DVPacket
56 } DVPacket;
57
58 struct iec61883_data {
59     AVClass *class;
60     raw1394handle_t raw1394;            ///< handle for libraw1394
61     iec61883_dv_fb_t iec61883_dv;       ///< handle for libiec61883 when used with DV
62     iec61883_mpeg2_t iec61883_mpeg2;    ///< handle for libiec61883 when used with HDV
63
64     DVDemuxContext *dv_demux;           ///< generic DV muxing/demuxing context
65     MpegTSContext *mpeg_demux;          ///< generic HDV muxing/demuxing context
66
67     DVPacket *queue_first;              ///< first element of packet queue
68     DVPacket *queue_last;               ///< last element of packet queue
69
70     int packets;                        ///< Number of packets queued
71     int max_packets;                    ///< Max. number of packets in queue
72
73     int bandwidth;                      ///< returned by libiec61883
74     int channel;                        ///< returned by libiec61883
75     int input_port;                     ///< returned by libiec61883
76     int type;                           ///< Stream type, to distinguish DV/HDV
77     int node;                           ///< returned by libiec61883
78     int output_port;                    ///< returned by libiec61883
79     int thread_loop;                    ///< Condition for thread while-loop
80     int receiving;                      ///< True as soon data from device available
81     int receive_error;                  ///< Set in receive task in case of error
82     int eof;                            ///< True as soon as no more data available
83
84     struct pollfd raw1394_poll;         ///< to poll for new data from libraw1394
85
86     /** Parse function for DV/HDV differs, so this is set before packets arrive */
87     int (*parse_queue)(struct iec61883_data *dv, AVPacket *pkt);
88
89 #if THREADS
90     pthread_t receive_task_thread;
91     pthread_mutex_t mutex;
92     pthread_cond_t cond;
93 #endif
94 };
95
96 static int iec61883_callback(unsigned char *data, int length,
97                              int complete, void *callback_data)
98 {
99     struct iec61883_data *dv = callback_data;
100     DVPacket *packet;
101     int ret;
102
103 #ifdef THREADS
104     pthread_mutex_lock(&dv->mutex);
105 #endif
106
107     if (dv->packets >= dv->max_packets) {
108         av_log(NULL, AV_LOG_ERROR, "DV packet queue overrun, dropping.\n");
109         ret = 0;
110         goto exit;
111     }
112
113     packet = av_mallocz(sizeof(*packet));
114     if (!packet) {
115         ret = -1;
116         goto exit;
117     }
118
119     packet->buf = av_malloc(length);
120     if (!packet->buf) {
121         ret = -1;
122         goto exit;
123     }
124     packet->len = length;
125
126     memcpy(packet->buf, data, length);
127
128     if (dv->queue_first) {
129         dv->queue_last->next = packet;
130         dv->queue_last = packet;
131     } else {
132         dv->queue_first = packet;
133         dv->queue_last = packet;
134     }
135     dv->packets++;
136
137     ret = 0;
138
139 exit:
140 #ifdef THREADS
141     pthread_cond_signal(&dv->cond);
142     pthread_mutex_unlock(&dv->mutex);
143 #endif
144     return ret;
145 }
146
147 static void *iec61883_receive_task(void *opaque)
148 {
149     struct iec61883_data *dv = (struct iec61883_data *)opaque;
150     int result;
151
152 #ifdef THREADS
153     while (dv->thread_loop)
154 #endif
155     {
156         while ((result = poll(&dv->raw1394_poll, 1, 200)) < 0) {
157             if (!(errno == EAGAIN || errno == EINTR)) {
158                 av_log(NULL, AV_LOG_ERROR, "Raw1394 poll error occurred.\n");
159                 dv->receive_error = AVERROR(EIO);
160                 return NULL;
161             }
162         }
163         if (result > 0 && ((dv->raw1394_poll.revents & POLLIN)
164                            || (dv->raw1394_poll.revents & POLLPRI))) {
165             dv->receiving = 1;
166             raw1394_loop_iterate(dv->raw1394);
167         } else if (dv->receiving) {
168             av_log(NULL, AV_LOG_ERROR, "No more input data available\n");
169 #ifdef THREADS
170             pthread_mutex_lock(&dv->mutex);
171             dv->eof = 1;
172             pthread_cond_signal(&dv->cond);
173             pthread_mutex_unlock(&dv->mutex);
174 #else
175             dv->eof = 1;
176 #endif
177             return NULL;
178         }
179     }
180
181     return NULL;
182 }
183
184 static int iec61883_parse_queue_dv(struct iec61883_data *dv, AVPacket *pkt)
185 {
186     DVPacket *packet;
187     int size;
188
189     size = avpriv_dv_get_packet(dv->dv_demux, pkt);
190     if (size > 0)
191         return size;
192
193     packet = dv->queue_first;
194     if (!packet)
195         return -1;
196
197     size = avpriv_dv_produce_packet(dv->dv_demux, pkt,
198                                     packet->buf, packet->len, -1);
199     pkt->destruct = av_destruct_packet;
200     dv->queue_first = packet->next;
201     av_free(packet);
202     dv->packets--;
203
204     if (size > 0)
205         return size;
206
207     return -1;
208 }
209
210 static int iec61883_parse_queue_hdv(struct iec61883_data *dv, AVPacket *pkt)
211 {
212     DVPacket *packet;
213     int size;
214
215     while (dv->queue_first) {
216         packet = dv->queue_first;
217         size = ff_mpegts_parse_packet(dv->mpeg_demux, pkt, packet->buf,
218                                       packet->len);
219         dv->queue_first = packet->next;
220         av_free(packet->buf);
221         av_free(packet);
222         dv->packets--;
223
224         if (size > 0)
225             return size;
226     }
227
228     return -1;
229 }
230
231 static int iec61883_read_header(AVFormatContext *context)
232 {
233     struct iec61883_data *dv = context->priv_data;
234     struct raw1394_portinfo pinf[16];
235     rom1394_directory rom_dir;
236     char *endptr;
237     int inport;
238     int nb_ports;
239     int port = -1;
240     int response;
241     int i, j = 0;
242
243     dv->input_port = -1;
244     dv->output_port = -1;
245     dv->channel = -1;
246
247     dv->raw1394 = raw1394_new_handle();
248
249     if (!dv->raw1394) {
250         av_log(context, AV_LOG_ERROR, "Failed to open IEEE1394 interface.\n");
251         return AVERROR(EIO);
252     }
253
254     if ((nb_ports = raw1394_get_port_info(dv->raw1394, pinf, 16)) < 0) {
255         av_log(context, AV_LOG_ERROR, "Failed to get number of IEEE1394 ports.\n");
256         goto fail;
257     }
258
259     inport = strtol(context->filename, &endptr, 10);
260     if (endptr != context->filename && *endptr == '\0') {
261         av_log(context, AV_LOG_INFO, "Selecting IEEE1394 port: %d\n", inport);
262         j = inport;
263         nb_ports = inport + 1;
264     } else if (strcmp(context->filename, "auto")) {
265         av_log(context, AV_LOG_ERROR, "Invalid input \"%s\", you should specify "
266                "\"auto\" for auto-detection, or the port number.\n", context->filename);
267         goto fail;
268     }
269
270     /* Select first AV/C tape recorder player node */
271
272     for (; j < nb_ports && port==-1; ++j) {
273         if (raw1394_set_port(dv->raw1394, j)) {
274             av_log(context, AV_LOG_ERROR, "Failed setting IEEE1394 port.\n");
275             goto fail;
276         }
277         for (i=0; i<raw1394_get_nodecount(dv->raw1394); ++i) {
278             if (rom1394_get_directory(dv->raw1394, i, &rom_dir) < 0)
279                 continue;
280             if (((rom1394_get_node_type(&rom_dir) == ROM1394_NODE_TYPE_AVC) &&
281                  avc1394_check_subunit_type(dv->raw1394, i, AVC1394_SUBUNIT_TYPE_VCR)) ||
282                 (rom_dir.unit_spec_id == MOTDCT_SPEC_ID)) {
283                 rom1394_free_directory(&rom_dir);
284                 dv->node = i;
285                 port = j;
286                 break;
287             }
288             rom1394_free_directory(&rom_dir);
289         }
290     }
291
292     if (port == -1) {
293         av_log(context, AV_LOG_ERROR, "No AV/C devices found.\n");
294         goto fail;
295     }
296
297     /* Find out if device is DV or HDV */
298
299     if (dv->type == IEC61883_AUTO) {
300         response = avc1394_transaction(dv->raw1394, dv->node,
301                                        AVC1394_CTYPE_STATUS |
302                                        AVC1394_SUBUNIT_TYPE_TAPE_RECORDER |
303                                        AVC1394_SUBUNIT_ID_0 |
304                                        AVC1394_VCR_COMMAND_OUTPUT_SIGNAL_MODE |
305                                        0xFF, 2);
306         response = AVC1394_GET_OPERAND0(response);
307         dv->type = (response == 0x10 || response == 0x90 || response == 0x1A || response == 0x9A) ?
308             IEC61883_HDV : IEC61883_DV;
309     }
310
311     /* Connect to device, and do initialization */
312
313     dv->channel = iec61883_cmp_connect(dv->raw1394, dv->node, &dv->output_port,
314                                        raw1394_get_local_id(dv->raw1394),
315                                        &dv->input_port, &dv->bandwidth);
316
317     if (dv->channel < 0)
318         dv->channel = 63;
319
320     if (!dv->max_packets)
321         dv->max_packets = 100;
322
323     if (dv->type == IEC61883_HDV) {
324
325         /* Init HDV receive */
326
327         avformat_new_stream(context, NULL);
328
329         dv->mpeg_demux = ff_mpegts_parse_open(context);
330         if (!dv->mpeg_demux)
331             goto fail;
332
333         dv->parse_queue = iec61883_parse_queue_hdv;
334
335         dv->iec61883_mpeg2 = iec61883_mpeg2_recv_init(dv->raw1394,
336                                                       (iec61883_mpeg2_recv_t)iec61883_callback,
337                                                       dv);
338
339         dv->max_packets *= 766;
340     } else {
341
342         /* Init DV receive */
343
344         dv->dv_demux = avpriv_dv_init_demux(context);
345         if (!dv->dv_demux)
346             goto fail;
347
348         dv->parse_queue = iec61883_parse_queue_dv;
349
350         dv->iec61883_dv = iec61883_dv_fb_init(dv->raw1394, iec61883_callback, dv);
351     }
352
353     dv->raw1394_poll.fd = raw1394_get_fd(dv->raw1394);
354     dv->raw1394_poll.events = POLLIN | POLLERR | POLLHUP | POLLPRI;
355
356     /* Actually start receiving */
357
358     if (dv->type == IEC61883_HDV)
359         iec61883_mpeg2_recv_start(dv->iec61883_mpeg2, dv->channel);
360     else
361         iec61883_dv_fb_start(dv->iec61883_dv, dv->channel);
362
363 #if THREADS
364     dv->thread_loop = 1;
365     pthread_mutex_init(&dv->mutex, NULL);
366     pthread_cond_init(&dv->cond, NULL);
367     pthread_create(&dv->receive_task_thread, NULL, iec61883_receive_task, dv);
368 #endif
369
370     return 0;
371
372 fail:
373     raw1394_destroy_handle(dv->raw1394);
374     return AVERROR(EIO);
375 }
376
377 static int iec61883_read_packet(AVFormatContext *context, AVPacket *pkt)
378 {
379     struct iec61883_data *dv = context->priv_data;
380     int size;
381
382     /**
383      * Try to parse frames from queue
384      */
385
386 #ifdef THREADS
387     pthread_mutex_lock(&dv->mutex);
388     while ((size = dv->parse_queue(dv, pkt)) == -1)
389         if (!dv->eof)
390             pthread_cond_wait(&dv->cond, &dv->mutex);
391         else
392             break;
393     pthread_mutex_unlock(&dv->mutex);
394 #else
395     int result;
396     while ((size = dv->parse_queue(dv, pkt)) == -1) {
397         iec61883_receive_task((void *)dv);
398         if (dv->receive_error)
399             return dv->receive_error;
400     }
401 #endif
402
403     return size;
404 }
405
406 static int iec61883_close(AVFormatContext *context)
407 {
408     struct iec61883_data *dv = context->priv_data;
409
410 #if THREADS
411     dv->thread_loop = 0;
412     pthread_join(dv->receive_task_thread, NULL);
413     pthread_cond_destroy(&dv->cond);
414     pthread_mutex_destroy(&dv->mutex);
415 #endif
416
417     if (dv->type == IEC61883_HDV) {
418         iec61883_mpeg2_recv_stop(dv->iec61883_mpeg2);
419         iec61883_mpeg2_close(dv->iec61883_mpeg2);
420         ff_mpegts_parse_close(dv->mpeg_demux);
421     } else {
422         iec61883_dv_fb_stop(dv->iec61883_dv);
423         iec61883_dv_fb_close(dv->iec61883_dv);
424     }
425     while (dv->queue_first) {
426         DVPacket *packet = dv->queue_first;
427         dv->queue_first = packet->next;
428         av_free(packet->buf);
429         av_free(packet);
430     }
431
432     iec61883_cmp_disconnect(dv->raw1394, dv->node, dv->output_port,
433                             raw1394_get_local_id(dv->raw1394),
434                             dv->input_port, dv->channel, dv->bandwidth);
435
436     raw1394_destroy_handle(dv->raw1394);
437
438     return 0;
439 }
440
441 static const AVOption options[] = {
442     { "dvtype", "override autodetection of DV/HDV", offsetof(struct iec61883_data, type), AV_OPT_TYPE_INT, {.i64 = IEC61883_AUTO}, IEC61883_AUTO, IEC61883_HDV, AV_OPT_FLAG_DECODING_PARAM, "dvtype" },
443     { "auto",   "auto detect DV/HDV", 0, AV_OPT_TYPE_CONST, {.i64 = IEC61883_AUTO}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "dvtype" },
444     { "dv",     "force device being treated as DV device", 0, AV_OPT_TYPE_CONST, {.i64 = IEC61883_DV},   0, 0, AV_OPT_FLAG_DECODING_PARAM, "dvtype" },
445     { "hdv" ,   "force device being treated as HDV device", 0, AV_OPT_TYPE_CONST, {.i64 = IEC61883_HDV},  0, 0, AV_OPT_FLAG_DECODING_PARAM, "dvtype" },
446     { "dvbuffer", "set queue buffer size (in packets)", offsetof(struct iec61883_data, max_packets), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
447     { NULL },
448 };
449
450 static const AVClass iec61883_class = {
451     .class_name = "iec61883 indev",
452     .item_name  = av_default_item_name,
453     .option     = options,
454     .version    = LIBAVUTIL_VERSION_INT,
455 };
456
457 AVInputFormat ff_iec61883_demuxer = {
458     .name           = "iec61883",
459     .long_name      = NULL_IF_CONFIG_SMALL("libiec61883 (new DV1394) A/V input device"),
460     .priv_data_size = sizeof(struct iec61883_data),
461     .read_header    = iec61883_read_header,
462     .read_packet    = iec61883_read_packet,
463     .read_close     = iec61883_close,
464     .flags          = AVFMT_NOFILE,
465     .priv_class     = &iec61883_class,
466 };